[
  {
    "path": ".appveyor.yml",
    "content": "version: 1.0.{build}\nimage:\n- Visual Studio 2017\ntest: off\nskip_branch_with_pr: true\nbuild:\n  parallel: true\nplatform:\n- x86\nenvironment:\n  matrix:\n  - PYTHON: 38\n    CONFIG: Debug\ninstall:\n- ps: |\n    $env:CMAKE_GENERATOR = \"Visual Studio 15 2017\"\n    if ($env:PLATFORM -eq \"x64\") { $env:PYTHON = \"$env:PYTHON-x64\" }\n    $env:PATH = \"C:\\Python$env:PYTHON\\;C:\\Python$env:PYTHON\\Scripts\\;$env:PATH\"\n    python -W ignore -m pip install --upgrade pip wheel\n    python -W ignore -m pip install pytest numpy --no-warn-script-location pytest-timeout\n- ps: |\n    Start-FileDownload 'https://gitlab.com/libeigen/eigen/-/archive/3.3.7/eigen-3.3.7.zip'\n    7z x eigen-3.3.7.zip -y > $null\n    $env:CMAKE_INCLUDE_PATH = \"eigen-3.3.7;$env:CMAKE_INCLUDE_PATH\"\nbuild_script:\n- cmake -G \"%CMAKE_GENERATOR%\" -A \"%CMAKE_ARCH%\"\n    -DCMAKE_CXX_STANDARD=14\n    -DPYBIND11_WERROR=ON\n    -DDOWNLOAD_CATCH=ON\n    -DCMAKE_SUPPRESS_REGENERATION=1\n    .\n- set MSBuildLogger=\"C:\\Program Files\\AppVeyor\\BuildAgent\\Appveyor.MSBuildLogger.dll\"\n- cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger%\n- cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger%\non_failure: if exist \"tests\\test_cmake_build\" type tests\\test_cmake_build\\*.log*\n"
  },
  {
    "path": ".clang-format",
    "content": "---\n# See all possible options and defaults with:\n# clang-format --style=llvm --dump-config\nBasedOnStyle: LLVM\nAccessModifierOffset: -4\nAllowShortLambdasOnASingleLine: true\nAlwaysBreakTemplateDeclarations: Yes\nBinPackArguments: false\nBinPackParameters: false\nBreakBeforeBinaryOperators: All\nBreakConstructorInitializers: BeforeColon\nColumnLimit: 99\nCommentPragmas: 'NOLINT:.*|^ IWYU pragma:'\nIncludeBlocks: Regroup\nIndentCaseLabels: true\nIndentPPDirectives: AfterHash\nIndentWidth: 4\nLanguage: Cpp\nSpaceAfterCStyleCast: true\nStandard: Cpp11\nStatementMacros: ['PyObject_HEAD']\nTabWidth: 4\nIncludeCategories:\n  - Regex:           '<pybind11/.*'\n    Priority:        -1\n  - Regex:           'pybind11.h\"$'\n    Priority:        1\n  - Regex:           '^\".*/?detail/'\n    Priority:        1\n    SortPriority:    2\n  - Regex:           '^\"'\n    Priority:        1\n    SortPriority:    3\n  - Regex:           '<[[:alnum:]._]+>'\n    Priority:        4\n  - Regex:           '.*'\n    Priority:        5\n...\n"
  },
  {
    "path": ".clang-tidy",
    "content": "FormatStyle: file\n\nChecks: |\n  *bugprone*,\n  *performance*,\n  clang-analyzer-optin.cplusplus.VirtualCall,\n  clang-analyzer-optin.performance.Padding,\n  cppcoreguidelines-init-variables,\n  cppcoreguidelines-prefer-member-initializer,\n  cppcoreguidelines-pro-type-static-cast-downcast,\n  cppcoreguidelines-slicing,\n  google-explicit-constructor,\n  llvm-namespace-comment,\n  misc-definitions-in-headers,\n  misc-misplaced-const,\n  misc-non-copyable-objects,\n  misc-static-assert,\n  misc-throw-by-value-catch-by-reference,\n  misc-uniqueptr-reset-release,\n  misc-unused-parameters,\n  modernize-avoid-bind,\n  modernize-loop-convert,\n  modernize-make-shared,\n  modernize-redundant-void-arg,\n  modernize-replace-auto-ptr,\n  modernize-replace-disallow-copy-and-assign-macro,\n  modernize-replace-random-shuffle,\n  modernize-shrink-to-fit,\n  modernize-use-auto,\n  modernize-use-bool-literals,\n  modernize-use-default-member-init,\n  modernize-use-emplace,\n  modernize-use-equals-default,\n  modernize-use-equals-delete,\n  modernize-use-noexcept,\n  modernize-use-nullptr,\n  modernize-use-override,\n  modernize-use-using,\n  readability-avoid-const-params-in-decls,\n  readability-braces-around-statements,\n  readability-const-return-type,\n  readability-container-size-empty,\n  readability-delete-null-pointer,\n  readability-else-after-return,\n  readability-implicit-bool-conversion,\n  readability-inconsistent-declaration-parameter-name,\n  readability-make-member-function-const,\n  readability-misplaced-array-index,\n  readability-non-const-parameter,\n  readability-qualified-auto,\n  readability-redundant-casting,\n  readability-redundant-function-ptr-dereference,\n  readability-redundant-inline-specifier,\n  readability-redundant-member-init,\n  readability-redundant-smartptr-get,\n  readability-redundant-string-cstr,\n  readability-simplify-subscript-expr,\n  readability-static-accessed-through-instance,\n  readability-static-definition-in-anonymous-namespace,\n  readability-string-compare,\n  readability-suspicious-call-argument,\n  readability-uniqueptr-delete-release,\n  -bugprone-chained-comparison,\n  -bugprone-easily-swappable-parameters,\n  -bugprone-exception-escape,\n  -bugprone-reserved-identifier,\n  -bugprone-unused-raii,\n  -performance-enum-size,\n  -performance-inefficient-string-concatenation,\n\nCheckOptions:\n- key:             modernize-use-equals-default.IgnoreMacros\n  value:           false\n- key:             performance-for-range-copy.WarnOnAllAutoCopies\n  value:           true\n- key:             performance-inefficient-string-concatenation.StrictMode\n  value:           true\n- key:             performance-unnecessary-value-param.AllowedTypes\n  value:           'exception_ptr$;'\n- key:             readability-implicit-bool-conversion.AllowPointerConditions\n  value:           true\n\nHeaderFilterRegex: 'pybind11/.*h'\n"
  },
  {
    "path": ".cmake-format.yaml",
    "content": "parse:\n  additional_commands:\n    pybind11_add_module:\n      flags:\n        - THIN_LTO\n        - MODULE\n        - SHARED\n        - NO_EXTRAS\n        - EXCLUDE_FROM_ALL\n        - SYSTEM\n\nformat:\n  line_width: 99\n  tab_size: 2\n\n  # If an argument group contains more than this many sub-groups\n  # (parg or kwarg groups) then force it to a vertical layout.\n  max_subgroups_hwrap: 2\n\n  # If a positional argument group contains more than this many\n  # arguments, then force it to a vertical layout.\n  max_pargs_hwrap: 6\n\n  # If a cmdline positional group consumes more than this many\n  # lines without nesting, then invalidate the layout (and nest)\n  max_rows_cmdline: 2\n  separate_ctrl_name_with_space: false\n  separate_fn_name_with_space: false\n  dangle_parens: false\n\n  # If the trailing parenthesis must be 'dangled' on its on\n  # 'line, then align it to this reference: `prefix`: the start'\n  # 'of the statement,  `prefix-indent`: the start of the'\n  # 'statement, plus one indentation  level, `child`: align to'\n  # the column of the arguments\n  dangle_align: prefix\n  # If the statement spelling length (including space and\n  # parenthesis) is smaller than this amount, then force reject\n  # nested layouts.\n  min_prefix_chars: 4\n\n  # If the statement spelling length (including space and\n  # parenthesis) is larger than the tab width by more than this\n  # amount, then force reject un-nested layouts.\n  max_prefix_chars: 10\n\n  # If a candidate layout is wrapped horizontally but it exceeds\n  # this many lines, then reject the layout.\n  max_lines_hwrap: 2\n\n  line_ending: unix\n\n  # Format command names consistently as 'lower' or 'upper' case\n  command_case: canonical\n\n  # Format keywords consistently as 'lower' or 'upper' case\n  # unchanged is valid too\n  keyword_case: 'upper'\n\n  # A list of command names which should always be wrapped\n  always_wrap: []\n\n  # If true, the argument lists which are known to be sortable\n  # will be sorted lexicographically\n  enable_sort: true\n\n  # If true, the parsers may infer whether or not an argument\n  # list is sortable (without annotation).\n  autosort: false\n\n# Causes a few issues - can be solved later, possibly.\nmarkup:\n  enable_markup: false\n"
  },
  {
    "path": ".codespell-ignore-lines",
    "content": "template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>\n    template <typename ThisT>\n        auto &this_ = static_cast<ThisT &>(*this);\n                if (load_impl<ThisT>(temp, false)) {\n                return load_impl<ThisT>(src, false);\n        ssize_t nd = 0;\n        auto trivial = broadcast(buffers, nd, shape);\n        auto ndim = (size_t) nd;\n    int nd;\n    ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }\n        using op = op_impl<id, ot, Base, L_type, R_type>;\ntemplate <op_id id, op_type ot, typename L, typename R>\n    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>\n    class_ &def(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {\n    class_ &def_cast(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {\n    int valu;\n    explicit movable_int(int v) : valu{v} {}\n    movable_int(movable_int &&other) noexcept : valu(other.valu) { other.valu = 91; }\n    explicit indestructible_int(int v) : valu{v} {}\n    REQUIRE(hld.as_raw_ptr_unowned<zombie>()->valu == 19);\n        REQUIRE(othr.valu == 19);\n        REQUIRE(orig.valu == 91);\n        (m.pass_valu, \"Valu\", \"pass_valu:Valu(_MvCtor)*_CpCtor\"),\natyp_valu        rtrn_valu() { atyp_valu obj{\"Valu\"}; return obj; }\n    assert m.atyp_valu().get_mtxt() == \"Valu\"\n// valu(e), ref(erence), ptr or p (pointer), r = rvalue, m = mutable, c = const,\n@pytest.mark.parametrize(\"access\", [\"ro\", \"rw\", \"static_ro\", \"static_rw\"])\nstruct IntStruct {\n    explicit IntStruct(int v) : value(v){};\n    ~IntStruct() { value = -value; }\n    IntStruct(const IntStruct &) = default;\n    IntStruct &operator=(const IntStruct &) = default;\n    py::class_<IntStruct>(m, \"IntStruct\").def(py::init([](const int i) { return IntStruct(i); }));\n    py::implicitly_convertible<int, IntStruct>();\n    m.def(\"test\", [](int expected, const IntStruct &in) {\n        [](int expected, const IntStruct &in) {\n"
  },
  {
    "path": ".gitattributes",
    "content": "docs/*.svg binary\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "*.cmake @henryiii\nCMakeLists.txt @henryiii\n*.yml @henryiii\n*.yaml @henryiii\n/tools/ @henryiii\n/pybind11/ @henryiii\nnoxfile.py @henryiii\n.clang-format @henryiii\n.clang-tidy @henryiii\n"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "Thank you for your interest in this project! Please refer to the following\nsections on how to contribute code and bug reports.\n\n### Reporting bugs\n\nBefore submitting a question or bug report, please take a moment of your time\nand ensure that your issue isn't already discussed in the project documentation\nprovided at [pybind11.readthedocs.org][] or in the [issue tracker][]. You can\nalso check [gitter][] to see if it came up before.\n\nAssuming that you have identified a previously unknown problem or an important\nquestion, it's essential that you submit a self-contained and minimal piece of\ncode that reproduces the problem. In other words: no external dependencies,\nisolate the function(s) that cause breakage, submit matched and complete C++\nand Python snippets that can be easily compiled and run in isolation; or\nideally make a small PR with a failing test case that can be used as a starting\npoint.\n\n## Pull requests\n\nContributions are submitted, reviewed, and accepted using GitHub pull requests.\nPlease refer to [this article][using pull requests] for details and adhere to\nthe following rules to make the process as smooth as possible:\n\n* Make a new branch for every feature you're working on.\n* Make small and clean pull requests that are easy to review but make sure they\n  do add value by themselves.\n* Add tests for any new functionality and run the test suite (`cmake --workflow\n  venv`) to ensure that no existing features break.\n* Please run [`pre-commit`][pre-commit] to check your code matches the\n  project style. (Note that `gawk` is required.) Use `pre-commit run\n  --all-files` before committing (or use installed-mode, check pre-commit docs)\n  to verify your code passes before pushing to save time.\n* This project has a strong focus on providing general solutions using a\n  minimal amount of code, thus small pull requests are greatly preferred.\n\n### Licensing of contributions\n\npybind11 is provided under a BSD-style license that can be found in the\n``LICENSE`` file. By using, distributing, or contributing to this project, you\nagree to the terms and conditions of this license.\n\nYou are under no obligation whatsoever to provide any bug fixes, patches, or\nupgrades to the features, functionality or performance of the source code\n(\"Enhancements\") to anyone; however, if you choose to make your Enhancements\navailable either publicly, or directly to the author of this software, without\nimposing a separate written license agreement for such Enhancements, then you\nhereby grant the following license: a non-exclusive, royalty-free perpetual\nlicense to install, use, modify, prepare derivative works, incorporate into\nother computer software, distribute, and sublicense such enhancements or\nderivative works thereof, in binary and source code form.\n\n\n## Development of pybind11\n\n### Quick setup\n\nTo setup a quick development environment, use [`nox`](https://nox.thea.codes).\nThis will allow you to do some common tasks with minimal setup effort, but will\ntake more time to run and be less flexible than a full development environment.\nIf you use [`pipx run nox`](https://pipx.pypa.io), you don't even need to\ninstall `nox`. Examples:\n\n```bash\n# List all available sessions\nnox -l\n\n# Run linters\nnox -s lint\n\n# Run tests on Python 3.9\nnox -s tests-3.9\n\n# Build and preview docs\nnox -s docs -- serve\n\n# Build SDists and wheels\nnox -s build\n```\n\n### Full setup\n\nTo setup an ideal development environment, run the following commands on a\nsystem with CMake 3.15+:\n\n```bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r tests/requirements.txt\ncmake -S . -B build -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON\ncmake --build build -j4\n```\n\nTips:\n\n* You can use `virtualenv` (faster, from PyPI) instead of `venv`.\n* You can select any name for your environment folder; if it contains \"env\" it\n  will be ignored by git.\n* If you don't have CMake 3.15+, just add \"cmake\" to the pip install command.\n* You can use `-DPYBIND11_FINDPYTHON=ON` to use FindPython.\n* For a specific Python, you can use `-DPython_ROOT_DIR=/path/to` or\n  `-DPython_EXECUTABLE=/path/to/python`.\n\n## CMake presets\n\nWe also support CMake presets. If you have [uv](https://docs.astral.sh/uv/),\nyou can use:\n\n```bash\ncmake --workflow venv\n```\n\nto setup a venv and run all tests. You can break this up into components\nif you want to use a specific version of Python (or any other config option) or\nbuild only one of the valid targets (listed below).\n\n```bash\ncmake --preset venv -DPYBIND11_CREATE_WITH_UV=3.13t\ncmake --build --preset venv\ncmake --build --preset venv -t cpptest\n```\n\nThe `default` preset will use an existing venv or Python install. If you'd like\nto run pytest yourself, say to easily control the options:\n\n```bash\ncd build\nsource .venv/bin/activate\ncd tests\npython -m pytest\n```\n\nThe `.so` file is not installed into the venv, so you need to run from this\ndirectory, the local directory is included with `python -m`.\n\n## Configuration options\n\nIn CMake, configuration options are given with \"-D\". Options are stored in the\nbuild directory, in the `CMakeCache.txt` file, so they are remembered for each\nbuild directory. Two selections are special - the generator, given with `-G`,\nand the compiler, which is selected based on environment variables `CXX` and\nsimilar, or `-DCMAKE_CXX_COMPILER=`. Unlike the others, these cannot be changed\nafter the initial run.\n\nThe valid options are:\n\n* `-DCMAKE_BUILD_TYPE`: Release, Debug, MinSizeRel, RelWithDebInfo\n* `-DPYBIND11_FINDPYTHON=ON`: Use CMake 3.12+'s FindPython instead of the\n  classic, deprecated, custom FindPythonLibs\n* `-DPYBIND11_NOPYTHON=ON`: Disable all Python searching (disables tests)\n* `-DBUILD_TESTING=ON`: Enable the tests\n* `-DDOWNLOAD_CATCH=ON`: Download catch to build the C++ tests\n* `-DDOWNLOAD_EIGEN=ON`: Download Eigen for the NumPy tests\n* `-DPYBIND11_INSTALL=ON/OFF`: Enable the install target (on by default for the\n  master project)\n* `-DUSE_PYTHON_INSTALL_DIR=ON`: Try to install into the python dir\n\n\n<details><summary>A few standard CMake tricks: (click to expand)</summary><p>\n\n* Use `cmake --build build -v` to see the commands used to build the files.\n* Use `cmake build -LH` to list the CMake options with help.\n* Use `ccmake` if available to see a curses (terminal) gui, or `cmake-gui` for\n  a completely graphical interface (not present in the PyPI package).\n* Use `cmake --build build -j12` to build with 12 cores (for example).\n* Use `-G` and the name of a generator to use something different. `cmake\n  --help` lists the generators available.\n      - On Unix, setting `CMAKE_GENERATOR=Ninja` in your environment will give\n        you automatic multithreading on all your CMake projects!\n* Open the `CMakeLists.txt` with QtCreator to generate for that IDE.\n* You can use `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to generate the `.json` file\n  that some tools expect.\n\n</p></details>\n\n\nTo run the tests, you can \"build\" the check target:\n\n```bash\ncmake --build build --target check\n```\n\n`--target` can be spelled `-t`. You can also run individual tests with these\ntargets:\n\n* `pytest`: Python tests only, using the\n[pytest](https://docs.pytest.org/en/stable/) framework\n* `cpptest`: C++ tests only\n* `test_cmake_build`: Install / subdirectory tests\n\nIf you want to build just a subset of tests, use\n`-DPYBIND11_TEST_OVERRIDE=\"test_callbacks;test_pickling\"`. If this is\nempty, all tests will be built. Tests are specified without an extension if they need both a .py and\n.cpp file.\n\nYou may also pass flags to the `pytest` target by editing `tests/pytest.ini` or\nby using the `PYTEST_ADDOPTS` environment variable\n(see [`pytest` docs](https://docs.pytest.org/en/2.7.3/customize.html#adding-default-options)). As an example:\n\n```bash\nenv PYTEST_ADDOPTS=\"--capture=no --exitfirst\" \\\n    cmake --build build --target pytest\n# Or using abbreviated flags\nenv PYTEST_ADDOPTS=\"-s -x\" cmake --build build --target pytest\n```\n\n### Formatting\n\nAll formatting is handled by pre-commit.\n\nInstall with brew (macOS) or pip (any OS):\n\n```bash\n# Any OS\npython3 -m pip install pre-commit\n\n# OR macOS with homebrew:\nbrew install pre-commit\n```\n\nThen, you can run it on the items you've added to your staging area, or all\nfiles:\n\n```bash\npre-commit run\n# OR\npre-commit run --all-files\n```\n\nAnd, if you want to always use it, you can install it as a git hook (hence the\nname, pre-commit):\n\n```bash\npre-commit install\n```\n\n### Clang-Format\n\nAs of v2.6.2, pybind11 ships with a [`clang-format`][clang-format]\nconfiguration file at the top level of the repo (the filename is\n`.clang-format`). Currently, formatting is NOT applied automatically, but\nmanually using `clang-format` for newly developed files is highly encouraged.\nTo check if a file needs formatting:\n\n```bash\nclang-format -style=file --dry-run some.cpp\n```\n\nThe output will show things to be fixed, if any. To actually format the file:\n\n```bash\nclang-format -style=file -i some.cpp\n```\n\nNote that the `-style-file` option searches the parent directories for the\n`.clang-format` file, i.e. the commands above can be run in any subdirectory\nof the pybind11 repo.\n\n### Clang-Tidy\n\n[`clang-tidy`][clang-tidy] performs deeper static code analyses and is\nmore complex to run, compared to `clang-format`, but support for `clang-tidy`\nis built into the pybind11 CMake configuration. To run `clang-tidy`, the\nfollowing recipe should work. Run the `docker` command from the top-level\ndirectory inside your pybind11 git clone.\n\n```bash\ndocker run --rm -v $PWD:/pybind11 -w /pybind11 -it silkeh/clang:20\napt-get update && apt-get install -y git python3-dev python3-pytest ninja-build\ncmake --preset tidy\ncmake --build --preset tidy\n```\n\nYou can add `--fix` to the options list in the preset if you want to apply fixes\n(remember `-j1` to run only one thread).\n\n### Include what you use\n\nTo run include what you use, install (`brew install include-what-you-use` on\nmacOS), then run:\n\n```bash\ncmake -S . -B build-iwyu -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=$(which include-what-you-use)\ncmake --build build-iwyu\n```\n\nThe report is sent to stderr; you can pipe it into a file if you wish.\n\n### Build recipes\n\nThis builds with the Intel compiler (assuming it is in your path, along with a\nrecent CMake and Python):\n\n```bash\npython3 -m venv venv\n. venv/bin/activate\npip install pytest\ncmake -S . -B build-intel -DCMAKE_CXX_COMPILER=$(which icpc) -DDOWNLOAD_CATCH=ON -DDOWNLOAD_EIGEN=ON -DPYBIND11_WERROR=ON\n```\n\nThis will test the PGI compilers:\n\n```bash\ndocker run --rm -it -v $PWD:/pybind11 nvcr.io/hpc/pgi-compilers:ce\napt-get update && apt-get install -y python3-dev python3-pip python3-pytest\nwget -qO- \"https://cmake.org/files/v3.18/cmake-3.18.2-Linux-x86_64.tar.gz\" | tar --strip-components=1 -xz -C /usr/local\ncmake -S pybind11/ -B build\ncmake --build build\n```\n\n### Explanation of the SDist/wheel building design\n\n> These details below are _only_ for packaging the Python sources from git. The\n> SDists and wheels created do not have any extra requirements at all and are\n> completely normal.\n\nThe main objective of the packaging system is to create SDists (Python's source\ndistribution packages) and wheels (Python's binary distribution packages) that\ninclude everything that is needed to work with pybind11, and which can be\ninstalled without any additional dependencies. This is more complex than it\nappears: in order to support CMake as a first class language even when using\nthe PyPI package, they must include the _generated_ CMake files (so as not to\nrequire CMake when installing the `pybind11` package itself). They should also\nprovide the option to install to the \"standard\" location\n(`<ENVROOT>/include/pybind11` and `<ENVROOT>/share/cmake/pybind11`) so they are\neasy to find with CMake, but this can cause problems if you are not an\nenvironment or using ``pyproject.toml`` requirements. This was solved by having\ntwo packages; the \"nice\" pybind11 package that stores the includes and CMake\nfiles inside the package, that you get access to via functions in the package,\nand a `pybind11-global` package that can be included via `pybind11[global]` if\nyou want the more invasive but discoverable file locations.\n\nIf you want to package the GitHub source for the \"global\" package, you need\nto use nox. Normal packaging will only make the normal package.\n\n\n```bash\nnox -s build\nnox -s build_global\n```\n\n\n[pre-commit]: https://pre-commit.com\n[clang-format]: https://clang.llvm.org/docs/ClangFormat.html\n[clang-tidy]: https://clang.llvm.org/extra/clang-tidy/\n[pybind11.readthedocs.org]: http://pybind11.readthedocs.org/en/latest\n[issue tracker]: https://github.com/pybind/pybind11/issues\n[gitter]: https://gitter.im/pybind/Lobby\n[using pull requests]: https://help.github.com/articles/using-pull-requests\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "content": "name: Bug Report\ndescription: File an issue about a bug\ntitle: \"[BUG]: \"\nlabels: [triage]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Please do your best to make the issue as easy to act on as possible, and only submit here if there is clearly a problem with pybind11 (ask first if unsure). **Note that a reproducer in a PR is much more likely to get immediate attention.**\n\n  - type: checkboxes\n    id: steps\n    attributes:\n      label: Required prerequisites\n      description: Make sure you've completed the following steps before submitting your issue -- thank you!\n      options:\n        - label: Make sure you've read the [documentation](https://pybind11.readthedocs.io). Your issue may be addressed there.\n          required: true\n        - label: Search the [issue tracker](https://github.com/pybind/pybind11/issues) and [Discussions](https:/pybind/pybind11/discussions) to verify that this hasn't already been reported. +1 or comment there if it has.\n          required: true\n        - label: Consider asking first in the [Gitter chat room](https://gitter.im/pybind/Lobby) or in a [Discussion](https:/pybind/pybind11/discussions/new).\n          required: false\n\n  - type: input\n    id: version\n    attributes:\n      label: What version (or hash if on master) of pybind11 are you using?\n    validations:\n      required: true\n\n  - type: textarea\n    id: description\n    attributes:\n      label: Problem description\n      placeholder: >-\n        Provide a short description, state the expected behavior and what\n        actually happens. Include relevant information like what version of\n        pybind11 you are using, what system you are on, and any useful commands\n        / output.\n    validations:\n      required: true\n\n  - type: textarea\n    id: code\n    attributes:\n      label: Reproducible example code\n      placeholder: >-\n        The code should be minimal, have no external dependencies, isolate the\n        function(s) that cause breakage. Submit matched and complete C++ and\n        Python snippets that can be easily compiled and run to diagnose the\n        issue. — Note that a reproducer in a PR is much more likely to get\n        immediate attention: failing tests in the pybind11 CI are the best\n        starting point for working out fixes.\n      render: text\n\n  - type: input\n    id: regression\n    attributes:\n      label: Is this a regression? Put the last known working version here if it is.\n      description: Put the last known working version here if this is a regression.\n      value: Not a regression\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Ask a question\n    url: https://github.com/pybind/pybind11/discussions/new\n    about: Please ask and answer questions here, or propose new ideas.\n  - name: Gitter room\n    url: https://gitter.im/pybind/Lobby\n    about: A room for discussing pybind11 with an active community\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  # Maintain dependencies for GitHub Actions\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"monthly\"\n    groups:\n      actions:\n        patterns:\n          - \"*\"\n"
  },
  {
    "path": ".github/labeler.yml",
    "content": "docs:\n  all:\n    - changed-files:\n      - all-globs-to-all-files:\n        - '!docs/changelog.md'\n        - '!docs/upgrade.rst'\n    - base-branch: \"^(?!dependabot).*\"\n    - base-branch: \"^(?!pre-commit-ci).*\"\n\nci:\n  - changed-files:\n    - any-glob-to-any-file:\n      - '.github/workflows/*.yml'\n"
  },
  {
    "path": ".github/labeler_merged.yml",
    "content": "# Add 'needs changelog` label to any change to code files as long as the `CHANGELOG` hasn't changed\n# Skip dependabot and pre-commit-ci PRs\nneeds changelog:\n  - all:\n      - changed-files:\n          - all-globs-to-all-files: \"!docs/changelog.md\"\n      - base-branch: \"^(?!dependabot).*\"\n      - base-branch: \"^(?!pre-commit-ci).*\"\n"
  },
  {
    "path": ".github/matchers/pylint.json",
    "content": "{\n  \"problemMatcher\": [\n    {\n      \"severity\": \"warning\",\n      \"pattern\": [\n        {\n          \"regexp\": \"^([^:]+):(\\\\d+):(\\\\d+): ([A-DF-Z]\\\\d+): \\\\033\\\\[[\\\\d;]+m([^\\\\033]+).*$\",\n          \"file\": 1,\n          \"line\": 2,\n          \"column\": 3,\n          \"code\": 4,\n          \"message\": 5\n        }\n      ],\n      \"owner\": \"pylint-warning\"\n    },\n    {\n      \"severity\": \"error\",\n      \"pattern\": [\n        {\n          \"regexp\": \"^([^:]+):(\\\\d+):(\\\\d+): (E\\\\d+): \\\\033\\\\[[\\\\d;]+m([^\\\\033]+).*$\",\n          \"file\": 1,\n          \"line\": 2,\n          \"column\": 3,\n          \"code\": 4,\n          \"message\": 5\n        }\n      ],\n      \"owner\": \"pylint-error\"\n    }\n  ]\n}\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "<!--\nTitle (above): please place [branch_name] at the beginning if you are targeting a branch other than master. *Do not target stable*.\nIt is recommended to use conventional commit format, see conventionalcommits.org, but not required.\n-->\n## Description\n\n<!-- Include relevant issues or PRs here, describe what changed and why -->\n\n\n## Suggested changelog entry:\n\n<!-- Fill in the block below with the expected entry. Delete if no entry needed;\n     but do not delete the header if an entry is needed! Will be collected via a script. -->\n\n* Placeholder.\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  workflow_dispatch:\n  pull_request:\n    types:\n      - opened\n      - synchronize\n      - reopened\n      - ready_for_review\n\npermissions: read-all\n\nconcurrency:\n  group: test-${{ github.ref }}\n  cancel-in-progress: true\n\nenv:\n  PYTHONDEVMODE: 1\n  PIP_BREAK_SYSTEM_PACKAGES: 1\n  PIP_ONLY_BINARY: numpy\n  FORCE_COLOR: 3\n  PYTEST_TIMEOUT: 300\n  # For cmake:\n  VERBOSE: 1\n  CMAKE_COLOR_DIAGNOSTICS: 1\n\njobs:\n  # This is the \"main\" test suite, which tests a large number of different\n  # versions of default compilers and Python versions in GitHub Actions.\n  # It is in two parts: one that always runs, and one that runs on non-draft\n  standard-small:\n    if: github.event.action != 'ready_for_review'\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - runs-on: ubuntu-22.04\n            python-version: '3.8'\n            cmake-args: -DPYBIND11_FINDPYTHON=OFF -DPYBIND11_NUMPY_1_ONLY=ON\n          - runs-on: ubuntu-latest\n            python-version: '3.13'\n            cmake-args: -DCMAKE_CXX_STANDARD=23 -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON\n          - runs-on: ubuntu-latest\n            python-version: '3.14t'\n            cmake-args: -DCMAKE_CXX_STANDARD=17 -DPYBIND11_TEST_SMART_HOLDER=ON\n          - runs-on: ubuntu-latest\n            python-version: 'pypy3.11'\n            cmake-args: -DCMAKE_CXX_STANDARD=17\n          - runs-on: ubuntu-latest\n            python-version: 'graalpy-24.2'\n            cmake-args: -DCMAKE_CXX_STANDARD=20\n          - runs-on: macos-latest\n            python-version: '3.14'\n            cmake-args: -DCMAKE_CXX_STANDARD=14\n          - runs-on: windows-2022\n            python-version: '3.8'\n            cmake-args: -DPYBIND11_FINDPYTHON=OFF\n\n\n    name: 🐍\n    uses: ./.github/workflows/reusable-standard.yml\n    with:\n      runs-on: ${{ matrix.runs-on }}\n      python-version: ${{ matrix.python-version }}\n      cmake-args: ${{ matrix.cmake-args }}\n\n  standard-large:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - runs-on: ubuntu-latest\n            python-version: '3.8'\n            cmake-args: -DPYBIND11_FINDPYTHON=ON -DCMAKE_CXX_STANDARD=17\n          - runs-on: ubuntu-latest\n            python-version: '3.10'\n            cmake-args: -DCMAKE_CXX_STANDARD=20\n          - runs-on: ubuntu-latest\n            python-version: '3.11'\n            cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DCMAKE_CXX_STANDARD=17\n          - runs-on: ubuntu-latest\n            python-version: '3.12'\n            cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON\n          - runs-on: ubuntu-latest\n            python-version: '3.14t'\n            cmake-args: -DCMAKE_CXX_STANDARD=20 -DPYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION=ON\n          - runs-on: ubuntu-latest\n            python-version: '3.14'\n            cmake-args: -DCMAKE_CXX_STANDARD=14\n          - runs-on: ubuntu-latest\n            python-version: 'pypy-3.10'\n            cmake-args: -DCMAKE_CXX_STANDARD=14\n          - runs-on: ubuntu-latest\n            python-version: 'graalpy-24.1'\n\n          # No SciPy for macOS ARM\n          - runs-on: macos-15-intel\n            python-version: '3.8'\n            cmake-args: -DCMAKE_CXX_STANDARD=14\n          - runs-on: macos-15-intel\n            python-version: '3.11'\n            cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON\n          - runs-on: macos-15-intel\n            python-version: '3.13'\n            cmake-args: -DCMAKE_CXX_STANDARD=11\n          - runs-on: macos-latest\n            python-version: '3.12'\n            cmake-args: -DCMAKE_CXX_STANDARD=17 -DPYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION=ON\n          - runs-on: macos-latest\n            python-version: '3.14t'\n            cmake-args: -DCMAKE_CXX_STANDARD=20\n          - runs-on: macos-15-intel\n            python-version: 'pypy-3.10'\n            cmake-args: -DCMAKE_CXX_STANDARD=17\n          - runs-on: macos-latest\n            python-version: 'pypy-3.11'\n          - runs-on: macos-latest\n            python-version: 'graalpy-24.2'\n\n          - runs-on: windows-latest\n            python-version: '3.9'\n            cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON\n          - runs-on: windows-2022\n            python-version: '3.8'\n            cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DPYBIND11_NUMPY_1_ONLY=ON\n          - runs-on: windows-2022\n            python-version: '3.9'\n            cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL -DCMAKE_CXX_STANDARD=14\n          # This needs a python built with MTd\n          # - runs-on: windows-2022\n          #   python-version: '3.11'\n          #   cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebug\n          - runs-on: windows-2022\n            python-version: '3.10'\n            cmake-args: -DPYBIND11_TEST_SMART_HOLDER=ON -DCMAKE_CXX_FLAGS=\"/GR /EHsc\"\n          - runs-on: windows-2022\n            python-version: '3.13'\n            cmake-args: -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebugDLL\n          - runs-on: windows-latest\n            python-version: '3.14'\n            cmake-args: -DCMAKE_CXX_STANDARD=20\n          - runs-on: windows-latest\n            python-version: '3.14t'\n            cmake-args: -DCMAKE_CXX_STANDARD=23\n          - runs-on: windows-latest\n            python-version: 'pypy-3.10'\n            cmake-args: -DCMAKE_CXX_STANDARD=17\n          - runs-on: windows-latest\n            python-version: 'pypy3.11'\n            cmake-args: -DCMAKE_CXX_STANDARD=20\n          # The setup-python action currently doesn't have graalpy for windows\n          # See https://github.com/actions/setup-python/pull/880\n\n    name: 🐍\n    uses: ./.github/workflows/reusable-standard.yml\n    with:\n      runs-on: ${{ matrix.runs-on }}\n      python-version: ${{ matrix.python-version }}\n      cmake-args: ${{ matrix.cmake-args }}\n\n  # This checks inplace builds with C++11\n  inplace:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - runs-on: ubuntu-latest\n            python-version: '3.9'\n          - runs-on: macos-latest\n            python-version: '3.12'\n          - runs-on: windows-latest\n            python-version: '3.11'\n\n    name: \"🐍 ${{ matrix.python-version }} • ${{ matrix.runs-on }} • x64 inplace C++14\"\n    runs-on: ${{ matrix.runs-on }}\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python-version }}\n        allow-prereleases: true\n\n    - name: Install uv\n      uses: astral-sh/setup-uv@v7\n      with:\n        enable-cache: true\n\n    - name: Prepare env\n      run: uv pip install --python=python --system -r tests/requirements.txt\n\n    # TODO Resolve Windows Ninja shared object issue on Python 3.8+\n    - name: Use Ninja except on Windows\n      if: runner.os != 'Windows'\n      run: echo \"CMAKE_GENERATOR=Ninja\" >> \"$GITHUB_ENV\"\n\n    # More-or-less randomly adding a few extra flags here.\n    # In particular, use this one to test the next ABI bump (internals version).\n    - name: Configure\n      run: >\n        cmake -S. -B.\n        -DPYBIND11_WERROR=ON\n        -DPYBIND11_SIMPLE_GIL_MANAGEMENT=ON\n        -DPYBIND11_PYTEST_ARGS=-v\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=14\n        -DPYBIND11_INTERNALS_VERSION=10000000\n\n    # Checks to makes sure defining `_` is allowed\n    # Triggers EHsc missing error on Windows\n    - name: Add underscore check\n      if: runner.os != 'Windows'\n      run: cmake -S. -B. -DCMAKE_CXX_FLAGS=\"-D_=1\"\n\n    - name: Build\n      run: cmake --build .\n\n    - name: Python tests\n      run: cmake --build . --target pytest\n\n    - name: Compiled tests\n      timeout-minutes: 3\n      run: cmake --build . --target cpptest\n\n    - name: Interface test\n      run: cmake --build . --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build . --target test_cross_module_rtti\n\n\n  manylinux:\n    name: Manylinux on 🐍 ${{ matrix.python-version }} (${{ matrix.container }})\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - container: quay.io/pypa/manylinux_2_28_x86_64:latest\n            python-version: '3.13t'\n          - container: quay.io/pypa/musllinux_1_2_x86_64:latest\n            python-version: '3.13t'\n          - container: quay.io/pypa/manylinux_2_28_x86_64:latest\n            python-version: '3.14t'\n          - container: quay.io/pypa/musllinux_1_2_x86_64:latest\n            python-version: '3.14t'\n    runs-on: ubuntu-latest\n    timeout-minutes: 40\n    container: ${{ matrix.container }}\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Prepare uv's path\n        run: echo \"$HOME/.local/bin\" >> $GITHUB_PATH\n\n      - name: Install ninja\n        run: uv tool install ninja\n\n      - name: Configure via preset\n        run: cmake --preset venv -DPYBIND11_CREATE_WITH_UV=\"${{ matrix.python-version }}\"\n\n      - name: Build C++11\n        run: cmake --build --preset venv\n\n      - name: Python tests C++11\n        run: cmake --build --preset testsvenv -t pytest\n\n  deadsnakes:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n        # TODO: Fails on 3.10, investigate\n        # JOB DISABLED (NEEDS WORK): https://github.com/pybind/pybind11/issues/4889\n        # - python-version: \"3.9\"\n        #   python-debug: true\n        #   valgrind: true\n        - python-version: \"3.11\"\n          python-debug: false\n\n    name: \"🐍 ${{ matrix.python-version }}${{ matrix.python-debug && '-dbg' || '' }} (deadsnakes)${{ matrix.valgrind && ' • Valgrind' || '' }} • x64\"\n    runs-on: ubuntu-latest\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python ${{ matrix.python-version }} (deadsnakes)\n      uses: deadsnakes/action@v3.2.0\n      with:\n        python-version: ${{ matrix.python-version }}\n        debug: ${{ matrix.python-debug }}\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Valgrind cache\n      if: matrix.valgrind\n      uses: actions/cache@v5\n      id: cache-valgrind\n      with:\n        path: valgrind\n        key: 3.16.1 # Valgrind version\n\n    - name: Compile Valgrind\n      if: matrix.valgrind && steps.cache-valgrind.outputs.cache-hit != 'true'\n      run: |\n        VALGRIND_VERSION=3.16.1\n        curl https://sourceware.org/pub/valgrind/valgrind-$VALGRIND_VERSION.tar.bz2 -o - | tar xj\n        mv valgrind-$VALGRIND_VERSION valgrind\n        cd valgrind\n        ./configure\n        make -j 2 > /dev/null\n\n    - name: Install Valgrind\n      if: matrix.valgrind\n      working-directory: valgrind\n      run: |\n        sudo make install\n        sudo apt-get update\n        sudo apt-get install ninja-build libc6-dbg\n\n    - name: Prepare env\n      run: |\n        python -m pip install -r tests/requirements.txt\n\n    - name: Configure\n      run: cmake --preset default -DCMAKE_CXX_STANDARD=17\n\n    - name: Build\n      run: cmake --build --preset default\n\n    - name: Python tests\n      run: cmake --build --preset default --target pytest\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: cmake --build --preset default --target cpptest\n\n    - name: Visibility test\n      run: cmake --build --preset default --target test_cross_module_rtti\n\n    - name: Run Valgrind on Python tests\n      if: matrix.valgrind\n      run: cmake --build --preset default --target memcheck\n\n\n  # Testing on clang using the excellent silkeh clang docker images\n  clang:\n    if: github.event.pull_request.draft == false\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - clang: 5\n            std: 14\n          - clang: 11\n            std: 20\n          - clang: 14\n            std: 20\n          - clang: 16\n            std: 20\n            container_suffix: \"-bullseye\"\n          - clang: 18\n            std: 20\n            cxx_flags: \"-Werror -Wall -Wextra -Wwrite-strings -Wunreachable-code -Wpointer-arith -Wredundant-decls\"\n            container_suffix: \"-bookworm\"\n\n    name: \"🐍 3 • Clang ${{ matrix.clang }} • C++${{ matrix.std }} • x64${{ matrix.cxx_flags && ' • cxx_flags' || '' }}\"\n    container: \"silkeh/clang:${{ matrix.clang }}${{ matrix.container_suffix }}\"\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Add wget and python3\n      run: apt-get update && apt-get install -y python3-dev python3-numpy python3-pytest libeigen3-dev\n\n    - name: Configure\n      shell: bash\n      run: >\n        cmake -S . -B build\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DCMAKE_CXX_STANDARD=${{ matrix.std }}\n        -DCMAKE_CXX_FLAGS=\"${{ matrix.cxx_flags }}\"\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Build\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: cmake --build build --target cpptest\n\n    - name: Interface test\n      run: cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti\n\n  # Testing NVCC; forces sources to behave like .cu files\n  cuda:\n    runs-on: ubuntu-latest\n    name: \"🐍 3.10 • CUDA 12.2 • Ubuntu 22.04\"\n    container: nvidia/cuda:12.2.0-devel-ubuntu22.04\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    # tzdata will try to ask for the timezone, so set the DEBIAN_FRONTEND\n    - name: Install 🐍 3\n      run: apt-get update && DEBIAN_FRONTEND=\"noninteractive\" apt-get install -y cmake git python3-dev python3-pytest python3-numpy\n\n    - name: Configure\n      run: cmake -S . -B build -DPYBIND11_CUDA_TESTS=ON -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON\n\n    - name: Build\n      run: cmake --build build -j2 --verbose\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n\n# TODO: Internal compiler error - report to NVidia\n#  # Testing CentOS 8 + PGI compilers\n#  centos-nvhpc8:\n#    runs-on: ubuntu-latest\n#    name: \"🐍 3 • CentOS8 / PGI 20.11 • x64\"\n#    container: centos:8\n#\n#    steps:\n#    - uses: actions/checkout@v6\n#\n#    - name: Add Python 3 and a few requirements\n#      run: yum update -y && yum install -y git python3-devel python3-numpy python3-pytest make environment-modules\n#\n#    - name: Install CMake with pip\n#      run: |\n#        python3 -m pip install --upgrade pip\n#        python3 -m pip install cmake --prefer-binary\n#\n#    - name: Install NVidia HPC SDK\n#      run: >\n#        yum -y install\n#        https://developer.download.nvidia.com/hpc-sdk/20.11/nvhpc-20-11-20.11-1.x86_64.rpm\n#        https://developer.download.nvidia.com/hpc-sdk/20.11/nvhpc-2020-20.11-1.x86_64.rpm\n#\n#    - name: Configure\n#      shell: bash\n#      run: |\n#        source /etc/profile.d/modules.sh\n#        module load /opt/nvidia/hpc_sdk/modulefiles/nvhpc/20.11\n#        cmake -S . -B build -DDOWNLOAD_CATCH=ON -DCMAKE_CXX_STANDARD=14 -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n#\n#    - name: Build\n#      run: cmake --build build -j 2 --verbose\n#\n#    - name: Python tests\n#      run: cmake --build build --target pytest\n#\n#    - name: C++ tests\n#      run: cmake --build build --target cpptest\n#\n#    - name: Interface test\n#      run: cmake --build build --target test_cmake_build\n\n\n  # Testing on Ubuntu + NVHPC (previous PGI) compilers, which seems to require more workarounds\n  ubuntu-nvhpc:\n    if: github.event.pull_request.draft == false\n    runs-on: ubuntu-24.04\n    name: \"🐍 3 • NVHPC 25.11 • C++17 • x64\"\n    timeout-minutes: 90\n\n    env:\n      # tzdata will try to ask for the timezone, so set the DEBIAN_FRONTEND\n      DEBIAN_FRONTEND: 'noninteractive'\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Clean out unused stuff to save space\n      run: |\n        sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /opt/hostedtoolcache/CodeQL\n        sudo apt-get clean\n\n    - name: Add NVHPC Repo\n      run: |\n        echo 'deb [trusted=yes] https://developer.download.nvidia.com/hpc-sdk/ubuntu/amd64 /' | \\\n          sudo tee /etc/apt/sources.list.d/nvhpc.list\n\n    - name: Install 🐍 3 & NVHPC\n      run: |\n        sudo apt-get update -y\n        sudo apt-get install -y cmake environment-modules git python3-dev python3-pip python3-numpy\n        sudo apt-get install -y --no-install-recommends nvhpc-25-11\n        sudo rm -rf /var/lib/apt/lists/*\n        apt-cache depends nvhpc-25-11\n        python3 -m pip install --upgrade pip\n        python3 -m pip install --upgrade pytest\n\n    # On some systems, you many need further workarounds:\n    # https://github.com/pybind/pybind11/pull/2475\n    - name: Configure\n      shell: bash\n      run: |\n        source /etc/profile.d/modules.sh\n        module load /opt/nvidia/hpc_sdk/modulefiles/nvhpc/25.11\n        cmake -S . -B build -DDOWNLOAD_CATCH=ON \\\n                            -DCMAKE_CXX_STANDARD=17 \\\n                            -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\") \\\n                            -DCMAKE_CXX_FLAGS=\"-Wc,--pending_instantiations=0\" \\\n                            -DPYBIND11_TEST_FILTER=\"test_smart_ptr.cpp\"\n\n    - name: Build\n      run: cmake --build build -j $(nproc) --verbose\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: cmake --build build --target cpptest\n\n    - name: Interface test\n      run: cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti\n\n  # Testing on GCC using the GCC docker images (only recent images supported)\n  gcc:\n    if: github.event.pull_request.draft == false\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - { gcc: 9, std: 20 }\n          - { gcc: 10, std: 17 }\n          - { gcc: 10, std: 20 }\n          - { gcc: 13, std: 20, cxx_flags: \"-Wall -Wextra -Wwrite-strings -Wunreachable-code -Wpointer-arith -Wredundant-decls\" }\n\n    name: \"🐍 3 • GCC ${{ matrix.gcc }} • C++${{ matrix.std }} • x64${{ matrix.cxx_flags && ' • cxx_flags' || '' }}\"\n    container: \"gcc:${{ matrix.gcc }}\"\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Add Python 3\n      run: apt-get update; apt-get install -y python3-dev python3-numpy python3-pytest python3-pip libeigen3-dev\n\n    - name: Update pip\n      run: python3 -m pip install --upgrade pip\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Configure\n      shell: bash\n      run: >\n        cmake -S . -B build\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DCMAKE_CXX_STANDARD=${{ matrix.std }}\n        -DCMAKE_CXX_FLAGS=\"${{ matrix.cxx_flags }}\"\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Build\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: cmake --build build --target cpptest\n\n    - name: Interface test\n      run: cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti\n\n    - name: Configure - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      if: matrix.gcc == '12'\n      shell: bash\n      run: >\n        cmake -S . -B build_partial\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DCMAKE_CXX_STANDARD=${{ matrix.std }}\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n        \"-DPYBIND11_TEST_OVERRIDE=test_call_policies.cpp;test_gil_scoped.cpp;test_thread.cpp\"\n\n    - name: Build - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      if: matrix.gcc == '12'\n      run: cmake --build build_partial -j 2\n\n    - name: Python tests - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      if: matrix.gcc == '12'\n      run: cmake --build build_partial --target pytest\n\n  # Testing on ICC using the oneAPI apt repo\n  icc:\n    if: github.event.pull_request.draft == false\n    runs-on: ubuntu-22.04\n    timeout-minutes: 90\n\n    name: \"🐍 3 • ICC latest • x64\"\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Add apt repo\n      run: |\n        sudo apt-get update\n        sudo apt-get install -y wget build-essential pkg-config cmake ca-certificates gnupg\n        wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB\n        sudo apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB\n        echo \"deb https://apt.repos.intel.com/oneapi all main\" | sudo tee /etc/apt/sources.list.d/oneAPI.list\n\n    - name: Add ICC & Python 3\n      run: sudo apt-get update; sudo apt-get install -y intel-oneapi-compiler-dpcpp-cpp-and-cpp-classic cmake python3-dev python3-numpy python3-pytest python3-pip\n\n    - name: Update pip\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        python3 -m pip install --upgrade pip\n\n    - name: Install dependencies\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        python3 -m pip install -r tests/requirements.txt\n\n    - name: Configure C++11\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake -S . -B build-11     \\\n        -DPYBIND11_WERROR=ON    \\\n        -DDOWNLOAD_CATCH=ON     \\\n        -DDOWNLOAD_EIGEN=OFF    \\\n        -DCMAKE_CXX_STANDARD=11             \\\n        -DCMAKE_CXX_COMPILER=$(which icpc)  \\\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Build C++11\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-11 -j 2 -v\n\n    - name: Python tests C++11\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        sudo service apport stop\n        cmake --build build-11 --target check\n\n    - name: C++ tests C++11\n      timeout-minutes: 3\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-11 --target cpptest\n\n    - name: Interface test C++11\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-11 --target test_cmake_build\n\n    - name: Visibility test\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-11 --target test_cross_module_rtti\n\n    - name: Configure C++17\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake -S . -B build-17     \\\n        -DPYBIND11_WERROR=ON    \\\n        -DDOWNLOAD_CATCH=ON     \\\n        -DDOWNLOAD_EIGEN=OFF    \\\n        -DCMAKE_CXX_STANDARD=17             \\\n        -DCMAKE_CXX_COMPILER=$(which icpc)  \\\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Build C++17\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-17 -j 2 -v\n\n    - name: Python tests C++17\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        sudo service apport stop\n        cmake --build build-17 --target check\n\n    - name: C++ tests C++17\n      timeout-minutes: 3\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-17 --target cpptest\n\n    - name: Interface test C++17\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-17 --target test_cmake_build\n\n    - name: Visibility test\n      run: |\n        set +e; source /opt/intel/oneapi/setvars.sh; set -e\n        cmake --build build-17 --target test_cross_module_rtti\n\n  # Testing on CentOS (manylinux uses a centos base).\n  centos:\n    if: github.event.pull_request.draft == false\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        container:\n          - \"almalinux:8\"\n          - \"almalinux:9\"\n\n    name: \"🐍 3 • ${{ matrix.container }} • x64\"\n    container: \"${{ matrix.container }}\"\n    timeout-minutes: 90\n\n    steps:\n    - name: Latest actions/checkout\n      uses: actions/checkout@v6\n\n    - name: Add Python 3.8\n      if: matrix.container == 'almalinux:8'\n      run: dnf update -y && dnf install -y python38-devel gcc-c++ make git\n\n    - name: Add Python 3 (default)\n      if: matrix.container != 'almalinux:8'\n      run: dnf update -y && dnf install -y python3-devel gcc-c++ make git\n\n    - name: Update pip\n      run: python3 -m pip install --upgrade pip\n\n    - name: Install dependencies\n      run: |\n        python3 -m pip install cmake -r tests/requirements.txt\n\n    - name: Ensure NumPy 2 is used (required Python >= 3.9)\n      if: matrix.container == 'almalinux:9'\n      run: |\n        python3 -m pip install 'numpy>=2.0.0b1' 'scipy>=1.13.0rc1'\n\n    - name: Configure\n      shell: bash\n      run: >\n        cmake -S . -B build\n        -DCMAKE_BUILD_TYPE=MinSizeRel\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=11\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Build\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: cmake --build build --target cpptest\n\n    - name: Interface test\n      run: cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti\n\n\n  # This tests an \"install\" with the CMake tools\n  install-classic:\n    if: github.event.pull_request.draft == false\n    name: \"🐍 3.9 • Debian • x86 •  Install\"\n    runs-on: ubuntu-latest\n    container: i386/debian:bullseye\n    timeout-minutes: 90\n\n    steps:\n    # v1 required for i386/debian container; pinned to SHA to prevent dependabot updates\n    - uses: actions/checkout@544eadc6bf3d226fd7a7a9f0dc5b5bf7ca0675b9  # v1\n\n    - name: Install requirements\n      run: |\n        apt-get update\n        apt-get install -y git make cmake g++ libeigen3-dev python3-dev python3-pip\n        pip3 install \"pytest==6.*\"\n\n    - name: Configure for install\n      run: >\n        cmake .\n        -DPYBIND11_INSTALL=1 -DPYBIND11_TEST=0\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n\n    - name: Make and install\n      run: make install\n\n    - name: Copy tests to new directory\n      run: cp -a tests /pybind11-tests\n\n    - name: Make a new test directory\n      run: mkdir /build-tests\n\n    - name: Configure tests\n      run: >\n        cmake ../pybind11-tests\n        -DDOWNLOAD_CATCH=ON\n        -DPYBIND11_WERROR=ON\n        -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\")\n      working-directory: /build-tests\n\n    - name: Python tests\n      run: make pytest -j 2\n      working-directory: /build-tests\n\n\n  # This verifies that the documentation is not horribly broken, and does a\n  # basic validation check on the SDist.\n  doxygen:\n    if: github.event.pull_request.draft == false\n    name: \"Documentation build test\"\n    runs-on: ubuntu-latest\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - uses: actions/setup-python@v6\n      with:\n        python-version: \"3.x\"\n\n    - name: Install Doxygen\n      run: sudo apt-get install -y doxygen librsvg2-bin # Changed to rsvg-convert in 20.04\n\n    - name: Build docs\n      run: pipx run nox -s docs\n\n    - name: Make SDist\n      run: pipx run nox -s build -- --sdist\n\n    - run: git status --ignored\n\n    - name: Check local include dir\n      run: >\n        ls pybind11;\n        python3 -c \"import pybind11, pathlib; assert (a := pybind11.get_include()) == (b := str(pathlib.Path('include').resolve())), f'{a} != {b}'\"\n\n    - name: Compare Dists (headers only)\n      working-directory: include\n      run: |\n        python3 -m pip install --user -U ../dist/*.tar.gz\n        installed=$(python3 -c \"import pybind11; print(pybind11.get_include() + '/pybind11')\")\n        diff -rq $installed ./pybind11\n\n  win32:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - python: '3.8'\n            args: -DCMAKE_CXX_STANDARD=17\n          - python: '3.10'\n            args: -DCMAKE_CXX_STANDARD=20\n          - python: '3.13'\n\n\n    name: \"🐍 ${{ matrix.python }} • MSVC 2022 • x86 ${{ matrix.args }}\"\n    runs-on: windows-2022\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python ${{ matrix.python }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python }}\n        architecture: x86\n        # Python 3.13.4 broken on Windows\n        check-latest: >-\n          ${{ matrix.python == '3.13' && runner.os == 'Windows' }}\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Prepare MSVC\n      uses: ilammy/msvc-dev-cmd@v1.13.0\n      with:\n        arch: x86\n\n    - name: Prepare env\n      run: |\n        python -m pip install -r tests/requirements.txt\n\n    - name: Configure ${{ matrix.args }}\n      run: >\n        cmake -S . -B build\n        -G \"Visual Studio 17 2022\" -A Win32\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        ${{ matrix.args }}\n    - name: Build C++11\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build -t pytest\n\n  win32-debug:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - python: 3.9\n            args: -DCMAKE_CXX_STANDARD=20\n          - python: 3.8\n            args: -DCMAKE_CXX_STANDARD=17\n\n    name: \"🐍 ${{ matrix.python }} • MSVC 2022 (Debug) • x86 ${{ matrix.args }}\"\n    runs-on: windows-2022\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python ${{ matrix.python }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python }}\n        architecture: x86\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Prepare MSVC\n      uses: ilammy/msvc-dev-cmd@v1.13.0\n      with:\n        arch: x86\n\n    - name: Prepare env\n      run: |\n        python -m pip install -r tests/requirements.txt\n\n    - name: Configure ${{ matrix.args }}\n      run: >\n        cmake -S . -B build\n        -G \"Visual Studio 17 2022\" -A Win32\n        -DCMAKE_BUILD_TYPE=Debug\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        ${{ matrix.args }}\n    - name: Build C++11\n      run: cmake --build build --config Debug -j 2\n\n    - name: Python tests\n      run: cmake --build build --config Debug -t pytest\n\n\n  windows-2022:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        python:\n        - 3.9\n\n    name: \"🐍 ${{ matrix.python }} • MSVC 2022 C++20 • x64\"\n    runs-on: windows-2022\n    timeout-minutes: 90\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python ${{ matrix.python }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python }}\n\n    - name: Prepare env\n      run: python3 -m pip install -r tests/requirements.txt\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Configure C++20\n      run: >\n        cmake -S . -B build\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=20\n\n    - name: Build C++20\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build --target pytest\n\n    - name: C++20 tests\n      timeout-minutes: 3\n      run: cmake --build build --target cpptest -j 2\n\n    - name: Interface test C++20\n      run: cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti\n\n    - name: Configure C++20 - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      run: >\n        cmake -S . -B build_partial\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=20\n        \"-DPYBIND11_TEST_OVERRIDE=test_call_policies.cpp;test_gil_scoped.cpp;test_thread.cpp\"\n\n    - name: Build C++20 - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      run: cmake --build build_partial -j 2\n\n    - name: Python tests - Exercise cmake -DPYBIND11_TEST_OVERRIDE\n      run: cmake --build build_partial --target pytest\n\n  mingw:\n    if: github.event.pull_request.draft == false\n    name: \"🐍 3 • windows-latest • ${{ matrix.sys }}\"\n    runs-on: windows-latest\n    timeout-minutes: 90\n    defaults:\n      run:\n        shell: msys2 {0}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - sys: mingw32\n            env: i686\n            extra_install: \"\"\n          - sys: mingw64\n            env: x86_64\n            extra_install: |\n              mingw-w64-x86_64-python-numpy\n              mingw-w64-x86_64-python-scipy\n              mingw-w64-x86_64-eigen3\n    steps:\n    - uses: msys2/setup-msys2@v2\n      with:\n        msystem: ${{matrix.sys}}\n        install: >-\n          git\n          mingw-w64-${{matrix.env}}-gcc\n          mingw-w64-${{matrix.env}}-python-pip\n          mingw-w64-${{matrix.env}}-cmake\n          mingw-w64-${{matrix.env}}-make\n          mingw-w64-${{matrix.env}}-python-pytest\n          mingw-w64-${{matrix.env}}-boost\n          mingw-w64-${{matrix.env}}-catch\n          ${{ matrix.extra_install }}\n\n    - uses: actions/checkout@v6\n\n    - name: Configure C++11\n      # LTO leads to many undefined reference like\n      # `pybind11::detail::function_call::function_call(pybind11::detail::function_call&&)\n      run: >-\n        cmake -G \"MinGW Makefiles\" -DCMAKE_CXX_STANDARD=11 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON\n        -DPYTHON_EXECUTABLE=$(python -c \"import sys; print(sys.executable)\")\n        -S . -B build\n\n    - name: Build C++11\n      run: cmake --build build -j 2\n\n    - name: Python tests C++11\n      run: cmake --build build --target pytest -j 2\n\n    - name: C++11 tests\n      timeout-minutes: 3\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target cpptest -j 2\n\n    - name: Interface test C++11\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target test_cmake_build\n\n    - name: Visibility test\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build --target test_cross_module_rtti\n\n    - name: Clean directory\n      run: git clean -fdx\n\n    - name: Configure C++14\n      run: >-\n        cmake -G \"MinGW Makefiles\" -DCMAKE_CXX_STANDARD=14 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON\n        -DPYTHON_EXECUTABLE=$(python -c \"import sys; print(sys.executable)\")\n        -S . -B build2\n\n    - name: Build C++14\n      run: cmake --build build2 -j 2\n\n    - name: Python tests C++14\n      run: cmake --build build2 --target pytest -j 2\n\n    - name: C++14 tests\n      timeout-minutes: 3\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target cpptest -j 2\n\n    - name: Interface test C++14\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target test_cmake_build\n\n    - name: Visibility test\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build2 --target test_cross_module_rtti\n\n    - name: Clean directory\n      run: git clean -fdx\n\n    - name: Configure C++17\n      run: >-\n        cmake -G \"MinGW Makefiles\" -DCMAKE_CXX_STANDARD=17 -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON\n        -DPYTHON_EXECUTABLE=$(python -c \"import sys; print(sys.executable)\")\n        -S . -B build3\n\n    - name: Build C++17\n      run: cmake --build build3 -j 2\n\n    - name: Python tests C++17\n      run: cmake --build build3 --target pytest -j 2\n\n    - name: C++17 tests\n      timeout-minutes: 3\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target cpptest -j 2\n\n    - name: Interface test C++17\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target test_cmake_build\n\n    - name: Visibility test\n      run: PYTHONHOME=/${{matrix.sys}} PYTHONPATH=/${{matrix.sys}} cmake --build build3 --target test_cross_module_rtti\n\n  windows_clang:\n    if: github.event.pull_request.draft == false\n\n    strategy:\n      matrix:\n        os: [windows-latest]\n        python: ['3.10']\n\n    runs-on: \"${{ matrix.os }}\"\n    timeout-minutes: 90\n\n    name: \"🐍 ${{ matrix.python }} • ${{ matrix.os }} • clang-latest\"\n\n    steps:\n      - name: Show env\n        run: env\n\n      - name: Checkout\n        uses: actions/checkout@v6\n\n      - name: Set up Clang\n        uses: egor-tensin/setup-clang@v2\n\n      - name: Setup Python ${{ matrix.python }}\n        uses: actions/setup-python@v6\n        with:\n          python-version: ${{ matrix.python }}\n\n      - name: Update CMake\n        uses: jwlawson/actions-setup-cmake@v2.1\n\n      - name: Install ninja-build tool\n        uses: seanmiddleditch/gha-setup-ninja@v6\n\n      - name: Run pip installs\n        run: |\n          python -m pip install --upgrade pip\n          python -m pip install -r tests/requirements.txt\n\n      - name: Show Clang++ version\n        run: clang++ --version\n\n      - name: Show CMake version\n        run: cmake --version\n\n      # TODO: WERROR=ON\n      - name: Configure Clang\n        run: >\n          cmake -G Ninja -S . -B .\n          -DPYBIND11_WERROR=OFF\n          -DPYBIND11_SIMPLE_GIL_MANAGEMENT=OFF\n          -DDOWNLOAD_CATCH=ON\n          -DDOWNLOAD_EIGEN=ON\n          -DCMAKE_CXX_COMPILER=clang++\n          -DCMAKE_CXX_STANDARD=17\n\n      - name: Build\n        run: cmake --build . -j 2\n\n      - name: Python tests\n        run: cmake --build . --target pytest -j 2\n\n      - name: C++ tests\n        timeout-minutes: 3\n        run: cmake --build . --target cpptest -j 2\n\n      - name: Interface test\n        run: cmake --build . --target test_cmake_build -j 2\n\n      - name: Visibility test\n        run: cmake --build . --target test_cross_module_rtti -j 2\n\n      - name: Clean directory\n        run: git clean -fdx\n\n  # Clang with MSVC/Windows SDK toolchain + python.org CPython (Windows ARM)\n  windows_arm_clang_msvc:\n    if: github.event.pull_request.draft == false\n\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [windows-11-arm]\n        python: ['3.13']\n\n    runs-on: \"${{ matrix.os }}\"\n    timeout-minutes: 90\n\n    name: \"🐍 ${{ matrix.python }} • ${{ matrix.os }} • clang-msvc\"\n\n    steps:\n      - name: Show env\n        run: env\n\n      - name: Checkout\n        uses: actions/checkout@v6\n\n      - name: Setup Python ${{ matrix.python }}\n        uses: actions/setup-python@v6\n        with:\n          python-version: ${{ matrix.python }}\n          architecture: arm64\n\n      - name: Run pip installs\n        run: |\n          python -m pip install --upgrade pip\n          python -m pip install -r tests/requirements.txt\n\n      - name: Configure CMake\n        run: >\n          cmake -G Ninja -S . -B .\n          -DPYBIND11_WERROR=OFF\n          -DPYBIND11_SIMPLE_GIL_MANAGEMENT=OFF\n          -DDOWNLOAD_CATCH=ON\n          -DDOWNLOAD_EIGEN=ON\n          -DCMAKE_CXX_COMPILER=clang++\n          -DCMAKE_CXX_STANDARD=20\n          -DPython_ROOT_DIR=\"$env:Python_ROOT_DIR\"\n\n      - name: Build\n        run: cmake --build . -j 2\n\n      - name: Python tests\n        run: cmake --build . --target pytest -j 2\n\n      - name: C++ tests\n        timeout-minutes: 3\n        run: cmake --build . --target cpptest -j 2\n\n      - name: Interface test\n        run: cmake --build . --target test_cmake_build -j 2\n\n      - name: Visibility test\n        run: cmake --build . --target test_cross_module_rtti -j 2\n\n  # Clang in MSYS2/MinGW-w64 CLANGARM64 toolchain + MSYS2 Python (Windows ARM)\n  windows_arm_clang_msys2:\n    if: github.event.pull_request.draft == false\n\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [windows-11-arm]\n\n    runs-on: \"${{ matrix.os }}\"\n    timeout-minutes: 90\n\n    name: \"${{ matrix.os }} • clang-msys2\"\n\n    defaults:\n      run:\n        shell: msys2 {0}\n\n    steps:\n    - uses: actions/checkout@v6\n      with:\n        submodules: true\n\n    - uses: msys2/setup-msys2@v2\n      with:\n        msystem: CLANGARM64\n        update: true\n        install: |\n          mingw-w64-clang-aarch64-cmake\n          mingw-w64-clang-aarch64-clang\n          mingw-w64-clang-aarch64-ninja\n          mingw-w64-clang-aarch64-python-pip\n          mingw-w64-clang-aarch64-python-pytest\n          mingw-w64-clang-aarch64-python-numpy\n\n    - name: Debug info\n      run: |\n        clang++ --version\n        cmake --version\n        ninja --version\n        python --version\n\n    - name: Run pip installs\n      run: |\n        python -m pip install --upgrade pip\n        python -m pip install -r tests/requirements.txt\n\n    - name: Configure CMake\n      run: >-\n        cmake -S . -B build\n        -DPYBIND11_WERROR=OFF\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_COMPILER=clang++\n        -DCMAKE_CXX_STANDARD=20\n        -DPYTHON_EXECUTABLE=$(python -c \"import sys; print(sys.executable)\")\n\n    - name: Build\n      run: cmake --build build -j 2\n\n    - name: Python tests\n      run: cmake --build build --target pytest -j 2\n\n    - name: C++ tests\n      timeout-minutes: 3\n      run: PYTHONHOME=/clangarm64 PYTHONPATH=/clangarm64 cmake --build build --target cpptest -j 2\n\n    - name: Interface test\n      run: cmake --build build --target test_cmake_build -j 2\n\n    - name: Visibility test\n      run: cmake --build build --target test_cross_module_rtti -j 2\n"
  },
  {
    "path": ".github/workflows/configure.yml",
    "content": "name: Config\n\non:\n  workflow_dispatch:\n  pull_request:\n    types:\n      - opened\n      - synchronize\n      - reopened\n      - ready_for_review\n  push:\n    branches:\n      - master\n      - stable\n      - v*\n\npermissions:\n  contents: read\n\njobs:\n  # This tests various versions of CMake in various combinations, to make sure\n  # the configure step passes.\n  cmake:\n    if: github.event.pull_request.draft == false\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n        - runs-on: ubuntu-22.04\n          cmake: \"3.15\"\n\n        - runs-on: ubuntu-24.04\n          cmake: \"3.26\"\n\n        - runs-on: ubuntu-24.04\n          cmake: \"3.29\"\n\n        - runs-on: macos-15-intel\n          cmake: \"3.15\"\n\n        - runs-on: macos-14\n          cmake: \"4.2\"\n\n        - runs-on: windows-latest\n          cmake: \"4.2\"\n\n    name: 🐍 3.11 • CMake ${{ matrix.cmake }} • ${{ matrix.runs-on }}\n    runs-on: ${{ matrix.runs-on }}\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python 3.11\n      uses: actions/setup-python@v6\n      with:\n        python-version: 3.11\n\n    - name: Install uv\n      uses: astral-sh/setup-uv@v7\n\n    - name: Prepare env\n      run: uv pip install --python=python --system -r tests/requirements.txt\n\n    # An action for adding a specific version of CMake:\n    #   https://github.com/jwlawson/actions-setup-cmake\n    - name: Setup CMake ${{ matrix.cmake }}\n      uses: jwlawson/actions-setup-cmake@v2.1\n      with:\n        cmake-version: ${{ matrix.cmake }}\n\n    # These steps use a directory with a space in it intentionally\n    - name: Configure\n      shell: bash\n      run: cmake -S. -B\"build dir\" -DPYBIND11_WERROR=ON -DDOWNLOAD_CATCH=ON\n\n    # Only build and test if this was manually triggered in the GitHub UI\n    - name: Build\n      working-directory: build dir\n      if: github.event_name == 'workflow_dispatch'\n      run: cmake --build . --config Release\n\n    - name: Test\n      working-directory: build dir\n      if: github.event_name == 'workflow_dispatch'\n      run: cmake --build . --config Release --target check\n"
  },
  {
    "path": ".github/workflows/docs-link.yml",
    "content": "name: Read the Docs PR preview\n\non:\n  pull_request_target:\n    types:\n      - opened\n      - synchronize\n\npermissions:\n  contents: read\n  pull-requests: write\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\njobs:\n  documentation-links:\n    runs-on: ubuntu-latest\n    if: github.event.repository.fork == false\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Check for docs changes\n        id: docs_changes\n        run: |\n          # Fetch the PR head\n          git fetch origin pull/${{ github.event.pull_request.number }}/head:pr-head\n\n          # Show diff between base (current checkout) and PR head\n          if git diff --name-only HEAD pr-head | grep -q '^docs/'; then\n            echo \"docs_changed=true\" >> \"$GITHUB_OUTPUT\"\n          else\n            echo \"docs_changed=false\" >> \"$GITHUB_OUTPUT\"\n          fi\n\n      - uses: readthedocs/actions/preview@v1\n        if: steps.docs_changes.outputs.docs_changed == 'true'\n        with:\n          project-slug: \"pybind11\"\n          single-version: \"true\"\n"
  },
  {
    "path": ".github/workflows/format.yml",
    "content": "# This is a format job. Pre-commit has a first-party GitHub action, so we use\n# that: https://github.com/pre-commit/action\n\nname: Format\n\non:\n  workflow_dispatch:\n  pull_request:\n  push:\n    branches:\n    - master\n    - stable\n    - \"v*\"\n\npermissions:\n  contents: read\n\nenv:\n  FORCE_COLOR: 3\n  # For cmake:\n  VERBOSE: 1\n\njobs:\n  pre-commit:\n    name: Format\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v6\n    - uses: actions/setup-python@v6\n      with:\n        python-version: \"3.x\"\n    - name: Add matchers\n      run: echo \"::add-matcher::$GITHUB_WORKSPACE/.github/matchers/pylint.json\"\n    - uses: pre-commit/action@v3.0.1\n\n  clang-tidy:\n    # When making changes here, please also review the \"Clang-Tidy\" section\n    # in .github/CONTRIBUTING.md and update as needed.\n    name: Clang-Tidy\n    runs-on: ubuntu-latest\n    container: silkeh/clang:20\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Install requirements\n      run: apt-get update && apt-get install -y git python3-dev python3-pytest ninja-build\n\n    - name: Configure\n      run: cmake --preset tidy\n    - name: Build\n      run: cmake --build --preset tidy\n\n    - name: Embedded\n      run: cmake --build --preset tidy -t cpptest\n"
  },
  {
    "path": ".github/workflows/labeler.yml",
    "content": "name: Labeler\non:\n  pull_request_target:\n    types: [closed]\n\npermissions: {}\n\njobs:\n  label:\n    name: Labeler\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n      pull-requests: write\n    steps:\n\n    - uses: actions/labeler@v6\n      if: >\n        github.event.pull_request.merged == true &&\n        !startsWith(github.event.pull_request.title, 'chore(deps):') &&\n        !startsWith(github.event.pull_request.title, 'ci(fix):') &&\n        !startsWith(github.event.pull_request.title, 'docs(changelog):')\n      with:\n        repo-token: ${{ secrets.GITHUB_TOKEN }}\n        configuration-path: .github/labeler_merged.yml\n"
  },
  {
    "path": ".github/workflows/nightlies.yml",
    "content": "name: Upload nightly wheels to Anaconda Cloud\n\non:\n  # Run daily at 2:34 UTC to upload nightly wheels to Anaconda Cloud\n  schedule:\n    - cron: \"34 2 * * *\"\n  # Run on demand with workflow dispatch\n  workflow_dispatch:\n\npermissions:\n  actions: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  build_wheel:\n    name: Build and upload wheel\n    if: github.repository_owner == 'pybind'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v7\n\n      - name: Build SDist and wheels\n        run: |\n          uv tool install nox\n          nox -s build\n          nox -s build_global\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: Packages\n          path: dist/*\n\n  upload_nightly_wheels:\n    name: Upload nightly wheels to Anaconda Cloud\n    if: github.repository_owner == 'pybind'\n    needs: [build_wheel]\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/download-artifact@v8\n        with:\n          name: Packages\n          path: dist\n\n      - name: List wheel to be deployed\n        run: ls -lha dist/*.whl\n\n      - name: Upload wheel to Anaconda Cloud as nightly\n        uses: scientific-python/upload-nightly-action@5748273c71e2d8d3a61f3a11a16421c8954f9ecf # 0.6.3\n        with:\n          artifacts_path: dist\n          anaconda_nightly_upload_token: ${{ secrets.ANACONDA_ORG_UPLOAD_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/pip.yml",
    "content": "name: Pip\n\non:\n  workflow_dispatch:\n  pull_request:\n  push:\n    branches:\n    - master\n    - stable\n    - v*\n  release:\n    types:\n    - published\n\npermissions:\n  contents: read\n\njobs:\n  # This builds the sdists and wheels and makes sure the files are exactly as\n  # expected.\n  test-packaging:\n    name: 🐍 3.8 • 📦 tests • windows-latest\n    runs-on: windows-latest\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup 🐍 3.8\n      uses: actions/setup-python@v6\n      with:\n        python-version: 3.8\n\n    - name: Install uv\n      uses: astral-sh/setup-uv@v7\n\n    - name: Prepare env\n      run: uv pip install --system -r tests/requirements.txt\n\n    - name: Python Packaging tests\n      run: pytest tests/extra_python_package/\n\n\n  # This runs the packaging tests and also builds and saves the packages as\n  # artifacts.\n  packaging:\n    name: 🐍 3.8 • 📦 & 📦 tests • ubuntu-latest\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup 🐍 3.8\n      uses: actions/setup-python@v6\n      with:\n        python-version: 3.8\n\n    - name: Install uv\n      uses: astral-sh/setup-uv@v7\n\n    - name: Prepare env\n      run: uv pip install --system -r tests/requirements.txt twine nox\n\n    - name: Python Packaging tests\n      run: pytest tests/extra_python_package/\n\n    - name: Build SDist and wheels\n      run: |\n        nox -s build\n        nox -s build_global\n\n    - name: Check metadata\n      run: twine check dist/*\n\n    - name: Save standard package\n      uses: actions/upload-artifact@v7\n      with:\n        name: standard\n        path: dist/pybind11-*\n\n    - name: Save global package\n      uses: actions/upload-artifact@v7\n      with:\n        name: global\n        path: dist/*global-*\n\n\n\n  # When a GitHub release is made, upload the artifacts to PyPI\n  upload:\n    name: Upload to PyPI\n    runs-on: ubuntu-latest\n    if: github.event_name == 'release' && github.event.action == 'published'\n    needs: [packaging]\n    environment:\n      name: pypi\n      url: https://pypi.org/p/pybind11\n    permissions:\n      id-token: write\n      attestations: write\n\n    steps:\n    # Downloads all to directories matching the artifact names\n    - uses: actions/download-artifact@v8\n\n    - name: Generate artifact attestation for sdist and wheel\n      uses: actions/attest-build-provenance@v4\n      with:\n        subject-path: \"*/pybind11*\"\n\n    - name: Publish standard package\n      uses: pypa/gh-action-pypi-publish@release/v1\n      with:\n        packages-dir: standard/\n\n    - name: Publish global package\n      uses: pypa/gh-action-pypi-publish@release/v1\n      with:\n        packages-dir: global/\n"
  },
  {
    "path": ".github/workflows/reusable-standard.yml",
    "content": "name: Reusable Standard Test\n\non:\n  workflow_call:\n    inputs:\n      python-version:\n        required: true\n        type: string\n      cmake-args:\n        required: false\n        type: string\n        default: ''\n      runs-on:\n        required: true\n        type: string\n\nenv:\n  PYTHONDEVMODE: 1\n  PIP_BREAK_SYSTEM_PACKAGES: 1\n  PIP_ONLY_BINARY: numpy\n  FORCE_COLOR: 3\n  PYTEST_TIMEOUT: 300\n  # For cmake:\n  VERBOSE: 1\n  CMAKE_COLOR_DIAGNOSTICS: 1\n\njobs:\n  standard:\n    name: 🧪\n    runs-on: ${{ inputs.runs-on }}\n    timeout-minutes: 90\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Setup Python ${{ inputs.python-version }}\n        uses: actions/setup-python@v6\n        with:\n          python-version: ${{ inputs.python-version }}\n          allow-prereleases: true\n          # Python 3.13.4 broken on Windows\n          check-latest: >-\n            ${{ inputs.python-version == '3.13' && runner.os == 'Windows' }}\n\n      - name: Setup Boost (Linux)\n        if: runner.os == 'Linux'\n        run: sudo apt-get update && sudo apt-get install -y libboost-dev\n\n      - name: Setup Boost (macOS)\n        if: runner.os == 'macOS'\n        run: brew install boost\n\n      - name: Install uv\n        uses: astral-sh/setup-uv@v7\n        with:\n          enable-cache: true\n\n      - name: Prepare env\n        run: uv pip install --python=python --system -r tests/requirements.txt\n\n      - name: Setup annotations on Linux\n        if: runner.os == 'Linux'\n        run: uv pip install --python=python --system pytest-github-actions-annotate-failures\n\n      # TODO Resolve Windows Ninja shared object issue on Python 3.8+\n      - name: Use Ninja except on Windows\n        if: runner.os != 'Windows'\n        run: echo \"CMAKE_GENERATOR=Ninja\" >> \"$GITHUB_ENV\"\n\n      - name: Configure\n        run: >\n          cmake -S. -Bbuild -Werror=dev\n          -DPYBIND11_WERROR=ON\n          -DPYBIND11_PYTEST_ARGS=-v\n          -DDOWNLOAD_CATCH=ON\n          -DDOWNLOAD_EIGEN=ON\n          ${{ inputs.cmake-args }}\n\n      - name: Build\n        run: cmake --build build\n\n      - name: Python tests\n        run: cmake --build build --target pytest\n\n      - name: C++ tests\n        timeout-minutes: 3\n        run: cmake --build build --target cpptest\n\n      - name: Interface test\n        run: cmake --build build --target test_cmake_build\n\n      - name: Visibility test\n        run: cmake --build build --target test_cross_module_rtti\n\n      - name: Setuptools helpers test\n        run: |\n          uv pip install --python=python --system setuptools\n          pytest tests/extra_setuptools\n"
  },
  {
    "path": ".github/workflows/tests-cibw.yml",
    "content": "name: CIBW\n\non:\n  workflow_dispatch:\n  pull_request:\n    branches:\n    - master\n    - stable\n    - v*\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  build-wasm-emscripten:\n    name: Pyodide wheel\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v6\n      with:\n        submodules: true\n        fetch-depth: 0\n\n    - uses: pypa/cibuildwheel@v3.3\n      env:\n        PYODIDE_BUILD_EXPORTS: whole_archive\n      with:\n        package-dir: tests\n        only: cp312-pyodide_wasm32\n\n  build-ios:\n    name: iOS wheel ${{ matrix.runs-on }}\n    runs-on: ${{ matrix.runs-on }}\n    strategy:\n      fail-fast: false\n      matrix:\n        runs-on: [macos-14, macos-15-intel]\n    steps:\n    - uses: actions/checkout@v6\n      with:\n        submodules: true\n        fetch-depth: 0\n\n    # We have to uninstall first because GH is now using a local tap to build cmake<4, iOS needs cmake>=4\n    - run: brew uninstall cmake && brew install cmake\n\n    - uses: pypa/cibuildwheel@v3.3\n      env:\n        CIBW_PLATFORM: ios\n        CIBW_SKIP: cp314-*  # https://github.com/pypa/cibuildwheel/issues/2494\n      with:\n        package-dir: tests\n\n  build-android:\n    name: Android wheel ${{ matrix.runs-on }}\n    runs-on: ${{ matrix.runs-on }}\n    strategy:\n      fail-fast: false\n      matrix:\n        runs-on: [macos-latest, macos-15-intel, ubuntu-latest]\n    steps:\n    - uses: actions/checkout@v6\n      with:\n        submodules: true\n        fetch-depth: 0\n\n    # GitHub Actions can't currently run the Android emulator on macOS.\n    - name: Skip Android tests on macOS\n      if: contains(matrix.runs-on, 'macos')\n      run: echo \"CIBW_TEST_COMMAND=\" >> \"$GITHUB_ENV\"\n\n    - uses: pypa/cibuildwheel@v3.3\n      env:\n        CIBW_PLATFORM: android\n      with:\n        package-dir: tests\n"
  },
  {
    "path": ".github/workflows/upstream.yml",
    "content": "name: Upstream\n\non:\n  workflow_dispatch:\n  pull_request:\n\npermissions:\n  contents: read\n\nconcurrency:\n  group: upstream-${{ github.ref }}\n  cancel-in-progress: true\n\nenv:\n  PIP_BREAK_SYSTEM_PACKAGES: 1\n  # For cmake:\n  VERBOSE: 1\n\njobs:\n  standard:\n    name: \"🐍 3.13 latest • ubuntu-latest • x64\"\n    runs-on: ubuntu-latest\n    # Only runs when the  'python dev' label is selected\n    if: \"contains(github.event.pull_request.labels.*.name, 'python dev')\"\n\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: Setup Python 3.13\n      uses: actions/setup-python@v6\n      with:\n        python-version: \"3.13\"\n        allow-prereleases: true\n\n    - name: Setup Boost\n      run: sudo apt-get install libboost-dev\n\n    - name: Update CMake\n      uses: jwlawson/actions-setup-cmake@v2.1\n\n    - name: Run pip installs\n      run: |\n        python -m pip install --upgrade pip\n        python -m pip install -r tests/requirements.txt\n\n    - name: Show platform info\n      run: |\n        python -m platform\n        cmake --version\n        pip list\n\n    # First build - C++11 mode and inplace\n    - name: Configure C++11\n      run: >\n        cmake -S . -B build11\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=11\n        -DCMAKE_BUILD_TYPE=Debug\n\n    - name: Build C++11\n      run: cmake --build build11 -j 2\n\n    - name: Python tests C++11\n      run: cmake --build build11 --target pytest -j 2\n\n    - name: C++11 tests\n      timeout-minutes: 3\n      run: cmake --build build11  --target cpptest -j 2\n\n    - name: Interface test C++11\n      run: cmake --build build11 --target test_cmake_build\n\n    # Second build - C++17 mode and in a build directory\n    - name: Configure C++17\n      run: >\n        cmake -S . -B build17\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=17\n\n    - name: Build C++17\n      run: cmake --build build17 -j 2\n\n    - name: Python tests C++17\n      run: cmake --build build17 --target pytest\n\n    - name: C++17 tests\n      timeout-minutes: 3\n      run: cmake --build build17 --target cpptest\n\n    # Third build - C++17 mode with unstable ABI\n    - name: Configure (unstable ABI)\n      run: >\n        cmake -S . -B build17max\n        -DPYBIND11_WERROR=ON\n        -DDOWNLOAD_CATCH=ON\n        -DDOWNLOAD_EIGEN=ON\n        -DCMAKE_CXX_STANDARD=17\n        -DPYBIND11_INTERNALS_VERSION=10000000\n\n    - name: Build (unstable ABI)\n      run: cmake --build build17max -j 2\n\n    - name: Python tests (unstable ABI)\n      run: cmake --build build17max --target pytest\n\n    - name: Interface test (unstable ABI)\n      run: cmake --build build17max --target test_cmake_build\n\n    # This makes sure the setup_helpers module can build packages using\n    # setuptools\n    - name: Setuptools helpers test\n      run: |\n        pip install setuptools\n        pytest tests/extra_setuptools\n"
  },
  {
    "path": ".gitignore",
    "content": "CMakeCache.txt\nCMakeFiles\nMakefile\ncmake_install.cmake\ncmake_uninstall.cmake\n.DS_Store\n*.so\n*.pyd\n*.dll\n*.sln\n*.sdf\n*.opensdf\n*.vcxproj\n*.vcxproj.user\n*.filters\nexample.dir\nWin32\nx64\nRelease\nDebug\n.vs\nCTestTestfile.cmake\nTesting\nautogen\nMANIFEST\n/.ninja_*\n/*.ninja\n/docs/.build\n__pycache__/\n*.py[co]\n*.egg-info\n*~\n.*.swp\n.DS_Store\n/dist\n/*build*\n.cache/\nsosize-*.txt\npybind11Config*.cmake\npybind11Targets.cmake\n/*env*\n/.vscode\n/pybind11/include/*\n/pybind11/share/*\n/docs/_build/*\n.ipynb_checkpoints/\ntests/main.cpp\nCMakeUserPresents.json\n\n/Python\n/tmp*\n.ruby-version\n.*cache*/\n*.lock\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "# To use:\n#\n#     pre-commit run -a\n#\n# Or:\n#\n#     pre-commit install  # (runs every time you commit in git)\n#\n# To update this file:\n#\n#     pre-commit autoupdate\n#\n# See https://github.com/pre-commit/pre-commit\n\n\nci:\n  autoupdate_commit_msg: \"chore(deps): update pre-commit hooks\"\n  autofix_commit_msg: \"style: pre-commit fixes\"\n  autoupdate_schedule: monthly\n\n# third-party content\nexclude: ^tools/JoinPaths.cmake$\n\nrepos:\n\n# Clang format the codebase automatically\n- repo: https://github.com/pre-commit/mirrors-clang-format\n  rev: \"v21.1.8\"\n  hooks:\n  - id: clang-format\n    types_or: [c++, c, cuda]\n\n# Ruff, the Python auto-correcting linter/formatter written in Rust\n- repo: https://github.com/astral-sh/ruff-pre-commit\n  rev: v0.14.14\n  hooks:\n  - id: ruff-check\n    args: [\"--fix\", \"--show-fixes\"]\n  - id: ruff-format\n\n# Check static types with mypy\n- repo: https://github.com/pre-commit/mirrors-mypy\n  rev: \"v1.19.1\"\n  hooks:\n  - id: mypy\n    args: []\n    exclude: ^(tests|docs)/\n    additional_dependencies:\n    - markdown-it-py\n    - nox\n    - rich\n    - types-setuptools\n\n# CMake formatting\n- repo: https://github.com/cheshirekow/cmake-format-precommit\n  rev: \"v0.6.13\"\n  hooks:\n  - id: cmake-format\n    additional_dependencies: [pyyaml]\n    types: [file]\n    files: (\\.cmake|CMakeLists.txt)(.in)?$\n\n# Standard hooks\n- repo: https://github.com/pre-commit/pre-commit-hooks\n  rev: \"v6.0.0\"\n  hooks:\n  - id: check-added-large-files\n  - id: check-case-conflict\n  - id: check-docstring-first\n  - id: check-merge-conflict\n  - id: check-symlinks\n  - id: check-toml\n  - id: check-yaml\n  - id: debug-statements\n  - id: end-of-file-fixer\n  - id: mixed-line-ending\n  - id: requirements-txt-fixer\n  - id: trailing-whitespace\n    exclude: \\.patch?$\n\n# Also code format the docs\n- repo: https://github.com/adamchainz/blacken-docs\n  rev: \"1.20.0\"\n  hooks:\n  - id: blacken-docs\n    additional_dependencies:\n    - black==23.*\n\n# Changes tabs to spaces\n- repo: https://github.com/Lucas-C/pre-commit-hooks\n  rev: \"v1.5.6\"\n  hooks:\n  - id: remove-tabs\n    exclude: (^docs/.*|\\.patch)?$\n\n# Avoid directional quotes\n- repo: https://github.com/sirosen/texthooks\n  rev: \"0.7.1\"\n  hooks:\n  - id: fix-ligatures\n  - id: fix-smartquotes\n\n# Checking for common mistakes\n- repo: https://github.com/pre-commit/pygrep-hooks\n  rev: \"v1.10.0\"\n  hooks:\n  - id: rst-backticks\n  - id: rst-directive-colons\n  - id: rst-inline-touching-normal\n\n# Check for spelling\n# Use tools/codespell_ignore_lines_from_errors.py\n# to rebuild .codespell-ignore-lines\n- repo: https://github.com/codespell-project/codespell\n  rev: \"v2.4.1\"\n  hooks:\n  - id: codespell\n    exclude: \"(.supp|^pyproject.toml)$\"\n    args: [\"-x.codespell-ignore-lines\", \"-Lccompiler,intstruct\"]\n\n# Also check spelling\n# Use mirror because pre-commit autoupdate confuses tags in the upstream repo.\n# See https://github.com/crate-ci/typos/issues/390\n- repo: https://github.com/adhtruong/mirrors-typos\n  rev: \"v1.42.3\"\n  hooks:\n  - id: typos\n    args: []\n\n# Check for common shell mistakes\n- repo: https://github.com/shellcheck-py/shellcheck-py\n  rev: \"v0.11.0.1\"\n  hooks:\n  - id: shellcheck\n\n# Disallow some common capitalization mistakes\n- repo: local\n  hooks:\n  - id: disallow-caps\n    name: Disallow improper capitalization\n    language: pygrep\n    entry: PyBind|\\bNumpy\\b|Cmake|CCache|PyTest\n    exclude: ^\\.pre-commit-config.yaml$\n\n# PyLint has native support - not always usable, but works for us\n- repo: https://github.com/PyCQA/pylint\n  rev: \"v4.0.4\"\n  hooks:\n  - id: pylint\n    files: ^pybind11\n\n# Check schemas on some of our YAML files\n- repo: https://github.com/python-jsonschema/check-jsonschema\n  rev: 0.36.1\n  hooks:\n  - id: check-readthedocs\n  - id: check-github-workflows\n  - id: check-dependabot\n"
  },
  {
    "path": ".readthedocs.yml",
    "content": "# https://blog.readthedocs.com/migrate-configuration-v2/\n\nversion: 2\n\nbuild:\n  os: ubuntu-22.04\n  apt_packages:\n    - librsvg2-bin\n  tools:\n    python: \"3.11\"\n\nsphinx:\n  configuration: docs/conf.py\n\npython:\n  install:\n  - requirements: docs/requirements.txt\n\nformats:\n  - pdf\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "# CMakeLists.txt -- Build system for the pybind11 modules\n#\n# Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\n# Propagate this policy (FindPythonInterp removal) so it can be detected later\nif(NOT CMAKE_VERSION VERSION_LESS \"3.27\")\n  cmake_policy(GET CMP0148 _pybind11_cmp0148)\nendif()\n\ncmake_minimum_required(VERSION 3.15...4.2)\n\nif(_pybind11_cmp0148)\n  cmake_policy(SET CMP0148 ${_pybind11_cmp0148})\n  unset(_pybind11_cmp0148)\nendif()\n\n# Avoid infinite recursion if tests include this as a subdirectory\ninclude_guard(GLOBAL)\n\n# Extract project version from source\nfile(STRINGS \"${CMAKE_CURRENT_SOURCE_DIR}/include/pybind11/detail/common.h\"\n     pybind11_version_defines REGEX \"#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) \")\n\nforeach(ver ${pybind11_version_defines})\n  if(ver MATCHES [[#define PYBIND11_VERSION_(MAJOR|MINOR|PATCH) +([^ ]+)$]])\n    set(PYBIND11_VERSION_${CMAKE_MATCH_1} \"${CMAKE_MATCH_2}\")\n  endif()\nendforeach()\n\nif(PYBIND11_VERSION_PATCH MATCHES [[\\.([a-zA-Z0-9]+)$]])\n  set(pybind11_VERSION_TYPE \"${CMAKE_MATCH_1}\")\nendif()\nstring(REGEX MATCH \"^[0-9]+\" PYBIND11_VERSION_PATCH \"${PYBIND11_VERSION_PATCH}\")\n\nproject(\n  pybind11\n  LANGUAGES CXX\n  VERSION \"${PYBIND11_VERSION_MAJOR}.${PYBIND11_VERSION_MINOR}.${PYBIND11_VERSION_PATCH}\")\n\n# Standard includes\ninclude(GNUInstallDirs)\ninclude(CMakePackageConfigHelpers)\ninclude(CMakeDependentOption)\n\nif(NOT pybind11_FIND_QUIETLY)\n  message(STATUS \"pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}\")\nendif()\n\n# Check if pybind11 is being used directly or via add_subdirectory\nif(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)\n  ### Warn if not an out-of-source builds\n  if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)\n    set(lines\n        \"You are building in-place. If that is not what you intended to \"\n        \"do, you can clean the source directory with:\\n\"\n        \"rm -r CMakeCache.txt CMakeFiles/ cmake_uninstall.cmake pybind11Config.cmake \"\n        \"pybind11ConfigVersion.cmake tests/CMakeFiles/\\n\")\n    message(AUTHOR_WARNING ${lines})\n  endif()\n\n  set(PYBIND11_MASTER_PROJECT ON)\n\n  message(STATUS \"CMake ${CMAKE_VERSION}\")\n\n  if(DEFINED SKBUILD AND DEFINED ENV{PYBIND11_GLOBAL_SDIST})\n    message(\n      FATAL_ERROR\n        \"PYBIND11_GLOBAL_SDIST is not supported, use nox -s build_global or a pybind11-global SDist instead.\"\n    )\n  endif()\n\n  if(CMAKE_CXX_STANDARD)\n    set(CMAKE_CXX_EXTENSIONS OFF)\n    set(CMAKE_CXX_STANDARD_REQUIRED ON)\n  endif()\n\n  set(pybind11_system \"\")\n\n  set_property(GLOBAL PROPERTY USE_FOLDERS ON)\n  if(CMAKE_VERSION VERSION_LESS \"3.18\")\n    set(_pybind11_findpython_default OFF)\n  else()\n    set(_pybind11_findpython_default ON)\n  endif()\nelse()\n  set(PYBIND11_MASTER_PROJECT OFF)\n  set(pybind11_system SYSTEM)\n  set(_pybind11_findpython_default COMPAT)\nendif()\n\n# Options\noption(PYBIND11_INSTALL \"Install pybind11 header files?\" ${PYBIND11_MASTER_PROJECT})\noption(PYBIND11_TEST \"Build pybind11 test suite?\" ${PYBIND11_MASTER_PROJECT})\noption(PYBIND11_NOPYTHON \"Disable search for Python\" OFF)\noption(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION\n       \"To enforce that a handle_type_name<> specialization exists\" OFF)\noption(PYBIND11_SIMPLE_GIL_MANAGEMENT\n       \"Use simpler GIL management logic that does not support disassociation\" OFF)\nset(PYBIND11_INTERNALS_VERSION\n    \"\"\n    CACHE STRING \"Override the ABI version, may be used to enable the unstable ABI.\")\noption(PYBIND11_USE_CROSSCOMPILING \"Respect CMAKE_CROSSCOMPILING\" OFF)\n\nif(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION)\n  add_compile_definitions(PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION)\nendif()\nif(PYBIND11_SIMPLE_GIL_MANAGEMENT)\n  add_compile_definitions(PYBIND11_SIMPLE_GIL_MANAGEMENT)\nendif()\n\ncmake_dependent_option(\n  USE_PYTHON_INCLUDE_DIR\n  \"Install pybind11 headers in Python include directory instead of default installation prefix\"\n  OFF \"PYBIND11_INSTALL\" OFF)\n\nset(PYBIND11_FINDPYTHON\n    ${_pybind11_findpython_default}\n    CACHE STRING \"Force new FindPython - NEW, OLD, COMPAT\")\n\nif(PYBIND11_MASTER_PROJECT)\n\n  # Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests\n  # (makes transition easier while we support both modes).\n  if(PYBIND11_FINDPYTHON\n     AND DEFINED PYTHON_EXECUTABLE\n     AND NOT DEFINED Python_EXECUTABLE)\n    set(Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\n  endif()\n\n  # This is a shortcut that is primarily for the venv cmake preset,\n  # but can be used to quickly setup tests manually, too\n  set(PYBIND11_CREATE_WITH_UV\n      \"\"\n      CACHE STRING \"Create a virtualenv if it doesn't exist\")\n\n  if(NOT PYBIND11_CREATE_WITH_UV STREQUAL \"\")\n    set(Python_ROOT_DIR \"${CMAKE_CURRENT_BINARY_DIR}/.venv\")\n    if(EXISTS \"${Python_ROOT_DIR}\")\n      if(EXISTS \"${CMAKE_BINARY_DIR}/CMakeCache.txt\")\n        message(STATUS \"Using existing venv at ${Python_ROOT_DIR}, remove or --fresh to recreate\")\n      else()\n        # --fresh used to remove the cache\n        file(REMOVE_RECURSE \"${CMAKE_CURRENT_BINARY_DIR}/.venv\")\n      endif()\n    endif()\n    if(NOT EXISTS \"${Python_ROOT_DIR}\")\n      find_program(UV uv REQUIRED)\n      # CMake 3.19+ would be able to use COMMAND_ERROR_IS_FATAL\n      message(\n        STATUS \"Creating venv with ${UV} venv -p ${PYBIND11_CREATE_WITH_UV} '${Python_ROOT_DIR}'\")\n      execute_process(COMMAND ${UV} venv -p ${PYBIND11_CREATE_WITH_UV} \"${Python_ROOT_DIR}\"\n                      RESULT_VARIABLE _venv_result)\n      if(_venv_result AND NOT _venv_result EQUAL 0)\n        message(FATAL_ERROR \"uv venv failed with '${_venv_result}'\")\n      endif()\n      message(\n        STATUS\n          \"Installing deps with ${UV} pip install -p '${Python_ROOT_DIR}' -r tests/requirements.txt\"\n      )\n      execute_process(\n        COMMAND ${UV} pip install -p \"${Python_ROOT_DIR}\" -r\n                \"${CMAKE_CURRENT_SOURCE_DIR}/tests/requirements.txt\" RESULT_VARIABLE _pip_result)\n      if(_pip_result AND NOT _pip_result EQUAL 0)\n        message(FATAL_ERROR \"uv pip install failed with '${_pip_result}'\")\n      endif()\n    endif()\n  else()\n    if(NOT DEFINED Python3_EXECUTABLE\n       AND NOT DEFINED Python_EXECUTABLE\n       AND NOT DEFINED Python_ROOT_DIR\n       AND NOT DEFINED ENV{VIRTUALENV}\n       AND EXISTS \"${CMAKE_CURRENT_SOURCE_DIR}/.venv\")\n      message(STATUS \"Autodetecting Python in virtual environment\")\n      set(Python_ROOT_DIR \"${CMAKE_CURRENT_SOURCE_DIR}/.venv\")\n    endif()\n  endif()\nendif()\n\nset(PYBIND11_HEADERS\n    include/pybind11/detail/argument_vector.h\n    include/pybind11/detail/class.h\n    include/pybind11/detail/common.h\n    include/pybind11/detail/cpp_conduit.h\n    include/pybind11/detail/descr.h\n    include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h\n    include/pybind11/detail/exception_translation.h\n    include/pybind11/detail/function_record_pyobject.h\n    include/pybind11/detail/function_ref.h\n    include/pybind11/detail/holder_caster_foreign_helpers.h\n    include/pybind11/detail/init.h\n    include/pybind11/detail/internals.h\n    include/pybind11/detail/native_enum_data.h\n    include/pybind11/detail/pybind11_namespace_macros.h\n    include/pybind11/detail/struct_smart_holder.h\n    include/pybind11/detail/type_caster_base.h\n    include/pybind11/detail/typeid.h\n    include/pybind11/detail/using_smart_holder.h\n    include/pybind11/detail/value_and_holder.h\n    include/pybind11/attr.h\n    include/pybind11/buffer_info.h\n    include/pybind11/cast.h\n    include/pybind11/chrono.h\n    include/pybind11/common.h\n    include/pybind11/complex.h\n    include/pybind11/conduit/pybind11_conduit_v1.h\n    include/pybind11/conduit/pybind11_platform_abi_id.h\n    include/pybind11/conduit/wrap_include_python_h.h\n    include/pybind11/critical_section.h\n    include/pybind11/options.h\n    include/pybind11/eigen.h\n    include/pybind11/eigen/common.h\n    include/pybind11/eigen/matrix.h\n    include/pybind11/eigen/tensor.h\n    include/pybind11/embed.h\n    include/pybind11/eval.h\n    include/pybind11/gil.h\n    include/pybind11/gil_safe_call_once.h\n    include/pybind11/gil_simple.h\n    include/pybind11/iostream.h\n    include/pybind11/functional.h\n    include/pybind11/native_enum.h\n    include/pybind11/numpy.h\n    include/pybind11/operators.h\n    include/pybind11/pybind11.h\n    include/pybind11/pytypes.h\n    include/pybind11/subinterpreter.h\n    include/pybind11/stl.h\n    include/pybind11/stl_bind.h\n    include/pybind11/stl/filesystem.h\n    include/pybind11/trampoline_self_life_support.h\n    include/pybind11/type_caster_pyobject_ptr.h\n    include/pybind11/typing.h\n    include/pybind11/warnings.h)\n\n# Compare with grep and warn if mismatched\nif(PYBIND11_MASTER_PROJECT)\n  file(\n    GLOB_RECURSE _pybind11_header_check\n    LIST_DIRECTORIES false\n    RELATIVE \"${CMAKE_CURRENT_SOURCE_DIR}\"\n    CONFIGURE_DEPENDS \"include/pybind11/*.h\")\n  set(_pybind11_here_only ${PYBIND11_HEADERS})\n  set(_pybind11_disk_only ${_pybind11_header_check})\n  list(REMOVE_ITEM _pybind11_here_only ${_pybind11_header_check})\n  list(REMOVE_ITEM _pybind11_disk_only ${PYBIND11_HEADERS})\n  if(_pybind11_here_only)\n    message(AUTHOR_WARNING \"PYBIND11_HEADERS has extra files:\" ${_pybind11_here_only})\n  endif()\n  if(_pybind11_disk_only)\n    message(AUTHOR_WARNING \"PYBIND11_HEADERS is missing files:\" ${_pybind11_disk_only})\n  endif()\nendif()\n\nlist(TRANSFORM PYBIND11_HEADERS PREPEND \"${CMAKE_CURRENT_SOURCE_DIR}/\")\n\n# Cache variable so this can be used in parent projects\nset(pybind11_INCLUDE_DIR\n    \"${CMAKE_CURRENT_LIST_DIR}/include\"\n    CACHE INTERNAL \"Directory where pybind11 headers are located\")\n\n# Backward compatible variable for add_subdirectory mode\nif(NOT PYBIND11_MASTER_PROJECT)\n  set(PYBIND11_INCLUDE_DIR\n      \"${pybind11_INCLUDE_DIR}\"\n      CACHE INTERNAL \"\")\nendif()\n\n# Note: when creating targets, you cannot use if statements at configure time -\n# you need generator expressions, because those will be placed in the target file.\n# You can also place ifs *in* the Config.in, but not here.\n\n# This section builds targets, but does *not* touch Python\n# Non-IMPORT targets cannot be defined twice\nif(NOT TARGET pybind11_headers)\n  # Build the headers-only target (no Python included):\n  # (long name used here to keep this from clashing in subdirectory mode)\n  add_library(pybind11_headers INTERFACE)\n  add_library(pybind11::pybind11_headers ALIAS pybind11_headers) # to match exported target\n  add_library(pybind11::headers ALIAS pybind11_headers) # easier to use/remember\n\n  target_include_directories(\n    pybind11_headers ${pybind11_system} INTERFACE $<BUILD_INTERFACE:${pybind11_INCLUDE_DIR}>\n                                                  $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)\n\n  target_compile_features(pybind11_headers INTERFACE cxx_inheriting_constructors cxx_user_literals\n                                                     cxx_right_angle_brackets)\n  if(NOT \"${PYBIND11_INTERNALS_VERSION}\" STREQUAL \"\")\n    target_compile_definitions(\n      pybind11_headers INTERFACE \"PYBIND11_INTERNALS_VERSION=${PYBIND11_INTERNALS_VERSION}\")\n  endif()\nelse()\n  # It is invalid to install a target twice, too.\n  set(PYBIND11_INSTALL OFF)\nendif()\n\ninclude(\"${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11Common.cmake\")\n# https://github.com/jtojnar/cmake-snips/#concatenating-paths-when-building-pkg-config-files\n# TODO: cmake 3.20 adds the cmake_path() function, which obsoletes this snippet\ninclude(\"${CMAKE_CURRENT_SOURCE_DIR}/tools/JoinPaths.cmake\")\n\n# Relative directory setting\nif(USE_PYTHON_INCLUDE_DIR AND DEFINED Python_INCLUDE_DIRS)\n  file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${Python_INCLUDE_DIRS})\nelseif(USE_PYTHON_INCLUDE_DIR AND DEFINED PYTHON_INCLUDE_DIR)\n  file(RELATIVE_PATH CMAKE_INSTALL_INCLUDEDIR ${CMAKE_INSTALL_PREFIX} ${PYTHON_INCLUDE_DIRS})\nendif()\n\nif(PYBIND11_INSTALL)\n  if(DEFINED SKBUILD_PROJECT_NAME AND SKBUILD_PROJECT_NAME STREQUAL \"pybind11_global\")\n    install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION \"${SKBUILD_HEADERS_DIR}\")\n  endif()\n  install(DIRECTORY ${pybind11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})\n  set(PYBIND11_CMAKECONFIG_INSTALL_DIR\n      \"${CMAKE_INSTALL_DATAROOTDIR}/cmake/${PROJECT_NAME}\"\n      CACHE STRING \"install path for pybind11Config.cmake\")\n\n  if(IS_ABSOLUTE \"${CMAKE_INSTALL_INCLUDEDIR}\")\n    set(pybind11_INCLUDEDIR \"${CMAKE_INSTALL_FULL_INCLUDEDIR}\")\n  else()\n    set(pybind11_INCLUDEDIR \"\\$\\{PACKAGE_PREFIX_DIR\\}/${CMAKE_INSTALL_INCLUDEDIR}\")\n  endif()\n\n  configure_package_config_file(\n    tools/${PROJECT_NAME}Config.cmake.in \"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake\"\n    INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})\n\n  # CMake natively supports header-only libraries\n  write_basic_package_version_file(\n    ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake\n    VERSION ${PROJECT_VERSION}\n    COMPATIBILITY AnyNewerVersion ARCH_INDEPENDENT)\n\n  install(\n    FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake\n          ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake\n          tools/FindPythonLibsNew.cmake\n          tools/pybind11Common.cmake\n          tools/pybind11Tools.cmake\n          tools/pybind11NewTools.cmake\n          tools/pybind11GuessPythonExtSuffix.cmake\n    DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})\n\n  if(NOT PYBIND11_EXPORT_NAME)\n    set(PYBIND11_EXPORT_NAME \"${PROJECT_NAME}Targets\")\n  endif()\n\n  install(TARGETS pybind11_headers EXPORT \"${PYBIND11_EXPORT_NAME}\")\n\n  install(\n    EXPORT \"${PYBIND11_EXPORT_NAME}\"\n    NAMESPACE \"pybind11::\"\n    DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR})\n\n  # pkg-config support\n  if(NOT prefix_for_pc_file)\n    if(IS_ABSOLUTE \"${CMAKE_INSTALL_DATAROOTDIR}\")\n      set(prefix_for_pc_file \"${CMAKE_INSTALL_PREFIX}\")\n    else()\n      set(pc_datarootdir \"${CMAKE_INSTALL_DATAROOTDIR}\")\n      if(CMAKE_VERSION VERSION_LESS 3.20)\n        set(prefix_for_pc_file \"\\${pcfiledir}/..\")\n        while(pc_datarootdir)\n          get_filename_component(pc_datarootdir \"${pc_datarootdir}\" DIRECTORY)\n          string(APPEND prefix_for_pc_file \"/..\")\n        endwhile()\n      else()\n        cmake_path(RELATIVE_PATH CMAKE_INSTALL_PREFIX BASE_DIRECTORY CMAKE_INSTALL_DATAROOTDIR\n                   OUTPUT_VARIABLE prefix_for_pc_file)\n      endif()\n    endif()\n  endif()\n  join_paths(includedir_for_pc_file \"\\${prefix}\" \"${CMAKE_INSTALL_INCLUDEDIR}\")\n  configure_file(\"${CMAKE_CURRENT_SOURCE_DIR}/tools/pybind11.pc.in\"\n                 \"${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc\" @ONLY)\n  install(FILES \"${CMAKE_CURRENT_BINARY_DIR}/pybind11.pc\"\n          DESTINATION \"${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/\")\n\n  # When building a wheel, include __init__.py's for modules\n  # (see https://github.com/pybind/pybind11/pull/5552)\n  if(DEFINED SKBUILD_PROJECT_NAME AND SKBUILD_PROJECT_NAME STREQUAL \"pybind11\")\n    file(MAKE_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/empty\")\n    file(TOUCH \"${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py\")\n    install(FILES \"${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py\"\n            DESTINATION \"${CMAKE_INSTALL_DATAROOTDIR}/\")\n    install(FILES \"${CMAKE_CURRENT_BINARY_DIR}/empty/__init__.py\"\n            DESTINATION \"${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig/\")\n  endif()\n\n  # Uninstall target\n  if(PYBIND11_MASTER_PROJECT)\n    configure_file(\"${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake_uninstall.cmake.in\"\n                   \"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake\" IMMEDIATE @ONLY)\n\n    add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P\n                                        ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)\n  endif()\nendif()\n\n# BUILD_TESTING takes priority, but only if this is the master project\nif(PYBIND11_MASTER_PROJECT AND DEFINED BUILD_TESTING)\n  if(BUILD_TESTING)\n    if(_pybind11_nopython)\n      message(FATAL_ERROR \"Cannot activate tests in NOPYTHON mode\")\n    else()\n      add_subdirectory(tests)\n    endif()\n  endif()\nelse()\n  if(PYBIND11_TEST)\n    if(_pybind11_nopython)\n      message(FATAL_ERROR \"Cannot activate tests in NOPYTHON mode\")\n    else()\n      add_subdirectory(tests)\n    endif()\n  endif()\nendif()\n\n# Better symmetry with find_package(pybind11 CONFIG) mode.\nif(NOT PYBIND11_MASTER_PROJECT)\n  set(pybind11_FOUND\n      TRUE\n      CACHE INTERNAL \"True if pybind11 and all required components found on the system\")\nendif()\n"
  },
  {
    "path": "CMakePresets.json",
    "content": "{\n  \"version\": 6,\n  \"configurePresets\": [\n    {\n      \"name\": \"default\",\n      \"displayName\": \"Default\",\n      \"binaryDir\": \"build\",\n      \"generator\": \"Ninja\",\n      \"errors\": {\n        \"dev\": true,\n        \"deprecated\": true\n      },\n      \"cacheVariables\": {\n        \"CMAKE_BUILD_TYPE\": \"Debug\",\n        \"CMAKE_EXPORT_COMPILE_COMMANDS\": true,\n        \"DOWNLOAD_CATCH\": true,\n        \"DOWNLOAD_EIGEN\": true,\n        \"PYBIND11_FINDPYTHON\": \"NEW\",\n        \"PYBIND11_WERROR\": true,\n        \"CMAKE_COLOR_DIAGNOSTICS\": true\n      }\n    },\n    {\n      \"name\": \"venv\",\n      \"displayName\": \"Venv\",\n      \"inherits\": \"default\",\n      \"cacheVariables\": {\n        \"PYBIND11_CREATE_WITH_UV\": \"python3\",\n        \"Python_ROOT_DIR\": \".venv\"\n      }\n    },\n    {\n      \"name\": \"tidy\",\n      \"displayName\": \"Clang-tidy\",\n      \"inherits\": \"default\",\n      \"binaryDir\": \"build-tidy\",\n      \"cacheVariables\": {\n        \"CMAKE_CXX_CLANG_TIDY\": \"clang-tidy;--use-color;--warnings-as-errors=*\",\n        \"CMAKE_CXX_STANDARD\": \"17\"\n      }\n    }\n  ],\n  \"buildPresets\": [\n    {\n      \"name\": \"default\",\n      \"displayName\": \"Default Build\",\n      \"configurePreset\": \"default\"\n    },\n    {\n      \"name\": \"venv\",\n      \"displayName\": \"Venv Build\",\n      \"configurePreset\": \"venv\"\n    },\n    {\n      \"name\": \"tidy\",\n      \"displayName\": \"Clang-tidy Build\",\n      \"configurePreset\": \"tidy\",\n      \"nativeToolOptions\": [\"-k0\"]\n    },\n    {\n      \"name\": \"tests\",\n      \"displayName\": \"Tests (for workflow)\",\n      \"configurePreset\": \"default\",\n      \"targets\": [\"pytest\", \"cpptest\", \"test_cmake_build\", \"test_cross_module_rtti\"]\n    },\n    {\n      \"name\": \"testsvenv\",\n      \"displayName\": \"Tests Venv (for workflow)\",\n      \"configurePreset\": \"venv\",\n      \"targets\": [\"pytest\", \"cpptest\", \"test_cmake_build\", \"test_cross_module_rtti\"]\n    }\n  ],\n  \"workflowPresets\": [\n    {\n      \"name\": \"default\",\n      \"displayName\": \"Default Workflow\",\n      \"steps\": [\n        { \"type\": \"configure\", \"name\": \"default\" },\n        { \"type\": \"build\", \"name\": \"default\" },\n        { \"type\": \"build\", \"name\": \"tests\" }\n      ]\n    },\n    {\n      \"name\": \"venv\",\n      \"displayName\": \"Default Workflow\",\n      \"steps\": [\n        { \"type\": \"configure\", \"name\": \"venv\" },\n        { \"type\": \"build\", \"name\": \"venv\" },\n        { \"type\": \"build\", \"name\": \"testsvenv\" }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nPlease also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of\nexternal contributions to this project including patches, pull requests, etc.\n"
  },
  {
    "path": "README.rst",
    "content": ".. figure:: https://github.com/pybind/pybind11/raw/master/docs/pybind11-logo.png\n   :alt: pybind11 logo\n\n**pybind11 (v3)  — Seamless interoperability between C++ and Python**\n\n|Latest Documentation Status| |Stable Documentation Status| |Gitter chat| |GitHub Discussions|\n\n|CI| |Build status| |SPEC 4 — Using and Creating Nightly Wheels|\n\n|Repology| |PyPI package| |Conda-forge| |Python Versions|\n\n`Setuptools example <https://github.com/pybind/python_example>`_\n• `Scikit-build example <https://github.com/pybind/scikit_build_example>`_\n• `CMake example <https://github.com/pybind/cmake_example>`_\n\n.. start\n\n\n**pybind11** is a lightweight header-only library that exposes C++ types\nin Python and vice versa, mainly to create Python bindings of existing\nC++ code. Its goals and syntax are similar to the excellent\n`Boost.Python <http://www.boost.org/doc/libs/1_58_0/libs/python/doc/>`_\nlibrary by David Abrahams: to minimize boilerplate code in traditional\nextension modules by inferring type information using compile-time\nintrospection.\n\nThe main issue with Boost.Python—and the reason for creating such a\nsimilar project—is Boost. Boost is an enormously large and complex suite\nof utility libraries that works with almost every C++ compiler in\nexistence. This compatibility has its cost: arcane template tricks and\nworkarounds are necessary to support the oldest and buggiest of compiler\nspecimens. Now that C++11-compatible compilers are widely available,\nthis heavy machinery has become an excessively large and unnecessary\ndependency.\n\nThink of this library as a tiny self-contained version of Boost.Python\nwith everything stripped away that isn't relevant for binding\ngeneration. Without comments, the core header files only require ~4K\nlines of code and depend on Python (CPython 3.8+, PyPy, or GraalPy) and the C++\nstandard library. This compact implementation was possible thanks to some C++11\nlanguage features (specifically: tuples, lambda functions and variadic\ntemplates). Since its creation, this library has grown beyond Boost.Python in\nmany ways, leading to dramatically simpler binding code in many common\nsituations.\n\nTutorial and reference documentation is provided at\n`pybind11.readthedocs.io <https://pybind11.readthedocs.io/en/latest>`_.\nA PDF version of the manual is available\n`here <https://pybind11.readthedocs.io/_/downloads/en/latest/pdf/>`_.\nAnd the source code is always available at\n`github.com/pybind/pybind11 <https://github.com/pybind/pybind11>`_.\n\n\nCore features\n-------------\n\n\npybind11 can map the following core C++ features to Python:\n\n- Functions accepting and returning custom data structures per value,\n  reference, or pointer\n- Instance methods and static methods\n- Overloaded functions\n- Instance attributes and static attributes\n- Arbitrary exception types\n- Enumerations\n- Callbacks\n- Iterators and ranges\n- Custom operators\n- Single and multiple inheritance\n- STL data structures\n- Smart pointers with reference counting like ``std::shared_ptr``\n- Internal references with correct reference counting\n- C++ classes with virtual (and pure virtual) methods can be extended\n  in Python\n- Integrated NumPy support (NumPy 2 requires pybind11 2.12+)\n\nGoodies\n-------\n\nIn addition to the core functionality, pybind11 provides some extra\ngoodies:\n\n- CPython 3.8+, PyPy3 7.3.17+, and GraalPy 24.1+ are supported with an\n  implementation-agnostic interface (see older versions for older CPython\n  and PyPy versions).\n\n- It is possible to bind C++11 lambda functions with captured\n  variables. The lambda capture data is stored inside the resulting\n  Python function object.\n\n- pybind11 uses C++11 move constructors and move assignment operators\n  whenever possible to efficiently transfer custom data types.\n\n- It's easy to expose the internal storage of custom data types through\n  Pythons' buffer protocols. This is handy e.g. for fast conversion\n  between C++ matrix classes like Eigen and NumPy without expensive\n  copy operations.\n\n- pybind11 can automatically vectorize functions so that they are\n  transparently applied to all entries of one or more NumPy array\n  arguments.\n\n- Python's slice-based access and assignment operations can be\n  supported with just a few lines of code.\n\n- Everything is contained in just a few header files; there is no need\n  to link against any additional libraries.\n\n- Binaries are generally smaller by a factor of at least 2 compared to\n  equivalent bindings generated by Boost.Python. A recent pybind11\n  conversion of PyRosetta, an enormous Boost.Python binding project,\n  `reported <https://graylab.jhu.edu/Sergey/2016.RosettaCon/PyRosetta-4.pdf>`_\n  a binary size reduction of **5.4x** and compile time reduction by\n  **5.8x**.\n\n- Function signatures are precomputed at compile time (using\n  ``constexpr``), leading to smaller binaries.\n\n- With little extra effort, C++ types can be pickled and unpickled\n  similar to regular Python objects.\n\nSupported platforms & compilers\n-------------------------------\n\npybind11 is exercised in continuous integration across a range of operating\nsystems, Python versions, C++ standards, and toolchains. For an up-to-date\nview of the combinations we currently test, please see the\n`pybind11 GitHub Actions <https://github.com/pybind/pybind11/actions?query=branch%3Amaster>`_\nlogs.\n\nThe test matrix naturally evolves over time as older platforms and compilers\nfall out of use and new ones are added by the community. Closely related\nversions of a tested compiler or platform will often work as well in practice,\nbut we cannot promise to validate every possible combination. If a\nconfiguration you rely on is missing from the matrix or regresses, issues and\npull requests to extend coverage are very welcome. At the same time, we need\nto balance the size of the test matrix with the available CI resources,\nsuch as GitHub's limits on concurrent jobs under the free tier.\n\nAbout\n-----\n\nThis project was created by `Wenzel\nJakob <http://rgl.epfl.ch/people/wjakob>`_. Significant features and/or\nimprovements to the code were contributed by\nJonas Adler,\nLori A. Burns,\nSylvain Corlay,\nEric Cousineau,\nAaron Gokaslan,\nRalf Grosse-Kunstleve,\nTrent Houliston,\nAxel Huebl,\n@hulucc,\nYannick Jadoul,\nSergey Lyskov,\nJohan Mabille,\nTomasz Miąsko,\nDean Moldovan,\nBen Pritchard,\nJason Rhinelander,\nBoris Schäling,\nPim Schellart,\nHenry Schreiner,\nIvan Smirnov,\nDustin Spicuzza,\nBoris Staletic,\nEthan Steinberg,\nPatrick Stewart,\nIvor Wanders,\nand\nXiaofei Wang.\n\nWe thank Google for a generous financial contribution to the continuous\nintegration infrastructure used by this project.\n\n\nContributing\n~~~~~~~~~~~~\n\nSee the `contributing\nguide <https://github.com/pybind/pybind11/blob/master/.github/CONTRIBUTING.md>`_\nfor information on building and contributing to pybind11.\n\nLicense\n~~~~~~~\n\npybind11 is provided under a BSD-style license that can be found in the\n`LICENSE <https://github.com/pybind/pybind11/blob/master/LICENSE>`_\nfile. By using, distributing, or contributing to this project, you agree\nto the terms and conditions of this license.\n\n.. |Latest Documentation Status| image:: https://readthedocs.org/projects/pybind11/badge?version=latest\n   :target: http://pybind11.readthedocs.org/en/latest\n.. |Stable Documentation Status| image:: https://img.shields.io/badge/docs-stable-blue.svg\n   :target: http://pybind11.readthedocs.org/en/stable\n.. |Gitter chat| image:: https://img.shields.io/gitter/room/gitterHQ/gitter.svg\n   :target: https://gitter.im/pybind/Lobby\n.. |CI| image:: https://github.com/pybind/pybind11/workflows/CI/badge.svg\n   :target: https://github.com/pybind/pybind11/actions\n.. |Build status| image:: https://ci.appveyor.com/api/projects/status/riaj54pn4h08xy40?svg=true\n   :target: https://ci.appveyor.com/project/wjakob/pybind11\n.. |PyPI package| image:: https://img.shields.io/pypi/v/pybind11.svg\n   :target: https://pypi.org/project/pybind11/\n.. |Conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pybind11.svg\n   :target: https://github.com/conda-forge/pybind11-feedstock\n.. |Repology| image:: https://repology.org/badge/latest-versions/python:pybind11.svg\n   :target: https://repology.org/project/python:pybind11/versions\n.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pybind11.svg\n   :target: https://pypi.org/project/pybind11/\n.. |GitHub Discussions| image:: https://img.shields.io/static/v1?label=Discussions&message=Ask&color=blue&logo=github\n   :target: https://github.com/pybind/pybind11/discussions\n.. |SPEC 4 — Using and Creating Nightly Wheels| image:: https://img.shields.io/badge/SPEC-4-green?labelColor=%23004811&color=%235CA038\n   :target: https://scientific-python.org/specs/spec-0004/\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\nSecurity updates are applied only to the latest release.\n\n## Reporting a Vulnerability\n\nIf you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released.\n\nPlease disclose it at [security advisory](https://github.com/pybind/pybind11/security/advisories/new).\n\nThis project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure.\n"
  },
  {
    "path": "docs/Doxyfile",
    "content": "PROJECT_NAME           = pybind11\nINPUT                  = ../include/pybind11/\nRECURSIVE              = YES\n\nGENERATE_HTML          = NO\nGENERATE_LATEX         = NO\nGENERATE_XML           = YES\nXML_OUTPUT             = .build/doxygenxml\nXML_PROGRAMLISTING     = YES\n\nMACRO_EXPANSION        = YES\nEXPAND_ONLY_PREDEF     = YES\nEXPAND_AS_DEFINED      = PYBIND11_RUNTIME_EXCEPTION\n\nALIASES                = \"rst=\\verbatim embed:rst\"\nALIASES               += \"endrst=\\endverbatim\"\n\nQUIET                  = YES\nWARNINGS               = YES\nWARN_IF_UNDOCUMENTED   = NO\nPREDEFINED             = PYBIND11_NOINLINE\n"
  },
  {
    "path": "docs/_static/css/custom.css",
    "content": ".highlight .go {\n  color: #707070;\n}\n"
  },
  {
    "path": "docs/advanced/cast/chrono.rst",
    "content": "Chrono\n======\n\nWhen including the additional header file :file:`pybind11/chrono.h` conversions\nfrom C++11 chrono datatypes to python datetime objects are automatically enabled.\nThis header also enables conversions of python floats (often from sources such\nas ``time.monotonic()``, ``time.perf_counter()`` and ``time.process_time()``)\ninto durations.\n\nAn overview of clocks in C++11\n------------------------------\n\nA point of confusion when using these conversions is the differences between\nclocks provided in C++11. There are three clock types defined by the C++11\nstandard and users can define their own if needed. Each of these clocks have\ndifferent properties and when converting to and from python will give different\nresults.\n\nThe first clock defined by the standard is ``std::chrono::system_clock``. This\nclock measures the current date and time. However, this clock changes with to\nupdates to the operating system time. For example, if your time is synchronised\nwith a time server this clock will change. This makes this clock a poor choice\nfor timing purposes but good for measuring the wall time.\n\nThe second clock defined in the standard is ``std::chrono::steady_clock``.\nThis clock ticks at a steady rate and is never adjusted. This makes it excellent\nfor timing purposes, however the value in this clock does not correspond to the\ncurrent date and time. Often this clock will be the amount of time your system\nhas been on, although it does not have to be. This clock will never be the same\nclock as the system clock as the system clock can change but steady clocks\ncannot.\n\nThe third clock defined in the standard is ``std::chrono::high_resolution_clock``.\nThis clock is the clock that has the highest resolution out of the clocks in the\nsystem. It is normally a typedef to either the system clock or the steady clock\nbut can be its own independent clock. This is important as when using these\nconversions as the types you get in python for this clock might be different\ndepending on the system.\nIf it is a typedef of the system clock, python will get datetime objects, but if\nit is a different clock they will be timedelta objects.\n\nProvided conversions\n--------------------\n\n.. rubric:: C++ to Python\n\n- ``std::chrono::system_clock::time_point`` → ``datetime.datetime``\n    System clock times are converted to python datetime instances. They are\n    in the local timezone, but do not have any timezone information attached\n    to them (they are naive datetime objects).\n\n- ``std::chrono::duration`` → ``datetime.timedelta``\n    Durations are converted to timedeltas, any precision in the duration\n    greater than microseconds is lost by rounding towards zero.\n\n- ``std::chrono::[other_clocks]::time_point`` → ``datetime.timedelta``\n    Any clock time that is not the system clock is converted to a time delta.\n    This timedelta measures the time from the clocks epoch to now.\n\n.. rubric:: Python to C++\n\n- ``datetime.datetime`` or ``datetime.date`` or ``datetime.time`` → ``std::chrono::system_clock::time_point``\n    Date/time objects are converted into system clock timepoints. Any\n    timezone information is ignored and the type is treated as a naive\n    object.\n\n- ``datetime.timedelta`` → ``std::chrono::duration``\n    Time delta are converted into durations with microsecond precision.\n\n- ``datetime.timedelta`` → ``std::chrono::[other_clocks]::time_point``\n    Time deltas that are converted into clock timepoints are treated as\n    the amount of time from the start of the clocks epoch.\n\n- ``float`` → ``std::chrono::duration``\n    Floats that are passed to C++ as durations be interpreted as a number of\n    seconds. These will be converted to the duration using ``duration_cast``\n    from the float.\n\n- ``float`` → ``std::chrono::[other_clocks]::time_point``\n    Floats that are passed to C++ as time points will be interpreted as the\n    number of seconds from the start of the clocks epoch.\n"
  },
  {
    "path": "docs/advanced/cast/custom.rst",
    "content": ".. _custom_type_caster:\n\nCustom type casters\n===================\n\nSome applications may prefer custom type casters that convert between existing\nPython types and C++ types, similar to the ``list`` ↔ ``std::vector``\nand ``dict`` ↔ ``std::map`` conversions which are built into pybind11.\nImplementing custom type casters is fairly advanced usage.\nWhile it is recommended to use the pybind11 API as much as possible, more complex examples may\nrequire familiarity with the intricacies of the Python C API.\nYou can refer to the `Python/C API Reference Manual <https://docs.python.org/3/c-api/index.html>`_\nfor more information.\n\nThe following snippets demonstrate how this works for a very simple ``Point2D`` type.\nWe want this type to be convertible to C++ from Python types implementing the\n``Sequence`` protocol and having two elements of type ``float``.\nWhen returned from C++ to Python, it should be converted to a Python ``tuple[float, float]``.\nFor this type we could provide Python bindings for different arithmetic functions implemented\nin C++ (here demonstrated by a simple ``negate`` function).\n\n..\n    PLEASE KEEP THE CODE BLOCKS IN SYNC WITH\n        tests/test_docs_advanced_cast_custom.cpp\n        tests/test_docs_advanced_cast_custom.py\n    Ideally, change the test, run pre-commit (incl. clang-format),\n    then copy the changed code back here.\n    Also use TEST_SUBMODULE in tests, but PYBIND11_MODULE in docs.\n\n.. code-block:: cpp\n\n    namespace user_space {\n\n    struct Point2D {\n        double x;\n        double y;\n    };\n\n    Point2D negate(const Point2D &point) { return Point2D{-point.x, -point.y}; }\n\n    } // namespace user_space\n\n\nThe following Python snippet demonstrates the intended usage of ``negate`` from the Python side:\n\n.. code-block:: python\n\n    from my_math_module import docs_advanced_cast_custom as m\n\n    point1 = [1.0, -1.0]\n    point2 = m.negate(point1)\n    assert point2 == (-1.0, 1.0)\n\nTo register the necessary conversion routines, it is necessary to add an\ninstantiation of the ``pybind11::detail::type_caster<T>`` template.\nAlthough this is an implementation detail, adding an instantiation of this\ntype is explicitly allowed.\n\n.. code-block:: cpp\n\n    namespace pybind11 {\n    namespace detail {\n\n    template <>\n    struct type_caster<user_space::Point2D> {\n        // This macro inserts a lot of boilerplate code and sets the type hint.\n        // `io_name` is used to specify different type hints for arguments and return values.\n        // The signature of our negate function would then look like:\n        // `negate(Sequence[float]) -> tuple[float, float]`\n        PYBIND11_TYPE_CASTER(user_space::Point2D, io_name(\"Sequence[float]\", \"tuple[float, float]\"));\n\n        // C++ -> Python: convert `Point2D` to `tuple[float, float]`. The second and third arguments\n        // are used to indicate the return value policy and parent object (for\n        // return_value_policy::reference_internal) and are often ignored by custom casters.\n        // The return value should reflect the type hint specified by the second argument of `io_name`.\n        static handle\n        cast(const user_space::Point2D &number, return_value_policy /*policy*/, handle /*parent*/) {\n            return py::make_tuple(number.x, number.y).release();\n        }\n\n        // Python -> C++: convert a `PyObject` into a `Point2D` and return false upon failure. The\n        // second argument indicates whether implicit conversions should be allowed.\n        // The accepted types should reflect the type hint specified by the first argument of\n        // `io_name`.\n        bool load(handle src, bool /*convert*/) {\n            // Check if handle is a Sequence\n            if (!py::isinstance<py::sequence>(src)) {\n                return false;\n            }\n            auto seq = py::reinterpret_borrow<py::sequence>(src);\n            // Check if exactly two values are in the Sequence\n            if (seq.size() != 2) {\n                return false;\n            }\n            // Check if each element is either a float or an int\n            for (auto item : seq) {\n                if (!py::isinstance<py::float_>(item) && !py::isinstance<py::int_>(item)) {\n                    return false;\n                }\n            }\n            value.x = seq[0].cast<double>();\n            value.y = seq[1].cast<double>();\n            return true;\n        }\n    };\n\n    } // namespace detail\n    } // namespace pybind11\n\n    // Bind the negate function\n    PYBIND11_MODULE(docs_advanced_cast_custom, m, py::mod_gil_not_used()) { m.def(\"negate\", user_space::negate); }\n\n.. note::\n\n    A ``type_caster<T>`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires\n    that ``T`` is default-constructible (``value`` is first default constructed\n    and then ``load()`` assigns to it).\n\n.. note::\n    For further information on the ``return_value_policy`` argument of ``cast`` refer to :ref:`return_value_policies`.\n    To learn about the ``convert`` argument of ``load`` see :ref:`nonconverting_arguments`.\n\n.. warning::\n\n    When using custom type casters, it's important to declare them consistently\n    in every compilation unit of the Python extension module to satisfy the C++ One Definition Rule\n    (`ODR <https://en.cppreference.com/w/cpp/language/definition>`_). Otherwise,\n    undefined behavior can ensue.\n\n.. note::\n\n    Using the type hint ``Sequence[float]`` signals to static type checkers, that not only tuples may be\n    passed, but any type implementing the Sequence protocol, e.g., ``list[float]``.\n    Unfortunately, that loses the length information ``tuple[float, float]`` provides.\n    One way of still providing some length information in type hints is using ``typing.Annotated``, e.g.,\n    ``Annotated[Sequence[float], 2]``, or further add libraries like\n    `annotated-types <https://github.com/annotated-types/annotated-types>`_.\n"
  },
  {
    "path": "docs/advanced/cast/eigen.rst",
    "content": "Eigen\n#####\n\n`Eigen <http://eigen.tuxfamily.org>`_ is C++ header-based library for dense and\nsparse linear algebra. Due to its popularity and widespread adoption, pybind11\nprovides transparent conversion and limited mapping support between Eigen and\nScientific Python linear algebra data types.\n\nTo enable the built-in Eigen support you must include the optional header file\n:file:`pybind11/eigen.h`.\n\nPass-by-value\n=============\n\nWhen binding a function with ordinary Eigen dense object arguments (for\nexample, ``Eigen::MatrixXd``), pybind11 will accept any input value that is\nalready (or convertible to) a ``numpy.ndarray`` with dimensions compatible with\nthe Eigen type, copy its values into a temporary Eigen variable of the\nappropriate type, then call the function with this temporary variable.\n\nSparse matrices are similarly copied to or from\n``scipy.sparse.csr_matrix``/``scipy.sparse.csc_matrix`` objects.\n\nPass-by-reference\n=================\n\nOne major limitation of the above is that every data conversion implicitly\ninvolves a copy, which can be both expensive (for large matrices) and disallows\nbinding functions that change their (Matrix) arguments.  Pybind11 allows you to\nwork around this by using Eigen's ``Eigen::Ref<MatrixType>`` class much as you\nwould when writing a function taking a generic type in Eigen itself (subject to\nsome limitations discussed below).\n\nWhen calling a bound function accepting a ``Eigen::Ref<const MatrixType>``\ntype, pybind11 will attempt to avoid copying by using an ``Eigen::Map`` object\nthat maps into the source ``numpy.ndarray`` data: this requires both that the\ndata types are the same (e.g. ``dtype='float64'`` and ``MatrixType::Scalar`` is\n``double``); and that the storage is layout compatible.  The latter limitation\nis discussed in detail in the section below, and requires careful\nconsideration: by default, numpy matrices and Eigen matrices are *not* storage\ncompatible.\n\nIf the numpy matrix cannot be used as is (either because its types differ, e.g.\npassing an array of integers to an Eigen parameter requiring doubles, or\nbecause the storage is incompatible), pybind11 makes a temporary copy and\npasses the copy instead.\n\nWhen a bound function parameter is instead ``Eigen::Ref<MatrixType>`` (note the\nlack of ``const``), pybind11 will only allow the function to be called if it\ncan be mapped *and* if the numpy array is writeable (that is\n``a.flags.writeable`` is true).  Any access (including modification) made to\nthe passed variable will be transparently carried out directly on the\n``numpy.ndarray``.\n\nThis means you can write code such as the following and have it work as\nexpected:\n\n.. code-block:: cpp\n\n    void scale_by_2(Eigen::Ref<Eigen::VectorXd> v) {\n        v *= 2;\n    }\n\nNote, however, that you will likely run into limitations due to numpy and\nEigen's difference default storage order for data; see the below section on\n:ref:`storage_orders` for details on how to bind code that won't run into such\nlimitations.\n\n.. note::\n\n    Passing by reference is not supported for sparse types.\n\nReturning values to Python\n==========================\n\nWhen returning an ordinary dense Eigen matrix type to numpy (e.g.\n``Eigen::MatrixXd`` or ``Eigen::RowVectorXf``) pybind11 keeps the matrix and\nreturns a numpy array that directly references the Eigen matrix: no copy of the\ndata is performed.  The numpy array will have ``array.flags.owndata`` set to\n``False`` to indicate that it does not own the data, and the lifetime of the\nstored Eigen matrix will be tied to the returned ``array``.\n\nIf you bind a function with a non-reference, ``const`` return type (e.g.\n``const Eigen::MatrixXd``), the same thing happens except that pybind11 also\nsets the numpy array's ``writeable`` flag to false.\n\nIf you return an lvalue reference or pointer, the usual pybind11 rules apply,\nas dictated by the binding function's return value policy (see the\ndocumentation on :ref:`return_value_policies` for full details).  That means,\nwithout an explicit return value policy, lvalue references will be copied and\npointers will be managed by pybind11.  In order to avoid copying, you should\nexplicitly specify an appropriate return value policy, as in the following\nexample:\n\n.. code-block:: cpp\n\n    class MyClass {\n        Eigen::MatrixXd big_mat = Eigen::MatrixXd::Zero(10000, 10000);\n    public:\n        Eigen::MatrixXd &getMatrix() { return big_mat; }\n        const Eigen::MatrixXd &viewMatrix() { return big_mat; }\n    };\n\n    // Later, in binding code:\n    py::class_<MyClass>(m, \"MyClass\")\n        .def(py::init<>())\n        .def(\"copy_matrix\", &MyClass::getMatrix) // Makes a copy!\n        .def(\"get_matrix\", &MyClass::getMatrix, py::return_value_policy::reference_internal)\n        .def(\"view_matrix\", &MyClass::viewMatrix, py::return_value_policy::reference_internal)\n        ;\n\n.. code-block:: python\n\n    a = MyClass()\n    m = a.get_matrix()  # flags.writeable = True,  flags.owndata = False\n    v = a.view_matrix()  # flags.writeable = False, flags.owndata = False\n    c = a.copy_matrix()  # flags.writeable = True,  flags.owndata = True\n    # m[5,6] and v[5,6] refer to the same element, c[5,6] does not.\n\nNote in this example that ``py::return_value_policy::reference_internal`` is\nused to tie the life of the MyClass object to the life of the returned arrays.\n\nYou may also return an ``Eigen::Ref``, ``Eigen::Map`` or other map-like Eigen\nobject (for example, the return value of ``matrix.block()`` and related\nmethods) that map into a dense Eigen type.  When doing so, the default\nbehaviour of pybind11 is to simply reference the returned data: you must take\ncare to ensure that this data remains valid!  You may ask pybind11 to\nexplicitly *copy* such a return value by using the\n``py::return_value_policy::copy`` policy when binding the function.  You may\nalso use ``py::return_value_policy::reference_internal`` or a\n``py::keep_alive`` to ensure the data stays valid as long as the returned numpy\narray does.\n\nWhen returning such a reference of map, pybind11 additionally respects the\nreadonly-status of the returned value, marking the numpy array as non-writeable\nif the reference or map was itself read-only.\n\n.. note::\n\n    Sparse types are always copied when returned.\n\n.. _storage_orders:\n\nStorage orders\n==============\n\nPassing arguments via ``Eigen::Ref`` has some limitations that you must be\naware of in order to effectively pass matrices by reference.  First and\nforemost is that the default ``Eigen::Ref<MatrixType>`` class requires\ncontiguous storage along columns (for column-major types, the default in Eigen)\nor rows if ``MatrixType`` is specifically an ``Eigen::RowMajor`` storage type.\nThe former, Eigen's default, is incompatible with ``numpy``'s default row-major\nstorage, and so you will not be able to pass numpy arrays to Eigen by reference\nwithout making one of two changes.\n\n(Note that this does not apply to vectors (or column or row matrices): for such\ntypes the \"row-major\" and \"column-major\" distinction is meaningless).\n\nThe first approach is to change the use of ``Eigen::Ref<MatrixType>`` to the\nmore general ``Eigen::Ref<MatrixType, 0, Eigen::Stride<Eigen::Dynamic,\nEigen::Dynamic>>`` (or similar type with a fully dynamic stride type in the\nthird template argument).  Since this is a rather cumbersome type, pybind11\nprovides a ``py::EigenDRef<MatrixType>`` type alias for your convenience (along\nwith EigenDMap for the equivalent Map, and EigenDStride for just the stride\ntype).\n\nThis type allows Eigen to map into any arbitrary storage order.  This is not\nthe default in Eigen for performance reasons: contiguous storage allows\nvectorization that cannot be done when storage is not known to be contiguous at\ncompile time.  The default ``Eigen::Ref`` stride type allows non-contiguous\nstorage along the outer dimension (that is, the rows of a column-major matrix\nor columns of a row-major matrix), but not along the inner dimension.\n\nThis type, however, has the added benefit of also being able to map numpy array\nslices.  For example, the following (contrived) example uses Eigen with a numpy\nslice to multiply by 2 all coefficients that are both on even rows (0, 2, 4,\n...) and in columns 2, 5, or 8:\n\n.. code-block:: cpp\n\n    m.def(\"scale\", [](py::EigenDRef<Eigen::MatrixXd> m, double c) { m *= c; });\n\n.. code-block:: python\n\n    # a = np.array(...)\n    scale_by_2(myarray[0::2, 2:9:3])\n\nThe second approach to avoid copying is more intrusive: rearranging the\nunderlying data types to not run into the non-contiguous storage problem in the\nfirst place.  In particular, that means using matrices with ``Eigen::RowMajor``\nstorage, where appropriate, such as:\n\n.. code-block:: cpp\n\n    using RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    // Use RowMatrixXd instead of MatrixXd\n\nNow bound functions accepting ``Eigen::Ref<RowMatrixXd>`` arguments will be\ncallable with numpy's (default) arrays without involving a copying.\n\nYou can, alternatively, change the storage order that numpy arrays use by\nadding the ``order='F'`` option when creating an array:\n\n.. code-block:: python\n\n    myarray = np.array(source, order=\"F\")\n\nSuch an object will be passable to a bound function accepting an\n``Eigen::Ref<MatrixXd>`` (or similar column-major Eigen type).\n\nOne major caveat with this approach, however, is that it is not entirely as\neasy as simply flipping all Eigen or numpy usage from one to the other: some\noperations may alter the storage order of a numpy array.  For example, ``a2 =\narray.transpose()`` results in ``a2`` being a view of ``array`` that references\nthe same data, but in the opposite storage order!\n\nWhile this approach allows fully optimized vectorized calculations in Eigen, it\ncannot be used with array slices, unlike the first approach.\n\nWhen *returning* a matrix to Python (either a regular matrix, a reference via\n``Eigen::Ref<>``, or a map/block into a matrix), no special storage\nconsideration is required: the created numpy array will have the required\nstride that allows numpy to properly interpret the array, whatever its storage\norder.\n\nFailing rather than copying\n===========================\n\nThe default behaviour when binding ``Eigen::Ref<const MatrixType>`` Eigen\nreferences is to copy matrix values when passed a numpy array that does not\nconform to the element type of ``MatrixType`` or does not have a compatible\nstride layout.  If you want to explicitly avoid copying in such a case, you\nshould bind arguments using the ``py::arg().noconvert()`` annotation (as\ndescribed in the :ref:`nonconverting_arguments` documentation).\n\nThe following example shows an example of arguments that don't allow data\ncopying to take place:\n\n.. code-block:: cpp\n\n    // The method and function to be bound:\n    class MyClass {\n        // ...\n        double some_method(const Eigen::Ref<const MatrixXd> &matrix) { /* ... */ }\n    };\n    float some_function(const Eigen::Ref<const MatrixXf> &big,\n                        const Eigen::Ref<const MatrixXf> &small) {\n        // ...\n    }\n\n    // The associated binding code:\n    using namespace pybind11::literals; // for \"arg\"_a\n    py::class_<MyClass>(m, \"MyClass\")\n        // ... other class definitions\n        .def(\"some_method\", &MyClass::some_method, py::arg().noconvert());\n\n    m.def(\"some_function\", &some_function,\n        \"big\"_a.noconvert(), // <- Don't allow copying for this arg\n        \"small\"_a            // <- This one can be copied if needed\n    );\n\nWith the above binding code, attempting to call the ``some_method(m)``\nmethod on a ``MyClass`` object, or attempting to call ``some_function(m, m2)``\nwill raise a ``RuntimeError`` rather than making a temporary copy of the array.\nIt will, however, allow the ``m2`` argument to be copied into a temporary if\nnecessary.\n\nNote that explicitly specifying ``.noconvert()`` is not required for *mutable*\nEigen references (e.g. ``Eigen::Ref<MatrixXd>`` without ``const`` on the\n``MatrixXd``): mutable references will never be called with a temporary copy.\n\nVectors versus column/row matrices\n==================================\n\nEigen and numpy have fundamentally different notions of a vector.  In Eigen, a\nvector is simply a matrix with the number of columns or rows set to 1 at\ncompile time (for a column vector or row vector, respectively).  NumPy, in\ncontrast, has comparable 2-dimensional 1xN and Nx1 arrays, but *also* has\n1-dimensional arrays of size N.\n\nWhen passing a 2-dimensional 1xN or Nx1 array to Eigen, the Eigen type must\nhave matching dimensions: That is, you cannot pass a 2-dimensional Nx1 numpy\narray to an Eigen value expecting a row vector, or a 1xN numpy array as a\ncolumn vector argument.\n\nOn the other hand, pybind11 allows you to pass 1-dimensional arrays of length N\nas Eigen parameters.  If the Eigen type can hold a column vector of length N it\nwill be passed as such a column vector.  If not, but the Eigen type constraints\nwill accept a row vector, it will be passed as a row vector.  (The column\nvector takes precedence when both are supported, for example, when passing a\n1D numpy array to a MatrixXd argument).  Note that the type need not be\nexplicitly a vector: it is permitted to pass a 1D numpy array of size 5 to an\nEigen ``Matrix<double, Dynamic, 5>``: you would end up with a 1x5 Eigen matrix.\nPassing the same to an ``Eigen::MatrixXd`` would result in a 5x1 Eigen matrix.\n\nWhen returning an Eigen vector to numpy, the conversion is ambiguous: a row\nvector of length 4 could be returned as either a 1D array of length 4, or as a\n2D array of size 1x4.  When encountering such a situation, pybind11 compromises\nby considering the returned Eigen type: if it is a compile-time vector--that\nis, the type has either the number of rows or columns set to 1 at compile\ntime--pybind11 converts to a 1D numpy array when returning the value.  For\ninstances that are a vector only at run-time (e.g. ``MatrixXd``,\n``Matrix<float, Dynamic, 4>``), pybind11 returns the vector as a 2D array to\nnumpy.  If this isn't want you want, you can use ``array.reshape(...)`` to get\na view of the same data in the desired dimensions.\n\n.. seealso::\n\n    The file :file:`tests/test_eigen.cpp` contains a complete example that\n    shows how to pass Eigen sparse and dense data types in more detail.\n"
  },
  {
    "path": "docs/advanced/cast/functional.rst",
    "content": "Functional\n##########\n\nThe following features must be enabled by including :file:`pybind11/functional.h`.\n\n\nCallbacks and passing anonymous functions\n=========================================\n\nThe C++11 standard brought lambda functions and the generic polymorphic\nfunction wrapper ``std::function<>`` to the C++ programming language, which\nenable powerful new ways of working with functions. Lambda functions come in\ntwo flavors: stateless lambda function resemble classic function pointers that\nlink to an anonymous piece of code, while stateful lambda functions\nadditionally depend on captured variables that are stored in an anonymous\n*lambda closure object*.\n\nHere is a simple example of a C++ function that takes an arbitrary function\n(stateful or stateless) with signature ``int -> int`` as an argument and runs\nit with the value 10.\n\n.. code-block:: cpp\n\n    int func_arg(const std::function<int(int)> &f) {\n        return f(10);\n    }\n\nThe example below is more involved: it takes a function of signature ``int -> int``\nand returns another function of the same kind. The return value is a stateful\nlambda function, which stores the value ``f`` in the capture object and adds 1 to\nits return value upon execution.\n\n.. code-block:: cpp\n\n    std::function<int(int)> func_ret(const std::function<int(int)> &f) {\n        return [f](int i) {\n            return f(i) + 1;\n        };\n    }\n\nThis example demonstrates using python named parameters in C++ callbacks which\nrequires using ``py::cpp_function`` as a wrapper. Usage is similar to defining\nmethods of classes:\n\n.. code-block:: cpp\n\n    py::cpp_function func_cpp() {\n        return py::cpp_function([](int i) { return i+1; },\n           py::arg(\"number\"));\n    }\n\nAfter including the extra header file :file:`pybind11/functional.h`, it is almost\ntrivial to generate binding code for all of these functions.\n\n.. code-block:: cpp\n\n    #include <pybind11/functional.h>\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        m.def(\"func_arg\", &func_arg);\n        m.def(\"func_ret\", &func_ret);\n        m.def(\"func_cpp\", &func_cpp);\n    }\n\nThe following interactive session shows how to call them from Python.\n\n.. code-block:: pycon\n\n    $ python\n    >>> import example\n    >>> def square(i):\n    ...     return i * i\n    ...\n    >>> example.func_arg(square)\n    100L\n    >>> square_plus_1 = example.func_ret(square)\n    >>> square_plus_1(4)\n    17L\n    >>> plus_1 = func_cpp()\n    >>> plus_1(number=43)\n    44L\n\n.. warning::\n\n    Keep in mind that passing a function from C++ to Python (or vice versa)\n    will instantiate a piece of wrapper code that translates function\n    invocations between the two languages. Naturally, this translation\n    increases the computational cost of each function call somewhat. A\n    problematic situation can arise when a function is copied back and forth\n    between Python and C++ many times in a row, in which case the underlying\n    wrappers will accumulate correspondingly. The resulting long sequence of\n    C++ -> Python -> C++ -> ... roundtrips can significantly decrease\n    performance.\n\n    There is one exception: pybind11 detects case where a stateless function\n    (i.e. a function pointer or a lambda function without captured variables)\n    is passed as an argument to another C++ function exposed in Python. In this\n    case, there is no overhead. Pybind11 will extract the underlying C++\n    function pointer from the wrapped function to sidestep a potential C++ ->\n    Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`.\n\n.. note::\n\n    This functionality is very useful when generating bindings for callbacks in\n    C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.).\n\n    The file :file:`tests/test_callbacks.cpp` contains a complete example\n    that demonstrates how to work with callbacks and anonymous functions in\n    more detail.\n"
  },
  {
    "path": "docs/advanced/cast/index.rst",
    "content": ".. _type-conversions:\n\nType conversions\n################\n\nApart from enabling cross-language function calls, a fundamental problem\nthat a binding tool like pybind11 must address is to provide access to\nnative Python types in C++ and vice versa. There are three fundamentally\ndifferent ways to do this—which approach is preferable for a particular type\ndepends on the situation at hand.\n\n1. Use a native C++ type everywhere. In this case, the type must be wrapped\n   using pybind11-generated bindings so that Python can interact with it.\n\n2. Use a native Python type everywhere. It will need to be wrapped so that\n   C++ functions can interact with it.\n\n3. Use a native C++ type on the C++ side and a native Python type on the\n   Python side. pybind11 refers to this as a *type conversion*.\n\n   Type conversions are the most \"natural\" option in the sense that native\n   (non-wrapped) types are used everywhere. The main downside is that a copy\n   of the data must be made on every Python ↔ C++ transition: this is\n   needed since the C++ and Python versions of the same type generally won't\n   have the same memory layout.\n\n   pybind11 can perform many kinds of conversions automatically. An overview\n   is provided in the table \":ref:`conversion_table`\".\n\nThe following subsections discuss the differences between these options in more\ndetail. The main focus in this section is on type conversions, which represent\nthe last case of the above list.\n\n.. toctree::\n   :maxdepth: 1\n\n   overview\n   strings\n   stl\n   functional\n   chrono\n   eigen\n   custom\n"
  },
  {
    "path": "docs/advanced/cast/overview.rst",
    "content": "Overview\n########\n\n.. rubric:: 1. Native type in C++, wrapper in Python\n\nExposing a custom C++ type using :class:`py::class_` was covered in detail\nin the :doc:`/classes` section. There, the underlying data structure is\nalways the original C++ class while the :class:`py::class_` wrapper provides\na Python interface. Internally, when an object like this is sent from C++ to\nPython, pybind11 will just add the outer wrapper layer over the native C++\nobject. Getting it back from Python is just a matter of peeling off the\nwrapper.\n\n.. rubric:: 2. Wrapper in C++, native type in Python\n\nThis is the exact opposite situation. Now, we have a type which is native to\nPython, like a ``tuple`` or a ``list``. One way to get this data into C++ is\nwith the :class:`py::object` family of wrappers. These are explained in more\ndetail in the :doc:`/advanced/pycpp/object` section. We'll just give a quick\nexample here:\n\n.. code-block:: cpp\n\n    void print_list(py::list my_list) {\n        for (auto item : my_list)\n            std::cout << item << \" \";\n    }\n\n.. code-block:: pycon\n\n    >>> print_list([1, 2, 3])\n    1 2 3\n\nThe Python ``list`` is not converted in any way -- it's just wrapped in a C++\n:class:`py::list` class. At its core it's still a Python object. Copying a\n:class:`py::list` will do the usual reference-counting like in Python.\nReturning the object to Python will just remove the thin wrapper.\n\n.. rubric:: 3. Converting between native C++ and Python types\n\nIn the previous two cases we had a native type in one language and a wrapper in\nthe other. Now, we have native types on both sides and we convert between them.\n\n.. code-block:: cpp\n\n    void print_vector(const std::vector<int> &v) {\n        for (auto item : v)\n            std::cout << item << \"\\n\";\n    }\n\n.. code-block:: pycon\n\n    >>> print_vector([1, 2, 3])\n    1 2 3\n\nIn this case, pybind11 will construct a new ``std::vector<int>`` and copy each\nelement from the Python ``list``. The newly constructed object will be passed\nto ``print_vector``. The same thing happens in the other direction: a new\n``list`` is made to match the value returned from C++.\n\nLots of these conversions are supported out of the box, as shown in the table\nbelow. They are very convenient, but keep in mind that these conversions are\nfundamentally based on copying data. This is perfectly fine for small immutable\ntypes but it may become quite expensive for large data structures. This can be\navoided by overriding the automatic conversion with a custom wrapper (i.e. the\nabove-mentioned approach 1). This requires some manual effort and more details\nare available in the :ref:`opaque` section.\n\n.. _conversion_table:\n\nList of all builtin conversions\n-------------------------------\n\nThe following basic data types are supported out of the box (some may require\nan additional extension header to be included). To pass other data structures\nas arguments and return values, refer to the section on binding :ref:`classes`.\n\n+------------------------------------+---------------------------+-----------------------------------+\n|  Data type                         |  Description              | Header file                       |\n+====================================+===========================+===================================+\n| ``int8_t``, ``uint8_t``            | 8-bit integers            | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``int16_t``, ``uint16_t``          | 16-bit integers           | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``int32_t``, ``uint32_t``          | 32-bit integers           | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``int64_t``, ``uint64_t``          | 64-bit integers           | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``ssize_t``, ``size_t``            | Platform-dependent size   | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``float``, ``double``              | Floating point types      | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``bool``                           | Two-state Boolean type    | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``char``                           | Character literal         | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``char16_t``                       | UTF-16 character literal  | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``char32_t``                       | UTF-32 character literal  | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``wchar_t``                        | Wide character literal    | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``const char *``                   | UTF-8 string literal      | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``const char16_t *``               | UTF-16 string literal     | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``const char32_t *``               | UTF-32 string literal     | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``const wchar_t *``                | Wide string literal       | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::string``                    | STL dynamic UTF-8 string  | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::u16string``                 | STL dynamic UTF-16 string | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::u32string``                 | STL dynamic UTF-32 string | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::wstring``                   | STL dynamic wide string   | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::string_view``,              | STL C++17 string views    | :file:`pybind11/pybind11.h`       |\n| ``std::u16string_view``, etc.      |                           |                                   |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::pair<T1, T2>``              | Pair of two custom types  | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::tuple<...>``                | Arbitrary tuple of types  | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::reference_wrapper<...>``    | Reference type wrapper    | :file:`pybind11/pybind11.h`       |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::complex<T>``                | Complex numbers           | :file:`pybind11/complex.h`        |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::array<T, Size>``            | STL static array          | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::vector<T>``                 | STL dynamic array         | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::deque<T>``                  | STL double-ended queue    | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::valarray<T>``               | STL value array           | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::list<T>``                   | STL linked list           | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::map<T1, T2>``               | STL ordered map           | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::unordered_map<T1, T2>``     | STL unordered map         | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::set<T>``                    | STL ordered set           | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::unordered_set<T>``          | STL unordered set         | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::optional<T>``               | STL optional type (C++17) | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::experimental::optional<T>`` | STL optional type (exp.)  | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::variant<...>``              | Type-safe union (C++17)   | :file:`pybind11/stl.h`            |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::filesystem::path``          | STL path (C++17) [#]_     | :file:`pybind11/stl/filesystem.h` |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::function<...>``             | STL polymorphic function  | :file:`pybind11/functional.h`     |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::chrono::duration<...>``     | STL time duration         | :file:`pybind11/chrono.h`         |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``std::chrono::time_point<...>``   | STL date/time             | :file:`pybind11/chrono.h`         |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``Eigen::Matrix<...>``             | Eigen: dense matrix       | :file:`pybind11/eigen.h`          |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``Eigen::Map<...>``                | Eigen: mapped memory      | :file:`pybind11/eigen.h`          |\n+------------------------------------+---------------------------+-----------------------------------+\n| ``Eigen::SparseMatrix<...>``       | Eigen: sparse matrix      | :file:`pybind11/eigen.h`          |\n+------------------------------------+---------------------------+-----------------------------------+\n\n.. [#] ``std::filesystem::path`` is converted to ``pathlib.Path`` and\n   can be loaded from ``os.PathLike``, ``str``, and ``bytes``.\n"
  },
  {
    "path": "docs/advanced/cast/stl.rst",
    "content": "STL containers\n##############\n\nAutomatic conversion\n====================\n\nWhen including the additional header file :file:`pybind11/stl.h`, conversions\nbetween ``std::vector<>``/``std::deque<>``/``std::list<>``/``std::array<>``/``std::valarray<>``,\n``std::set<>``/``std::unordered_set<>``, and\n``std::map<>``/``std::unordered_map<>`` and the Python ``list``, ``set`` and\n``dict`` data structures are automatically enabled. The types ``std::pair<>``\nand ``std::tuple<>`` are already supported out of the box with just the core\n:file:`pybind11/pybind11.h` header.\n\nThe major downside of these implicit conversions is that containers must be\nconverted (i.e. copied) on every Python->C++ and C++->Python transition, which\ncan have implications on the program semantics and performance. Please read the\nnext sections for more details and alternative approaches that avoid this.\n\n.. note::\n\n    Arbitrary nesting of any of these types is possible.\n\n.. seealso::\n\n    The file :file:`tests/test_stl.cpp` contains a complete\n    example that demonstrates how to pass STL data types in more detail.\n\n.. _cpp17_container_casters:\n\nC++17 library containers\n========================\n\nThe :file:`pybind11/stl.h` header also includes support for ``std::optional<>``\nand ``std::variant<>``. These require a C++17 compiler and standard library.\nIn C++14 mode, ``std::experimental::optional<>`` is supported if available.\n\nVarious versions of these containers also exist for C++11 (e.g. in Boost).\npybind11 provides an easy way to specialize the ``type_caster`` for such\ntypes:\n\n.. code-block:: cpp\n\n    // `boost::optional` as an example -- can be any `std::optional`-like container\n    namespace PYBIND11_NAMESPACE { namespace detail {\n        template <typename T>\n        struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};\n    }}\n\nThe above should be placed in a header file and included in all translation units\nwhere automatic conversion is needed. Similarly, a specialization can be provided\nfor custom variant types:\n\n.. code-block:: cpp\n\n    // `boost::variant` as an example -- can be any `std::variant`-like container\n    namespace PYBIND11_NAMESPACE { namespace detail {\n        template <typename... Ts>\n        struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};\n\n        // Specifies the function used to visit the variant -- `apply_visitor` instead of `visit`\n        template <>\n        struct visit_helper<boost::variant> {\n            template <typename... Args>\n            static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {\n                return boost::apply_visitor(args...);\n            }\n        };\n    }} // namespace PYBIND11_NAMESPACE::detail\n\nThe ``visit_helper`` specialization is not required if your ``name::variant`` provides\na ``name::visit()`` function. For any other function name, the specialization must be\nincluded to tell pybind11 how to visit the variant.\n\n.. warning::\n\n    When converting a ``variant`` type, pybind11 follows the same rules as when\n    determining which function overload to call (:ref:`overload_resolution`), and\n    so the same caveats hold. In particular, the order in which the ``variant``'s\n    alternatives are listed is important, since pybind11 will try conversions in\n    this order. This means that, for example, when converting ``variant<int, bool>``,\n    the ``bool`` variant will never be selected, as any Python ``bool`` is already\n    an ``int`` and is convertible to a C++ ``int``. Changing the order of alternatives\n    (and using ``variant<bool, int>``, in this example) provides a solution.\n\n.. note::\n\n    pybind11 only supports the modern implementation of ``boost::variant``\n    which makes use of variadic templates. This requires Boost 1.56 or newer.\n\n.. _opaque:\n\nMaking opaque types\n===================\n\npybind11 heavily relies on a template matching mechanism to convert parameters\nand return values that are constructed from STL data types such as vectors,\nlinked lists, hash tables, etc. This even works in a recursive manner, for\ninstance to deal with lists of hash maps of pairs of elementary and custom\ntypes, etc.\n\nHowever, a fundamental limitation of this approach is that internal conversions\nbetween Python and C++ types involve a copy operation that prevents\npass-by-reference semantics. What does this mean?\n\nSuppose we bind the following function\n\n.. code-block:: cpp\n\n    void append_1(std::vector<int> &v) {\n       v.push_back(1);\n    }\n\nand call it from Python, the following happens:\n\n.. code-block:: pycon\n\n   >>> v = [5, 6]\n   >>> append_1(v)\n   >>> print(v)\n   [5, 6]\n\nAs you can see, when passing STL data structures by reference, modifications\nare not propagated back the Python side. A similar situation arises when\nexposing STL data structures using the ``def_readwrite`` or ``def_readonly``\nfunctions:\n\n.. code-block:: cpp\n\n    /* ... definition ... */\n\n    class MyClass {\n        std::vector<int> contents;\n    };\n\n    /* ... binding code ... */\n\n    py::class_<MyClass>(m, \"MyClass\")\n        .def(py::init<>())\n        .def_readwrite(\"contents\", &MyClass::contents);\n\nIn this case, properties can be read and written in their entirety. However, an\n``append`` operation involving such a list type has no effect:\n\n.. code-block:: pycon\n\n   >>> m = MyClass()\n   >>> m.contents = [5, 6]\n   >>> print(m.contents)\n   [5, 6]\n   >>> m.contents.append(7)\n   >>> print(m.contents)\n   [5, 6]\n\nFinally, the involved copy operations can be costly when dealing with very\nlarge lists. To deal with all of the above situations, pybind11 provides a\nmacro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based\nconversion machinery of types, thus rendering them *opaque*. The contents of\nopaque objects are never inspected or extracted, hence they *can* be passed by\nreference. For instance, to turn ``std::vector<int>`` into an opaque type, add\nthe declaration\n\n.. code-block:: cpp\n\n    PYBIND11_MAKE_OPAQUE(std::vector<int>)\n\nbefore any binding code (e.g. invocations to ``class_::def()``, etc.). This\nmacro must be specified at the top level (and outside of any namespaces), since\nit adds a template instantiation of ``type_caster``. If your binding code consists of\nmultiple compilation units, it must be present in every file (typically via a\ncommon header) preceding any usage of ``std::vector<int>``. Opaque types must\nalso have a corresponding ``py::class_`` declaration to associate them with a\nname in Python, and to define a set of available operations, e.g.:\n\n.. code-block:: cpp\n\n    py::class_<std::vector<int>>(m, \"IntVector\")\n        .def(py::init<>())\n        .def(\"clear\", &std::vector<int>::clear)\n        .def(\"pop_back\", &std::vector<int>::pop_back)\n        .def(\"__len__\", [](const std::vector<int> &v) { return v.size(); })\n        .def(\"__iter__\", [](std::vector<int> &v) {\n           return py::make_iterator(v.begin(), v.end());\n        }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */\n        // ....\n\n.. seealso::\n\n    The file :file:`tests/test_opaque_types.cpp` contains a complete\n    example that demonstrates how to create and expose opaque types using\n    pybind11 in more detail.\n\n.. _stl_bind:\n\nBinding STL containers\n======================\n\nThe ability to expose STL containers as native Python objects is a fairly\ncommon request, hence pybind11 also provides an optional header file named\n:file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try\nto match the behavior of their native Python counterparts as much as possible.\n\nThe following example showcases usage of :file:`pybind11/stl_bind.h`:\n\n.. code-block:: cpp\n\n    // Don't forget this\n    #include <pybind11/stl_bind.h>\n\n    PYBIND11_MAKE_OPAQUE(std::vector<int>)\n    PYBIND11_MAKE_OPAQUE(std::map<std::string, double>)\n\n    // ...\n\n    // later in binding code:\n    py::bind_vector<std::vector<int>>(m, \"VectorInt\");\n    py::bind_map<std::map<std::string, double>>(m, \"MapStringDouble\");\n\nWhen binding STL containers pybind11 considers the types of the container's\nelements to decide whether the container should be confined to the local module\n(via the :ref:`module_local` feature).  If the container element types are\nanything other than already-bound custom types bound without\n``py::module_local()`` the container binding will have ``py::module_local()``\napplied.  This includes converting types such as numeric types, strings, Eigen\ntypes; and types that have not yet been bound at the time of the stl container\nbinding.  This module-local binding is designed to avoid potential conflicts\nbetween module bindings (for example, from two separate modules each attempting\nto bind ``std::vector<int>`` as a python type).\n\nIt is possible to override this behavior to force a definition to be either\nmodule-local or global.  To do so, you can pass the attributes\n``py::module_local()`` (to make the binding module-local) or\n``py::module_local(false)`` (to make the binding global) into the\n``py::bind_vector`` or ``py::bind_map`` arguments:\n\n.. code-block:: cpp\n\n    py::bind_vector<std::vector<int>>(m, \"VectorInt\", py::module_local(false));\n\nNote, however, that such a global binding would make it impossible to load this\nmodule at the same time as any other pybind module that also attempts to bind\nthe same container type (``std::vector<int>`` in the above example).\n\nSee :ref:`module_local` for more details on module-local bindings.\n\n.. seealso::\n\n    The file :file:`tests/test_stl_binders.cpp` shows how to use the\n    convenience STL container wrappers.\n"
  },
  {
    "path": "docs/advanced/cast/strings.rst",
    "content": "Strings, bytes and Unicode conversions\n######################################\n\nPassing Python strings to C++\n=============================\n\nWhen a Python ``str`` is passed from Python to a C++ function that accepts\n``std::string`` or ``char *`` as arguments, pybind11 will encode the Python\nstring to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation\ndoes not fail.\n\nThe C++ language is encoding agnostic. It is the responsibility of the\nprogrammer to track encodings. It's often easiest to simply `use UTF-8\neverywhere <http://utf8everywhere.org/>`_.\n\n.. code-block:: c++\n\n    m.def(\"utf8_test\",\n        [](const std::string &s) {\n            cout << \"utf-8 is icing on the cake.\\n\";\n            cout << s;\n        }\n    );\n    m.def(\"utf8_charptr\",\n        [](const char *s) {\n            cout << \"My favorite food is\\n\";\n            cout << s;\n        }\n    );\n\n.. code-block:: pycon\n\n    >>> utf8_test(\"🎂\")\n    utf-8 is icing on the cake.\n    🎂\n\n    >>> utf8_charptr(\"🍕\")\n    My favorite food is\n    🍕\n\n.. note::\n\n    Some terminal emulators do not support UTF-8 or emoji fonts and may not\n    display the example above correctly.\n\nThe results are the same whether the C++ function accepts arguments by value or\nreference, and whether or not ``const`` is used.\n\nPassing bytes to C++\n--------------------\n\nA Python ``bytes`` object will be passed to C++ functions that accept\n``std::string`` or ``char*`` *without* conversion.  In order to make a function\n*only* accept ``bytes`` (and not ``str``), declare it as taking a ``py::bytes``\nargument.\n\n\nReturning C++ strings to Python\n===============================\n\nWhen a C++ function returns a ``std::string`` or ``char*`` to a Python caller,\n**pybind11 will assume that the string is valid UTF-8** and will decode it to a\nnative Python ``str``, using the same API as Python uses to perform\n``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will\nraise a ``UnicodeDecodeError``.\n\n.. code-block:: c++\n\n    m.def(\"std_string_return\",\n        []() {\n            return std::string(\"This string needs to be UTF-8 encoded\");\n        }\n    );\n\n.. code-block:: pycon\n\n    >>> isinstance(example.std_string_return(), str)\n    True\n\n\nBecause UTF-8 is inclusive of pure ASCII, there is never any issue with\nreturning a pure ASCII string to Python. If there is any possibility that the\nstring is not pure ASCII, it is necessary to ensure the encoding is valid\nUTF-8.\n\n.. warning::\n\n    Implicit conversion assumes that a returned ``char *`` is null-terminated.\n    If there is no null terminator a buffer overrun will occur.\n\nExplicit conversions\n--------------------\n\nIf some C++ code constructs a ``std::string`` that is not a UTF-8 string, one\ncan perform a explicit conversion and return a ``py::str`` object. Explicit\nconversion has the same overhead as implicit conversion.\n\n.. code-block:: c++\n\n    // This uses the Python C API to convert Latin-1 to Unicode\n    m.def(\"str_output\",\n        []() {\n            std::string s = \"Send your r\\xe9sum\\xe9 to Alice in HR\"; // Latin-1\n            py::handle py_s = PyUnicode_DecodeLatin1(s.data(), s.length(), nullptr);\n            if (!py_s) {\n                throw py::error_already_set();\n            }\n            return py::reinterpret_steal<py::str>(py_s);\n        }\n    );\n\n.. code-block:: pycon\n\n    >>> str_output()\n    'Send your résumé to Alice in HR'\n\nThe `Python C API\n<https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides\nseveral built-in codecs. Note that these all return *new* references, so\nuse :cpp:func:`reinterpret_steal` when converting them to a :cpp:class:`str`.\n\n\nOne could also use a third party encoding library such as libiconv to transcode\nto UTF-8.\n\nReturn C++ strings without conversion\n-------------------------------------\n\nIf the data in a C++ ``std::string`` does not represent text and should be\nreturned to Python as ``bytes``, then one can return the data as a\n``py::bytes`` object.\n\n.. code-block:: c++\n\n    m.def(\"return_bytes\",\n        []() {\n            std::string s(\"\\xba\\xd0\\xba\\xd0\");  // Not valid UTF-8\n            return py::bytes(s);  // Return the data without transcoding\n        }\n    );\n\n.. code-block:: pycon\n\n    >>> example.return_bytes()\n    b'\\xba\\xd0\\xba\\xd0'\n\n\nNote the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without\nencoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.\n\n.. code-block:: c++\n\n    m.def(\"asymmetry\",\n        [](std::string s) {  // Accepts str or bytes from Python\n            return s;  // Looks harmless, but implicitly converts to str\n        }\n    );\n\n.. code-block:: pycon\n\n    >>> isinstance(example.asymmetry(b\"have some bytes\"), str)\n    True\n\n    >>> example.asymmetry(b\"\\xba\\xd0\\xba\\xd0\")  # invalid utf-8 as bytes\n    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte\n\n\nWide character strings\n======================\n\nWhen a Python ``str`` is passed to a C++ function expecting ``std::wstring``,\n``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be\nencoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each\ntype, in the platform's native endianness. When strings of these types are\nreturned, they are assumed to contain valid UTF-16 or UTF-32, and will be\ndecoded to Python ``str``.\n\n.. code-block:: c++\n\n    #define UNICODE\n    #include <windows.h>\n\n    m.def(\"set_window_text\",\n        [](HWND hwnd, std::wstring s) {\n            // Call SetWindowText with null-terminated UTF-16 string\n            ::SetWindowText(hwnd, s.c_str());\n        }\n    );\n    m.def(\"get_window_text\",\n        [](HWND hwnd) {\n            const int buffer_size = ::GetWindowTextLength(hwnd) + 1;\n            auto buffer = std::make_unique< wchar_t[] >(buffer_size);\n\n            ::GetWindowText(hwnd, buffer.data(), buffer_size);\n\n            std::wstring text(buffer.get());\n\n            // wstring will be converted to Python str\n            return text;\n        }\n    );\n\nStrings in multibyte encodings such as Shift-JIS must transcoded to a\nUTF-8/16/32 before being returned to Python.\n\n\nCharacter literals\n==================\n\nC++ functions that accept character literals as input will receive the first\ncharacter of a Python ``str`` as their input. If the string is longer than one\nUnicode character, trailing characters will be ignored.\n\nWhen a character literal is returned from C++ (such as a ``char`` or a\n``wchar_t``), it will be converted to a ``str`` that represents the single\ncharacter.\n\n.. code-block:: c++\n\n    m.def(\"pass_char\", [](char c) { return c; });\n    m.def(\"pass_wchar\", [](wchar_t w) { return w; });\n\n.. code-block:: pycon\n\n    >>> example.pass_char(\"A\")\n    'A'\n\nWhile C++ will cast integers to character types (``char c = 0x65;``), pybind11\ndoes not convert Python integers to characters implicitly. The Python function\n``chr()`` can be used to convert integers to characters.\n\n.. code-block:: pycon\n\n    >>> example.pass_char(0x65)\n    TypeError\n\n    >>> example.pass_char(chr(0x65))\n    'A'\n\nIf the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``\nas the argument type.\n\nGrapheme clusters\n-----------------\n\nA single grapheme may be represented by two or more Unicode characters. For\nexample 'é' is usually represented as U+00E9 but can also be expressed as the\ncombining character sequence U+0065 U+0301 (that is, the letter 'e' followed by\na combining acute accent). The combining character will be lost if the\ntwo-character sequence is passed as an argument, even though it renders as a\nsingle grapheme.\n\n.. code-block:: pycon\n\n    >>> example.pass_wchar(\"é\")\n    'é'\n\n    >>> combining_e_acute = \"e\" + \"\\u0301\"\n\n    >>> combining_e_acute\n    'é'\n\n    >>> combining_e_acute == \"é\"\n    False\n\n    >>> example.pass_wchar(combining_e_acute)\n    'e'\n\nNormalizing combining characters before passing the character literal to C++\nmay resolve *some* of these issues:\n\n.. code-block:: pycon\n\n    >>> example.pass_wchar(unicodedata.normalize(\"NFC\", combining_e_acute))\n    'é'\n\nIn some languages (Thai for example), there are `graphemes that cannot be\nexpressed as a single Unicode code point\n<http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is\nno way to capture them in a C++ character type.\n\n\nC++17 string views\n==================\n\nC++17 string views are automatically supported when compiling in C++17 mode.\nThey follow the same rules for encoding and decoding as the corresponding STL\nstring type (for example, a ``std::u16string_view`` argument will be passed\nUTF-16-encoded data, and a returned ``std::string_view`` will be decoded as\nUTF-8).\n\nReferences\n==========\n\n* `The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_\n* `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_\n"
  },
  {
    "path": "docs/advanced/classes.rst",
    "content": "Classes\n#######\n\nThis section presents advanced binding code for classes and it is assumed\nthat you are already familiar with the basics from :doc:`/classes`.\n\n.. _overriding_virtuals:\n\nOverriding virtual functions in Python\n======================================\n\nSuppose that a C++ class or interface has a virtual function that we'd like\nto override from within Python (we'll focus on the class ``Animal``; ``Dog`` is\ngiven as a specific example of how one would do this with traditional C++\ncode).\n\n.. code-block:: cpp\n\n    class Animal {\n    public:\n        virtual ~Animal() { }\n        virtual std::string go(int n_times) = 0;\n    };\n\n    class Dog : public Animal {\n    public:\n        std::string go(int n_times) override {\n            std::string result;\n            for (int i=0; i<n_times; ++i)\n                result += \"woof! \";\n            return result;\n        }\n    };\n\nLet's also suppose that we are given a plain function which calls the\nfunction ``go()`` on an arbitrary ``Animal`` instance.\n\n.. code-block:: cpp\n\n    std::string call_go(Animal *animal) {\n        return animal->go(3);\n    }\n\nNormally, the binding code for these classes would look as follows:\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Animal>(m, \"Animal\")\n            .def(\"go\", &Animal::go);\n\n        py::class_<Dog, Animal>(m, \"Dog\")\n            .def(py::init<>());\n\n        m.def(\"call_go\", &call_go);\n    }\n\nHowever, these bindings are impossible to extend: ``Animal`` is not\nconstructible, and we clearly require some kind of \"trampoline\" that\nredirects virtual calls back to Python.\n\nDefining a new type of ``Animal`` from within Python is possible but requires a\nhelper class that is defined as follows:\n\n.. code-block:: cpp\n\n    class PyAnimal : public Animal, public py::trampoline_self_life_support {\n    public:\n        /* Inherit the constructors */\n        using Animal::Animal;\n\n        /* Trampoline (need one for each virtual function) */\n        std::string go(int n_times) override {\n            PYBIND11_OVERRIDE_PURE(\n                std::string, /* Return type */\n                Animal,      /* Parent class */\n                go,          /* Name of function in C++ (must match Python name) */\n                n_times      /* Argument(s) */\n            );\n        }\n    };\n\nThe ``py::trampoline_self_life_support`` base class is needed to ensure\nthat a ``std::unique_ptr`` can safely be passed between Python and C++. To\nhelp you steer clear of notorious pitfalls (e.g. inheritance slicing),\npybind11 enforces that trampoline classes inherit from\n``py::trampoline_self_life_support`` if used in in combination with\n``py::smart_holder``.\n\n.. note::\n    For completeness, the base class has no effect if a holder other than\n    ``py::smart_holder`` used, including the default ``std::unique_ptr<T>``.\n    To avoid confusion, pybind11 will fail to compile bindings that combine\n    ``py::trampoline_self_life_support`` with a holder other than\n    ``py::smart_holder``.\n\n    Please think twice, though, before deciding to not use the safer\n    ``py::smart_holder``. The pitfalls associated with avoiding it are very\n    real, and the overhead for using it is very likely in the noise.\n\nThe macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual\nfunctions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have\na default implementation.  There are also two alternate macros\n:c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which\ntake a string-valued name argument between the *Parent class* and *Name of the\nfunction* slots, which defines the name of function in Python. This is required\nwhen the C++ and Python versions of the\nfunction have different names, e.g.  ``operator()`` vs ``__call__``.\n\nThe binding code also needs a few minor adaptations (highlighted):\n\n.. code-block:: cpp\n    :emphasize-lines: 2,3\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Animal, PyAnimal /* <--- trampoline */, py::smart_holder>(m, \"Animal\")\n            .def(py::init<>())\n            .def(\"go\", &Animal::go);\n\n        py::class_<Dog, Animal, py::smart_holder>(m, \"Dog\")\n            .def(py::init<>());\n\n        m.def(\"call_go\", &call_go);\n    }\n\nImportantly, pybind11 is made aware of the trampoline helper class by\nspecifying it as an extra template argument to ``py::class_``. (This can also\nbe combined with other template arguments such as a custom holder type; the\norder of template types does not matter).  Following this, we are able to\ndefine a constructor as usual.\n\nBindings should be made against the actual class, not the trampoline helper class.\n\n.. code-block:: cpp\n    :emphasize-lines: 3\n\n    py::class_<Animal, PyAnimal /* <--- trampoline */, py::smart_holder>(m, \"Animal\");\n        .def(py::init<>())\n        .def(\"go\", &Animal::go); /* <--- DO NOT USE &PyAnimal::go HERE */\n\nNote, however, that the above is sufficient for allowing python classes to\nextend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the\nnecessary steps required to providing proper overriding support for inherited\nclasses.\n\nThe Python session below shows how to override ``Animal::go`` and invoke it via\na virtual method call.\n\n.. code-block:: pycon\n\n    >>> from example import *\n    >>> d = Dog()\n    >>> call_go(d)\n    'woof! woof! woof! '\n    >>> class Cat(Animal):\n    ...     def go(self, n_times):\n    ...         return \"meow! \" * n_times\n    ...\n    >>> c = Cat()\n    >>> call_go(c)\n    'meow! meow! meow! '\n\nIf you are defining a custom constructor in a derived Python class, you *must*\nensure that you explicitly call the bound C++ constructor using ``__init__``,\n*regardless* of whether it is a default constructor or not. Otherwise, the\nmemory for the C++ portion of the instance will be left uninitialized, which\nwill generally leave the C++ instance in an invalid state and cause undefined\nbehavior if the C++ instance is subsequently used.\n\n.. versionchanged:: 2.6\n   The default pybind11 metaclass will throw a ``TypeError`` when it detects\n   that ``__init__`` was not called by a derived class.\n\nHere is an example:\n\n.. code-block:: python\n\n    class Dachshund(Dog):\n        def __init__(self, name):\n            Dog.__init__(self)  # Without this, a TypeError is raised.\n            self.name = name\n\n        def bark(self):\n            return \"yap!\"\n\nNote that a direct ``__init__`` constructor *should be called*, and ``super()``\nshould not be used. For simple cases of linear inheritance, ``super()``\nmay work, but once you begin mixing Python and C++ multiple inheritance,\nthings will fall apart due to differences between Python's MRO and C++'s\nmechanisms.\n\nPlease take a look at the :ref:`macro_notes` before using this feature.\n\n.. note::\n\n    When the overridden type returns a reference or pointer to a type that\n    pybind11 converts from Python (for example, numeric values, std::string,\n    and other built-in value-converting types), there are some limitations to\n    be aware of:\n\n    - because in these cases there is no C++ variable to reference (the value\n      is stored in the referenced Python variable), pybind11 provides one in\n      the PYBIND11_OVERRIDE macros (when needed) with static storage duration.\n      Note that this means that invoking the overridden method on *any*\n      instance will change the referenced value stored in *all* instances of\n      that type.\n\n    - Attempts to modify a non-const reference will not have the desired\n      effect: it will change only the static cache variable, but this change\n      will not propagate to underlying Python instance, and the change will be\n      replaced the next time the override is invoked.\n\n.. warning::\n\n    The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called\n    ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override`\n    used to be called ``get_overload``. This naming was corrected and the older\n    macro and function names may soon be deprecated, in order to reduce\n    confusion with overloaded functions and methods and ``py::overload_cast``\n    (see :ref:`classes`).\n\n.. seealso::\n\n    The file :file:`tests/test_virtual_functions.cpp` contains a complete\n    example that demonstrates how to override virtual functions using pybind11\n    in more detail.\n\n.. _virtual_and_inheritance:\n\nCombining virtual functions and inheritance\n===========================================\n\nWhen combining virtual methods with inheritance, you need to be sure to provide\nan override for each method for which you want to allow overrides from derived\npython classes.  For example, suppose we extend the above ``Animal``/``Dog``\nexample as follows:\n\n.. code-block:: cpp\n\n    class Animal {\n    public:\n        virtual std::string go(int n_times) = 0;\n        virtual std::string name() { return \"unknown\"; }\n    };\n    class Dog : public Animal {\n    public:\n        std::string go(int n_times) override {\n            std::string result;\n            for (int i=0; i<n_times; ++i)\n                result += bark() + \" \";\n            return result;\n        }\n        virtual std::string bark() { return \"woof!\"; }\n    };\n\nthen the trampoline class for ``Animal`` must, as described in the previous\nsection, override ``go()`` and ``name()``, but in order to allow python code to\ninherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that\noverrides both the added ``bark()`` method *and* the ``go()`` and ``name()``\nmethods inherited from ``Animal`` (even though ``Dog`` doesn't directly\noverride the ``name()`` method):\n\n.. code-block:: cpp\n\n    class PyAnimal : public Animal, public py::trampoline_self_life_support {\n    public:\n        using Animal::Animal; // Inherit constructors\n        std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); }\n        std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); }\n    };\n    class PyDog : public Dog, public py::trampoline_self_life_support {\n    public:\n        using Dog::Dog; // Inherit constructors\n        std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); }\n        std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); }\n        std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); }\n    };\n\n.. note::\n\n    Note the trailing commas in the ``PYBIND11_OVERRIDE`` calls to ``name()``\n    and ``bark()``. These are needed to portably implement a trampoline for a\n    function that does not take any arguments. For functions that take\n    a nonzero number of arguments, the trailing comma must be omitted.\n\nA registered class derived from a pybind11-registered class with virtual\nmethods requires a similar trampoline class, *even if* it doesn't explicitly\ndeclare or override any virtual methods itself:\n\n.. code-block:: cpp\n\n    class Husky : public Dog {};\n    class PyHusky : public Husky, public py::trampoline_self_life_support {\n    public:\n        using Husky::Husky; // Inherit constructors\n        std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); }\n        std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); }\n        std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); }\n    };\n\nThere is, however, a technique that can be used to avoid this duplication\n(which can be especially helpful for a base class with several virtual\nmethods).  The technique involves using template trampoline classes, as\nfollows:\n\n.. code-block:: cpp\n\n    template <class AnimalBase = Animal>\n    class PyAnimal : public AnimalBase, public py::trampoline_self_life_support {\n    public:\n        using AnimalBase::AnimalBase; // Inherit constructors\n        std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); }\n        std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); }\n    };\n    template <class DogBase = Dog>\n    class PyDog : public PyAnimal<DogBase>, public py::trampoline_self_life_support {\n    public:\n        using PyAnimal<DogBase>::PyAnimal; // Inherit constructors\n        // Override PyAnimal's pure virtual go() with a non-pure one:\n        std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); }\n        std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); }\n    };\n\nThis technique has the advantage of requiring just one trampoline method to be\ndeclared per virtual method and pure virtual method override.  It does,\nhowever, require the compiler to generate at least as many methods (and\npossibly more, if both pure virtual and overridden pure virtual methods are\nexposed, as above).\n\nThe classes are then registered with pybind11 using:\n\n.. code-block:: cpp\n\n    py::class_<Animal, PyAnimal<>, py::smart_holder> animal(m, \"Animal\");\n    py::class_<Dog, Animal, PyDog<>, py::smart_holder> dog(m, \"Dog\");\n    py::class_<Husky, Dog, PyDog<Husky>, py::smart_holder> husky(m, \"Husky\");\n    // ... add animal, dog, husky definitions\n\nNote that ``Husky`` did not require a dedicated trampoline template class at\nall, since it neither declares any new virtual methods nor provides any pure\nvirtual method implementations.\n\nWith either the repeated-virtuals or templated trampoline methods in place, you\ncan now create a python class that inherits from ``Dog``:\n\n.. code-block:: python\n\n    class ShihTzu(Dog):\n        def bark(self):\n            return \"yip!\"\n\n.. seealso::\n\n    See the file :file:`tests/test_virtual_functions.cpp` for complete examples\n    using both the duplication and templated trampoline approaches.\n\n.. _extended_aliases:\n\nExtended trampoline class functionality\n=======================================\n\n.. _extended_class_functionality_forced_trampoline:\n\nForced trampoline class initialisation\n--------------------------------------\nThe trampoline classes described in the previous sections are, by default, only\ninitialized when needed.  More specifically, they are initialized when a python\nclass actually inherits from a registered type (instead of merely creating an\ninstance of the registered type), or when a registered constructor is only\nvalid for the trampoline class but not the registered class.  This is primarily\nfor performance reasons: when the trampoline class is not needed for anything\nexcept virtual method dispatching, not initializing the trampoline class\nimproves performance by avoiding needing to do a run-time check to see if the\ninheriting python instance has an overridden method.\n\nSometimes, however, it is useful to always initialize a trampoline class as an\nintermediate class that does more than just handle virtual method dispatching.\nFor example, such a class might perform extra class initialization, extra\ndestruction operations, and might define new members and methods to enable a\nmore python-like interface to a class.\n\nIn order to tell pybind11 that it should *always* initialize the trampoline\nclass when creating new instances of a type, the class constructors should be\ndeclared using ``py::init_alias<Args, ...>()`` instead of the usual\n``py::init<Args, ...>()``.  This forces construction via the trampoline class,\nensuring member initialization and (eventual) destruction.\n\n.. seealso::\n\n    See the file :file:`tests/test_virtual_functions.cpp` for complete examples\n    showing both normal and forced trampoline instantiation.\n\nDifferent method signatures\n---------------------------\nThe macro's introduced in :ref:`overriding_virtuals` cover most of the standard\nuse cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy\nto create a direct one-on-one mapping between the arguments and method return\ntype.\n\nAn example would be when the C++ signature contains output arguments using\nreferences (See also :ref:`faq_reference_arguments`). Another way of solving\nthis is to use the method body of the trampoline class to do conversions to the\ninput and return of the Python method.\n\nThe main building block to do so is the :func:`get_override`, this function\nallows retrieving a method implemented in Python from within the trampoline's\nmethods. Consider for example a C++ method which has the signature\n``bool myMethod(int32_t& value)``, where the return indicates whether\nsomething should be done with the ``value``. This can be made convenient on the\nPython side by allowing the Python function to return ``None`` or an ``int``:\n\n.. code-block:: cpp\n\n    bool MyClass::myMethod(int32_t& value)\n    {\n        pybind11::gil_scoped_acquire gil;  // Acquire the GIL while in this scope.\n        // Try to look up the overridden method on the Python side.\n        pybind11::function override = pybind11::get_override(this, \"myMethod\");\n        if (override) {  // method is found\n            auto obj = override(value);  // Call the Python function.\n            if (py::isinstance<py::int_>(obj)) {  // check if it returned a Python integer type\n                value = obj.cast<int32_t>();  // Cast it and assign it to the value.\n                return true;  // Return true; value should be used.\n            } else {\n                return false;  // Python returned none, return false.\n            }\n        }\n        return false;  // Alternatively return MyClass::myMethod(value);\n    }\n\nAvoiding Inheritance Slicing and ``std::weak_ptr`` surprises\n------------------------------------------------------------\n\nWhen working with classes that use virtual functions and are subclassed\nin Python, special care must be taken when converting Python objects to\n``std::shared_ptr<T>``. Depending on whether the class uses a plain\n``std::shared_ptr`` holder or ``py::smart_holder``, the resulting\n``shared_ptr`` may either allow inheritance slicing or lead to potentially\nsurprising behavior when constructing ``std::weak_ptr`` instances.\n\nThis section explains how ``std::shared_ptr`` and ``py::smart_holder`` manage\nobject lifetimes differently, how these differences affect trampoline-derived\nobjects, and what options are available to achieve the situation-specific\ndesired behavior.\n\nWhen using ``std::shared_ptr`` as the holder type, converting a Python object\nto a ``std::shared_ptr<T>`` (e.g., ``obj.cast<std::shared_ptr<T>>()``, or simply\npassing the Python object as an argument to a ``.def()``-ed function) returns\na ``shared_ptr`` that shares ownership with the original ``class_`` holder,\nusually preserving object lifetime. However, for Python classes that derive from\na trampoline, if the Python object is destroyed, only the base C++ object may\nremain alive, leading to inheritance slicing\n(see `#1333 <https://github.com/pybind/pybind11/issues/1333>`_).\n\nIn contrast, with ``py::smart_holder``, converting a Python object to\na ``std::shared_ptr<T>`` returns a new ``shared_ptr`` with an independent\ncontrol block that keeps the derived Python object alive. This avoids\ninheritance slicing but can lead to unintended behavior when creating\n``std::weak_ptr`` instances\n(see `#5623 <https://github.com/pybind/pybind11/issues/5623>`_).\n\nIf it is necessary to obtain a ``std::weak_ptr`` that shares the control block\nwith the ``smart_holder``—at the cost of reintroducing potential inheritance\nslicing—you can use ``py::potentially_slicing_weak_ptr<T>(obj)``.\n\nWhen precise lifetime management of derived Python objects is important,\nusing a Python-side ``weakref`` is the most reliable approach, as it avoids\nboth inheritance slicing and unintended interactions with ``std::weak_ptr``\nsemantics in C++.\n\n.. seealso::\n\n    * :func:`potentially_slicing_weak_ptr` C++ documentation\n    * :file:`tests/test_potentially_slicing_weak_ptr.cpp`\n\n\n.. _custom_constructors:\n\nCustom constructors\n===================\n\nThe syntax for binding constructors was previously introduced, but it only\nworks when a constructor of the appropriate arguments actually exists on the\nC++ side.  To extend this to more general cases, pybind11 makes it possible\nto bind factory functions as constructors. For example, suppose you have a\nclass like this:\n\n.. code-block:: cpp\n\n    class Example {\n    private:\n        Example(int); // private constructor\n    public:\n        // Factory function:\n        static Example create(int a) { return Example(a); }\n    };\n\n    py::class_<Example>(m, \"Example\")\n        .def(py::init(&Example::create));\n\nWhile it is possible to create a straightforward binding of the static\n``create`` method, it may sometimes be preferable to expose it as a constructor\non the Python side. This can be accomplished by calling ``.def(py::init(...))``\nwith the function reference returning the new instance passed as an argument.\nIt is also possible to use this approach to bind a function returning a new\ninstance by raw pointer or by the holder (e.g. ``std::unique_ptr``).\n\nThe following example shows the different approaches:\n\n.. code-block:: cpp\n\n    class Example {\n    private:\n        Example(int); // private constructor\n    public:\n        // Factory function - returned by value:\n        static Example create(int a) { return Example(a); }\n\n        // These constructors are publicly callable:\n        Example(double);\n        Example(int, int);\n        Example(std::string);\n    };\n\n    py::class_<Example>(m, \"Example\")\n        // Bind the factory function as a constructor:\n        .def(py::init(&Example::create))\n        // Bind a lambda function returning a pointer wrapped in a holder:\n        .def(py::init([](std::string arg) {\n            return std::unique_ptr<Example>(new Example(arg));\n        }))\n        // Return a raw pointer:\n        .def(py::init([](int a, int b) { return new Example(a, b); }))\n        // You can mix the above with regular C++ constructor bindings as well:\n        .def(py::init<double>())\n        ;\n\nWhen the constructor is invoked from Python, pybind11 will call the factory\nfunction and store the resulting C++ instance in the Python instance.\n\nWhen combining factory functions constructors with :ref:`virtual function\ntrampolines <overriding_virtuals>` there are two approaches.  The first is to\nadd a constructor to the alias class that takes a base value by\nrvalue-reference.  If such a constructor is available, it will be used to\nconstruct an alias instance from the value returned by the factory function.\nThe second option is to provide two factory functions to ``py::init()``: the\nfirst will be invoked when no alias class is required (i.e. when the class is\nbeing used but not inherited from in Python), and the second will be invoked\nwhen an alias is required.\n\nYou can also specify a single factory function that always returns an alias\ninstance: this will result in behaviour similar to ``py::init_alias<...>()``,\nas described in the :ref:`extended trampoline class documentation\n<extended_aliases>`.\n\nThe following example shows the different factory approaches for a class with\nan alias:\n\n.. code-block:: cpp\n\n    #include <pybind11/factory.h>\n    class Example {\n    public:\n        // ...\n        virtual ~Example() = default;\n    };\n    class PyExample : public Example, public py::trampoline_self_life_support {\n    public:\n        using Example::Example;\n        PyExample(Example &&base) : Example(std::move(base)) {}\n    };\n    py::class_<Example, PyExample, py::smart_holder>(m, \"Example\")\n        // Returns an Example pointer.  If a PyExample is needed, the Example\n        // instance will be moved via the extra constructor in PyExample, above.\n        .def(py::init([]() { return new Example(); }))\n        // Two callbacks:\n        .def(py::init([]() { return new Example(); } /* no alias needed */,\n                      []() { return new PyExample(); } /* alias needed */))\n        // *Always* returns an alias instance (like py::init_alias<>())\n        .def(py::init([]() { return new PyExample(); }))\n        ;\n\nBrace initialization\n--------------------\n\n``pybind11::init<>`` internally uses C++11 brace initialization to call the\nconstructor of the target class. This means that it can be used to bind\n*implicit* constructors as well:\n\n.. code-block:: cpp\n\n    struct Aggregate {\n        int a;\n        std::string b;\n    };\n\n    py::class_<Aggregate>(m, \"Aggregate\")\n        .def(py::init<int, const std::string &>());\n\n.. note::\n\n    Note that brace initialization preferentially invokes constructor overloads\n    taking a ``std::initializer_list``. In the rare event that this causes an\n    issue, you can work around it by using ``py::init(...)`` with a lambda\n    function that constructs the new object as desired.\n\n.. _classes_with_non_public_destructors:\n\nNon-public destructors\n======================\n\nIf a class has a private or protected destructor (as might e.g. be the case in\na singleton pattern), a compile error will occur when creating bindings via\npybind11. The underlying issue is that the ``std::unique_ptr`` holder type that\nis responsible for managing the lifetime of instances will reference the\ndestructor even if no deallocations ever take place. In order to expose classes\nwith private or protected destructors, it is possible to override the holder\ntype via a holder type argument to ``py::class_``. Pybind11 provides a helper\nclass ``py::nodelete`` that disables any destructor invocations. In this case,\nit is crucial that instances are deallocated on the C++ side to avoid memory\nleaks.\n\n.. code-block:: cpp\n\n    /* ... definition ... */\n\n    class MyClass {\n    private:\n        ~MyClass() { }\n    };\n\n    /* ... binding code ... */\n\n    py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, \"MyClass\")\n        .def(py::init<>())\n\n.. _destructors_that_call_python:\n\nDestructors that call Python\n============================\n\nIf a Python function is invoked from a C++ destructor, an exception may be thrown\nof type :class:`error_already_set`. If this error is thrown out of a class destructor,\n``std::terminate()`` will be called, terminating the process. Class destructors\nmust catch all exceptions of type :class:`error_already_set` to discard the Python\nexception using :func:`error_already_set::discard_as_unraisable`.\n\nEvery Python function should be treated as *possibly throwing*. When a Python generator\nstops yielding items, Python will throw a ``StopIteration`` exception, which can pass\nthough C++ destructors if the generator's stack frame holds the last reference to C++\nobjects.\n\nFor more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`.\n\n.. code-block:: cpp\n\n    class MyClass {\n    public:\n        ~MyClass() {\n            try {\n                py::print(\"Even printing is dangerous in a destructor\");\n                py::exec(\"raise ValueError('This is an unraisable exception')\");\n            } catch (py::error_already_set &e) {\n                // error_context should be information about where/why the occurred,\n                // e.g. use __func__ to get the name of the current function\n                e.discard_as_unraisable(__func__);\n            }\n        }\n    };\n\n.. note::\n\n    pybind11 does not support C++ destructors marked ``noexcept(false)``.\n\n.. versionadded:: 2.6\n\n.. _implicit_conversions:\n\nImplicit conversions\n====================\n\nSuppose that instances of two types ``A`` and ``B`` are used in a project, and\nthat an ``A`` can easily be converted into an instance of type ``B`` (examples of this\ncould be a fixed and an arbitrary precision number type).\n\n.. code-block:: cpp\n\n    py::class_<A>(m, \"A\")\n        /// ... members ...\n\n    py::class_<B>(m, \"B\")\n        .def(py::init<A>())\n        /// ... members ...\n\n    m.def(\"func\",\n        [](const B &) { /* .... */ }\n    );\n\nTo invoke the function ``func`` using a variable ``a`` containing an ``A``\ninstance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++\nwill automatically apply an implicit type conversion, which makes it possible\nto directly write ``func(a)``.\n\nIn this situation (i.e. where ``B`` has a constructor that converts from\n``A``), the following statement enables similar implicit conversions on the\nPython side:\n\n.. code-block:: cpp\n\n    py::implicitly_convertible<A, B>();\n\n.. note::\n\n    Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom\n    data type that is exposed to Python via pybind11.\n\n    To prevent runaway recursion, implicit conversions are non-reentrant: an\n    implicit conversion invoked as part of another implicit conversion of the\n    same type (i.e. from ``A`` to ``B``) will fail.\n\n.. _static_properties:\n\nStatic properties\n=================\n\nThe section on :ref:`properties` discussed the creation of instance properties\nthat are implemented in terms of C++ getters and setters.\n\nStatic properties can also be created in a similar way to expose getters and\nsetters of static class attributes. Note that the implicit ``self`` argument\nalso exists in this case and is used to pass the Python ``type`` subclass\ninstance. This parameter will often not be needed by the C++ side, and the\nfollowing example illustrates how to instantiate a lambda getter function\nthat ignores it:\n\n.. code-block:: cpp\n\n    py::class_<Foo>(m, \"Foo\")\n        .def_property_readonly_static(\"foo\", [](py::object /* self */) { return Foo(); });\n\nOperator overloading\n====================\n\nSuppose that we're given the following ``Vector2`` class with a vector addition\nand scalar multiplication operation, all implemented using overloaded operators\nin C++.\n\n.. code-block:: cpp\n\n    class Vector2 {\n    public:\n        Vector2(float x, float y) : x(x), y(y) { }\n\n        Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }\n        Vector2 operator*(float value) const { return Vector2(x * value, y * value); }\n        Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }\n        Vector2& operator*=(float v) { x *= v; y *= v; return *this; }\n\n        friend Vector2 operator*(float f, const Vector2 &v) {\n            return Vector2(f * v.x, f * v.y);\n        }\n\n        std::string toString() const {\n            return \"[\" + std::to_string(x) + \", \" + std::to_string(y) + \"]\";\n        }\n    private:\n        float x, y;\n    };\n\nThe following snippet shows how the above operators can be conveniently exposed\nto Python.\n\n.. code-block:: cpp\n\n    #include <pybind11/operators.h>\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Vector2>(m, \"Vector2\")\n            .def(py::init<float, float>())\n            .def(py::self + py::self)\n            .def(py::self += py::self)\n            .def(py::self *= float())\n            .def(float() * py::self)\n            .def(py::self * float())\n            .def(-py::self)\n            .def(\"__repr__\", &Vector2::toString);\n    }\n\nNote that a line like\n\n.. code-block:: cpp\n\n            .def(py::self * float())\n\nis really just short hand notation for\n\n.. code-block:: cpp\n\n    .def(\"__mul__\", [](const Vector2 &a, float b) {\n        return a * b;\n    }, py::is_operator())\n\nThis can be useful for exposing additional operators that don't exist on the\nC++ side, or to perform other types of customization. The ``py::is_operator``\nflag marker is needed to inform pybind11 that this is an operator, which\nreturns ``NotImplemented`` when invoked with incompatible arguments rather than\nthrowing a type error.\n\n.. note::\n\n    To use the more convenient ``py::self`` notation, the additional\n    header file :file:`pybind11/operators.h` must be included.\n\n.. seealso::\n\n    The file :file:`tests/test_operator_overloading.cpp` contains a\n    complete example that demonstrates how to work with overloaded operators in\n    more detail.\n\n.. _pickling:\n\nPickling support\n================\n\nPython's ``pickle`` module provides a powerful facility to serialize and\nde-serialize a Python object graph into a binary data stream. To pickle and\nunpickle C++ classes using pybind11, a ``py::pickle()`` definition must be\nprovided. Suppose the class in question has the following signature:\n\n.. code-block:: cpp\n\n    class Pickleable {\n    public:\n        Pickleable(const std::string &value) : m_value(value) { }\n        const std::string &value() const { return m_value; }\n\n        void setExtra(int extra) { m_extra = extra; }\n        int extra() const { return m_extra; }\n    private:\n        std::string m_value;\n        int m_extra = 0;\n    };\n\nPickling support in Python is enabled by defining the ``__setstate__`` and\n``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()``\nto bind these two functions:\n\n.. code-block:: cpp\n\n    py::class_<Pickleable>(m, \"Pickleable\")\n        .def(py::init<std::string>())\n        .def(\"value\", &Pickleable::value)\n        .def(\"extra\", &Pickleable::extra)\n        .def(\"setExtra\", &Pickleable::setExtra)\n        .def(py::pickle(\n            [](const Pickleable &p) { // __getstate__\n                /* Return a tuple that fully encodes the state of the object */\n                return py::make_tuple(p.value(), p.extra());\n            },\n            [](py::tuple t) { // __setstate__\n                if (t.size() != 2)\n                    throw std::runtime_error(\"Invalid state!\");\n\n                /* Create a new C++ instance */\n                Pickleable p(t[0].cast<std::string>());\n\n                /* Assign any additional state */\n                p.setExtra(t[1].cast<int>());\n\n                return p;\n            }\n        ));\n\nThe ``__setstate__`` part of the ``py::pickle()`` definition follows the same\nrules as the single-argument version of ``py::init()``. The return type can be\na value, pointer or holder type. See :ref:`custom_constructors` for details.\n\nAn instance can now be pickled as follows:\n\n.. code-block:: python\n\n    import pickle\n\n    p = Pickleable(\"test_value\")\n    p.setExtra(15)\n    data = pickle.dumps(p)\n\n\n.. note::\n    If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are\n    not supported. Newer versions are also fine; for instance, specify ``-1`` to\n    always use the latest available version. Beware: failure to follow these\n    instructions will cause important pybind11 memory allocation routines to be\n    skipped during unpickling, which will likely lead to memory corruption\n    and/or segmentation faults.\n\n.. seealso::\n\n    The file :file:`tests/test_pickling.cpp` contains a complete example\n    that demonstrates how to pickle and unpickle types using pybind11 in more\n    detail.\n\n.. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances\n\nDeepcopy support\n================\n\nPython normally uses references in assignments. Sometimes a real copy is needed\nto prevent changing all copies. The ``copy`` module [#f5]_ provides these\ncapabilities.\n\nA class with pickle support is automatically also (deep)copy\ncompatible. However, performance can be improved by adding custom\n``__copy__`` and ``__deepcopy__`` methods.\n\nFor simple classes (deep)copy can be enabled by using the copy constructor,\nwhich should look as follows:\n\n.. code-block:: cpp\n\n    py::class_<Copyable>(m, \"Copyable\")\n        .def(\"__copy__\",  [](const Copyable &self) {\n            return Copyable(self);\n        })\n        .def(\"__deepcopy__\", [](const Copyable &self, py::dict) {\n            return Copyable(self);\n        }, \"memo\"_a);\n\n.. note::\n\n    Dynamic attributes will not be copied in this example.\n\n.. [#f5] https://docs.python.org/3/library/copy.html\n\nMultiple Inheritance\n====================\n\npybind11 can create bindings for types that derive from multiple base types\n(aka. *multiple inheritance*). To do so, specify all bases in the template\narguments of the ``py::class_`` declaration:\n\n.. code-block:: cpp\n\n    py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, \"MyType\")\n       ...\n\nThe base types can be specified in arbitrary order, and they can even be\ninterspersed with alias types and holder types (discussed earlier in this\ndocument)---pybind11 will automatically find out which is which. The only\nrequirement is that the first template argument is the type to be declared.\n\nIt is also permitted to inherit multiply from exported C++ classes in Python,\nas well as inheriting from multiple Python and/or pybind11-exported classes.\n\nThere is one caveat regarding the implementation of this feature:\n\nWhen only one base type is specified for a C++ type that actually has multiple\nbases, pybind11 will assume that it does not participate in multiple\ninheritance, which can lead to undefined behavior. In such cases, add the tag\n``multiple_inheritance`` to the class constructor:\n\n.. code-block:: cpp\n\n    py::class_<MyType, BaseType2>(m, \"MyType\", py::multiple_inheritance());\n\nThe tag is redundant and does not need to be specified when multiple base types\nare listed.\n\n.. _module_local:\n\nModule-local class bindings\n===========================\n\nWhen creating a binding for a class, pybind11 by default makes that binding\n\"global\" across modules. What this means is that instances whose type is\ndefined with a ``py::class_`` statement in one module can be passed to or\nreturned from a function defined in any other module that is \"ABI compatible\"\nwith the first, i.e., that was built with sufficiently similar versions of\npybind11 and of the C++ compiler and C++ standard library. The internal data\nstructures that pybind11 uses to keep track of its types and instances are\nshared just as they would be if everything were in the same module.\nFor example, this allows the following:\n\n.. code-block:: cpp\n\n    // In the module1.cpp binding code for module1:\n    py::class_<Pet>(m, \"Pet\")\n        .def(py::init<std::string>())\n        .def_readonly(\"name\", &Pet::name);\n\n.. code-block:: cpp\n\n    // In the module2.cpp binding code for module2:\n    m.def(\"create_pet\", [](std::string name) { return new Pet(name); });\n\n.. code-block:: pycon\n\n    >>> from module1 import Pet\n    >>> from module2 import create_pet\n    >>> pet1 = Pet(\"Kitty\")\n    >>> pet2 = create_pet(\"Doggy\")\n    >>> pet2.name()\n    'Doggy'\n\nWhen writing binding code for a library, this is usually desirable: this\nallows, for example, splitting up a complex library into multiple Python\nmodules.\n\nIn some cases, however, this can cause conflicts.  For example, suppose two\nunrelated modules make use of an external C++ library and each provide custom\nbindings for one of that library's classes.  This will result in an error when\na Python program attempts to import both modules (directly or indirectly)\nbecause of conflicting definitions on the external type:\n\n.. code-block:: cpp\n\n    // dogs.cpp\n\n    // Binding for external library class:\n    py::class_<pets::Pet>(m, \"Pet\")\n        .def(\"name\", &pets::Pet::name);\n\n    // Binding for local extension class:\n    py::class_<Dog, pets::Pet>(m, \"Dog\")\n        .def(py::init<std::string>());\n\n.. code-block:: cpp\n\n    // cats.cpp, in a completely separate project from the above dogs.cpp.\n\n    // Binding for external library class:\n    py::class_<pets::Pet>(m, \"Pet\")\n        .def(\"get_name\", &pets::Pet::name);\n\n    // Binding for local extending class:\n    py::class_<Cat, pets::Pet>(m, \"Cat\")\n        .def(py::init<std::string>());\n\n.. code-block:: pycon\n\n    >>> import cats\n    >>> import dogs\n    Traceback (most recent call last):\n      File \"<stdin>\", line 1, in <module>\n    ImportError: generic_type: type \"Pet\" is already registered!\n\nTo get around this, you can tell pybind11 to keep the external class binding\nlocalized to the module by passing the ``py::module_local()`` attribute into\nthe ``py::class_`` constructor:\n\n.. code-block:: cpp\n\n    // Pet binding in dogs.cpp:\n    py::class_<pets::Pet>(m, \"Pet\", py::module_local())\n        .def(\"name\", &pets::Pet::name);\n\n.. code-block:: cpp\n\n    // Pet binding in cats.cpp:\n    py::class_<pets::Pet>(m, \"Pet\", py::module_local())\n        .def(\"get_name\", &pets::Pet::name);\n\nThis makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes,\navoiding the conflict and allowing both modules to be loaded.  C++ code in the\n``dogs`` module that casts or returns a ``Pet`` instance will result in a\n``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result\nin a ``cats.Pet`` Python instance.\n\nThis does come with two caveats, however: First, external modules cannot return\nor cast a ``Pet`` instance to Python (unless they also provide their own local\nbindings).  Second, from the Python point of view they are two distinct classes.\n\nNote that the locality only applies in the C++ -> Python direction.  When\npassing such a ``py::module_local`` type into a C++ function, the module-local\nclasses are still considered.  This means that if the following function is\nadded to any module (including but not limited to the ``cats`` and ``dogs``\nmodules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet``\nargument:\n\n.. code-block:: cpp\n\n    m.def(\"pet_name\", [](const pets::Pet &pet) { return pet.name(); });\n\nFor example, suppose the above function is added to each of ``cats.cpp``,\n``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that\ndoes *not* bind ``Pets`` at all).\n\n.. code-block:: pycon\n\n    >>> import cats, dogs, frogs  # No error because of the added py::module_local()\n    >>> mycat, mydog = cats.Cat(\"Fluffy\"), dogs.Dog(\"Rover\")\n    >>> (cats.pet_name(mycat), dogs.pet_name(mydog))\n    ('Fluffy', 'Rover')\n    >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat))\n    ('Rover', 'Fluffy', 'Fluffy')\n\nIt is possible to use ``py::module_local()`` registrations in one module even\nif another module registers the same type globally: within the module with the\nmodule-local definition, all C++ instances will be cast to the associated bound\nPython type.  In other modules any such values are converted to the global\nPython type created elsewhere.\n\n.. note::\n\n    STL bindings (as provided via the optional :file:`pybind11/stl_bind.h`\n    header) apply ``py::module_local`` by default when the bound type might\n    conflict with other modules; see :ref:`stl_bind` for details.\n\n.. note::\n\n    The localization of the bound types is actually tied to the shared object\n    or binary generated by the compiler/linker.  For typical modules created\n    with ``PYBIND11_MODULE()``, this distinction is not significant.  It is\n    possible, however, when :ref:`embedding` to embed multiple modules in the\n    same binary (see :ref:`embedding_modules`).  In such a case, the\n    localization will apply across all embedded modules within the same binary.\n\n.. seealso::\n\n    The file :file:`tests/test_local_bindings.cpp` contains additional examples\n    that demonstrate how ``py::module_local()`` works.\n\nBinding protected member functions\n==================================\n\nIt's normally not possible to expose ``protected`` member functions to Python:\n\n.. code-block:: cpp\n\n    class A {\n    protected:\n        int foo() const { return 42; }\n    };\n\n    py::class_<A>(m, \"A\")\n        .def(\"foo\", &A::foo); // error: 'foo' is a protected member of 'A'\n\nOn one hand, this is good because non-``public`` members aren't meant to be\naccessed from the outside. But we may want to make use of ``protected``\nfunctions in derived Python classes.\n\nThe following pattern makes this possible:\n\n.. code-block:: cpp\n\n    class A {\n    protected:\n        int foo() const { return 42; }\n    };\n\n    class Publicist : public A { // helper type for exposing protected functions\n    public:\n        using A::foo; // inherited with different access modifier\n    };\n\n    py::class_<A>(m, \"A\") // bind the primary class\n        .def(\"foo\", &Publicist::foo); // expose protected methods via the publicist\n\nThis works because ``&Publicist::foo`` is exactly the same function as\n``&A::foo`` (same signature and address), just with a different access\nmodifier. The only purpose of the ``Publicist`` helper class is to make\nthe function name ``public``.\n\nIf the intent is to expose ``protected`` ``virtual`` functions which can be\noverridden in Python, the publicist pattern can be combined with the previously\ndescribed trampoline:\n\n.. code-block:: cpp\n\n    class A {\n    public:\n        virtual ~A() = default;\n\n    protected:\n        virtual int foo() const { return 42; }\n    };\n\n    class Trampoline : public A, public py::trampoline_self_life_support {\n    public:\n        int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); }\n    };\n\n    class Publicist : public A {\n    public:\n        using A::foo;\n    };\n\n    py::class_<A, Trampoline, py::smart_holder>(m, \"A\") // <-- `Trampoline` here\n        .def(\"foo\", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`!\n\nBinding final classes\n=====================\n\nSome classes may not be appropriate to inherit from. In C++11, classes can\nuse the ``final`` specifier to ensure that a class cannot be inherited from.\nThe ``py::is_final`` attribute can be used to ensure that Python classes\ncannot inherit from a specified type. The underlying C++ type does not need\nto be declared final.\n\n.. code-block:: cpp\n\n    class IsFinal final {};\n\n    py::class_<IsFinal>(m, \"IsFinal\", py::is_final());\n\nWhen you try to inherit from such a class in Python, you will now get this\nerror:\n\n.. code-block:: pycon\n\n    >>> class PyFinalChild(IsFinal):\n    ...     pass\n    ...\n    TypeError: type 'IsFinal' is not an acceptable base type\n\n.. note:: This attribute is currently ignored on PyPy\n\n.. versionadded:: 2.6\n\nBinding classes with template parameters\n========================================\n\npybind11 can also wrap classes that have template parameters. Consider these classes:\n\n.. code-block:: cpp\n\n    struct Cat {};\n    struct Dog {};\n\n    template <typename PetType>\n    struct Cage {\n        Cage(PetType& pet);\n        PetType& get();\n    };\n\nC++ templates may only be instantiated at compile time, so pybind11 can only\nwrap instantiated templated classes. You cannot wrap a non-instantiated template:\n\n.. code-block:: cpp\n\n    // BROKEN (this will not compile)\n    py::class_<Cage>(m, \"Cage\");\n        .def(\"get\", &Cage::get);\n\nYou must explicitly specify each template/type combination that you want to\nwrap separately.\n\n.. code-block:: cpp\n\n    // ok\n    py::class_<Cage<Cat>>(m, \"CatCage\")\n        .def(\"get\", &Cage<Cat>::get);\n\n    // ok\n    py::class_<Cage<Dog>>(m, \"DogCage\")\n        .def(\"get\", &Cage<Dog>::get);\n\nIf your class methods have template parameters you can wrap those as well,\nbut once again each instantiation must be explicitly specified:\n\n.. code-block:: cpp\n\n    typename <typename T>\n    struct MyClass {\n        template <typename V>\n        T fn(V v);\n    };\n\n    py::class_<MyClass<int>>(m, \"MyClassT\")\n        .def(\"fn\", &MyClass<int>::fn<std::string>);\n\nCustom automatic downcasters\n============================\n\nAs explained in :ref:`inheritance`, pybind11 comes with built-in\nunderstanding of the dynamic type of polymorphic objects in C++; that\nis, returning a Pet to Python produces a Python object that knows it's\nwrapping a Dog, if Pet has virtual methods and pybind11 knows about\nDog and this Pet is in fact a Dog. Sometimes, you might want to\nprovide this automatic downcasting behavior when creating bindings for\na class hierarchy that does not use standard C++ polymorphism, such as\nLLVM [#f4]_. As long as there's some way to determine at runtime\nwhether a downcast is safe, you can proceed by specializing the\n``pybind11::polymorphic_type_hook`` template:\n\n.. code-block:: cpp\n\n    enum class PetKind { Cat, Dog, Zebra };\n    struct Pet {   // Not polymorphic: has no virtual methods\n        const PetKind kind;\n        int age = 0;\n      protected:\n        Pet(PetKind _kind) : kind(_kind) {}\n    };\n    struct Dog : Pet {\n        Dog() : Pet(PetKind::Dog) {}\n        std::string sound = \"woof!\";\n        std::string bark() const { return sound; }\n    };\n\n    namespace PYBIND11_NAMESPACE {\n        template<> struct polymorphic_type_hook<Pet> {\n            static const void *get(const Pet *src, const std::type_info*& type) {\n                // note that src may be nullptr\n                if (src && src->kind == PetKind::Dog) {\n                    type = &typeid(Dog);\n                    return static_cast<const Dog*>(src);\n                }\n                return src;\n            }\n        };\n    } // namespace PYBIND11_NAMESPACE\n\nWhen pybind11 wants to convert a C++ pointer of type ``Base*`` to a\nPython object, it calls ``polymorphic_type_hook<Base>::get()`` to\ndetermine if a downcast is possible. The ``get()`` function should use\nwhatever runtime information is available to determine if its ``src``\nparameter is in fact an instance of some class ``Derived`` that\ninherits from ``Base``. If it finds such a ``Derived``, it sets ``type\n= &typeid(Derived)`` and returns a pointer to the ``Derived`` object\nthat contains ``src``. Otherwise, it just returns ``src``, leaving\n``type`` at its default value of nullptr. If you set ``type`` to a\ntype that pybind11 doesn't know about, no downcasting will occur, and\nthe original ``src`` pointer will be used with its static type\n``Base*``.\n\nIt is critical that the returned pointer and ``type`` argument of\n``get()`` agree with each other: if ``type`` is set to something\nnon-null, the returned pointer must point to the start of an object\nwhose type is ``type``. If the hierarchy being exposed uses only\nsingle inheritance, a simple ``return src;`` will achieve this just\nfine, but in the general case, you must cast ``src`` to the\nappropriate derived-class pointer (e.g. using\n``static_cast<Derived>(src)``) before allowing it to be returned as a\n``void*``.\n\n.. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html\n\n.. note::\n\n    pybind11's standard support for downcasting objects whose types\n    have virtual methods is implemented using\n    ``polymorphic_type_hook`` too, using the standard C++ ability to\n    determine the most-derived type of a polymorphic object using\n    ``typeid()`` and to cast a base pointer to that most-derived type\n    (even if you don't know what it is) using ``dynamic_cast<void*>``.\n\n.. seealso::\n\n    The file :file:`tests/test_tagbased_polymorphic.cpp` contains a\n    more complete example, including a demonstration of how to provide\n    automatic downcasting for an entire class hierarchy without\n    writing one get() function for each class.\n\nAccessing the type object\n=========================\n\nYou can get the type object from a C++ class that has already been registered using:\n\n.. code-block:: cpp\n\n    py::type T_py = py::type::of<T>();\n\nYou can directly use ``py::type::of(ob)`` to get the type object from any python\nobject, just like ``type(ob)`` in Python.\n\n.. note::\n\n    Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`.\n\n.. versionadded:: 2.6\n\nCustom type setup\n=================\n\nFor advanced use cases, such as enabling garbage collection support, you may\nwish to directly manipulate the ``PyHeapTypeObject`` corresponding to a\n``py::class_`` definition.\n\nYou can do that using ``py::custom_type_setup``:\n\n.. code-block:: cpp\n\n   struct ContainerOwnsPythonObjects {\n       std::vector<py::object> list;\n\n       void append(const py::object &obj) { list.emplace_back(obj); }\n       py::object at(py::ssize_t index) const {\n           if (index >= size() || index < 0) {\n               throw py::index_error(\"Index out of range\");\n           }\n           return list.at(py::size_t(index));\n       }\n       py::ssize_t size() const { return py::ssize_t_cast(list.size()); }\n       void clear() { list.clear(); }\n   };\n\n   py::class_<ContainerOwnsPythonObjects> cls(\n       m, \"ContainerOwnsPythonObjects\", py::custom_type_setup([](PyHeapTypeObject *heap_type) {\n           auto *type = &heap_type->ht_type;\n           type->tp_flags |= Py_TPFLAGS_HAVE_GC;\n           type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {\n   // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse\n   #if PY_VERSION_HEX >= 0x03090000\n               Py_VISIT(Py_TYPE(self_base));\n   #endif\n               if (py::detail::is_holder_constructed(self_base)) {\n                   auto &self = py::cast<ContainerOwnsPythonObjects &>(py::handle(self_base));\n                   for (auto &item : self.list) {\n                       Py_VISIT(item.ptr());\n                   }\n               }\n               return 0;\n           };\n           type->tp_clear = [](PyObject *self_base) {\n               if (py::detail::is_holder_constructed(self_base)) {\n                   auto &self = py::cast<ContainerOwnsPythonObjects &>(py::handle(self_base));\n                   for (auto &item : self.list) {\n                       Py_CLEAR(item.ptr());\n                   }\n                   self.list.clear();\n               }\n               return 0;\n           };\n       }));\n   cls.def(py::init<>());\n   cls.def(\"append\", &ContainerOwnsPythonObjects::append);\n   cls.def(\"at\", &ContainerOwnsPythonObjects::at);\n   cls.def(\"size\", &ContainerOwnsPythonObjects::size);\n   cls.def(\"clear\", &ContainerOwnsPythonObjects::clear);\n\n.. versionadded:: 2.8\n"
  },
  {
    "path": "docs/advanced/deadlock.md",
    "content": "# Double locking, deadlocking, GIL\n\n[TOC]\n\n## Introduction\n\n### Overview\n\nIn concurrent programming with locks, *deadlocks* can arise when more than one\nmutex is locked at the same time, and careful attention has to be paid to lock\nordering to avoid this. Here we will look at a common situation that occurs in\nnative extensions for CPython written in C++.\n\n### Deadlocks\n\nA deadlock can occur when more than one thread attempts to lock more than one\nmutex, and two of the threads lock two of the mutexes in different orders. For\nexample, consider mutexes `mu1` and `mu2`, and threads T1 and T2, executing:\n\n|    | T1                  | T2                 |\n|--- | ------------------- | -------------------|\n|1   | `mu1.lock()`{.good} | `mu2.lock()`{.good}|\n|2   | `mu2.lock()`{.bad}  | `mu1.lock()`{.bad} |\n|3   | `/* work */`        | `/* work */`       |\n|4   | `mu2.unlock()`      | `mu1.unlock()`     |\n|5   | `mu1.unlock()`      | `mu2.unlock()`     |\n\nNow if T1 manages to lock `mu1` and T2 manages to lock `mu2` (as indicated in\ngreen), then both threads will block while trying to lock the respective other\nmutex (as indicated in red), but they are also unable to release the mutex that\nthey have locked (step 5).\n\n**The problem** is that it is possible for one thread to attempt to lock `mu1`\nand then `mu2`, and for another thread to attempt to lock `mu2` and then `mu1`.\nNote that it does not matter if either mutex is unlocked at any intermediate\npoint; what matters is only the order of any attempt to *lock* the mutexes. For\nexample, the following, more complex series of operations is just as prone to\ndeadlock:\n\n|    | T1                  | T2                 |\n|--- | ------------------- | -------------------|\n|1   | `mu1.lock()`{.good} | `mu1.lock()`{.good}|\n|2   | waiting for T2      | `mu2.lock()`{.good}|\n|3   | waiting for T2      | `/* work */`       |\n|3   | waiting for T2      | `mu1.unlock()`     |\n|3   | `mu2.lock()`{.bad}  | `/* work */`       |\n|3   | `/* work */`        | `mu1.lock()`{.bad} |\n|3   | `/* work */`        | `/* work */`       |\n|4   | `mu2.unlock()`      | `mu1.unlock()`     |\n|5   | `mu1.unlock()`      | `mu2.unlock()`     |\n\nWhen the mutexes involved in a locking sequence are known at compile-time, then\navoiding deadlocks is &ldquo;merely&rdquo; a matter of arranging the lock\noperations carefully so as to only occur in one single, fixed order. However, it\nis also possible for mutexes to only be determined at runtime. A typical example\nof this is a database where each row has its own mutex. An operation that\nmodifies two rows in a single transaction (e.g. &ldquo;transferring an amount\nfrom one account to another&rdquo;) must lock two row mutexes, but the locking\norder cannot be established at compile time. In this case, a dynamic\n&ldquo;deadlock avoidance algorithm&rdquo; is needed. (In C++, `std::lock`\nprovides such an algorithm. An algorithm might use a non-blocking `try_lock`\noperation on a mutex, which can either succeed or fail to lock the mutex, but\nreturns without blocking.)\n\nConceptually, one could also consider it a deadlock if _the same_ thread\nattempts to lock a mutex that it has already locked (e.g. when some locked\noperation accidentally recurses into itself): `mu.lock();`{.good}\n`mu.lock();`{.bad} However, this is a slightly separate issue: Typical mutexes\nare either of _recursive_ or _non-recursive_ kind. A recursive mutex allows\nrepeated locking and requires balanced unlocking. A non-recursive mutex can be\nimplemented more efficiently, and/but for efficiency reasons does not actually\nguarantee a deadlock on second lock. Instead, the API simply forbids such use,\nmaking it a precondition that the thread not already hold the mutex, with\nundefined behaviour on violation.\n\n### &ldquo;Once&rdquo; initialization\n\nA common programming problem is to have an operation happen precisely once, even\nif requested concurrently. While it is clear that we need to track in some\nshared state somewhere whether the operation has already happened, it is worth\nnoting that this state only ever transitions, once, from `false` to `true`. This\nis considerably simpler than a general shared state that can change values\narbitrarily. Next, we also need a mechanism for all but one thread to block\nuntil the initialization has completed, which we can provide with a mutex. The\nsimplest solution just always locks the mutex:\n\n```c++\n// The \"once\" mechanism:\nconstinit absl::Mutex mu(absl::kConstInit);\nconstinit bool init_done = false;\n\n// The operation of interest:\nvoid f();\n\nvoid InitOnceNaive() {\n  absl::MutexLock lock(&mu);\n  if (!init_done) {\n    f();\n    init_done = true;\n  }\n}\n```\n\nThis works, but the efficiency-minded reader will observe that once the\noperation has completed, all future lock contention on the mutex is\nunnecessary. This leads to the (in)famous &ldquo;double-locking&rdquo;\nalgorithm, which was historically hard to write correctly. The idea is to check\nthe boolean *before* locking the mutex, and avoid locking if the operation has\nalready completed. However, accessing shared state concurrently when at least\none access is a write is prone to causing a data race and needs to be done\naccording to an appropriate concurrent programming model. In C++ we use atomic\nvariables:\n\n```c++\n// The \"once\" mechanism:\nconstinit absl::Mutex mu(absl::kConstInit);\nconstinit std::atomic<bool> init_done = false;\n\n// The operation of interest:\nvoid f();\n\nvoid InitOnceWithFastPath() {\n  if (!init_done.load(std::memory_order_acquire)) {\n    absl::MutexLock lock(&mu);\n    if (!init_done.load(std::memory_order_relaxed)) {\n      f();\n      init_done.store(true, std::memory_order_release);\n    }\n  }\n}\n```\n\nChecking the flag now happens without holding the mutex lock, and if the\noperation has already completed, we return immediately. After locking the mutex,\nwe need to check the flag again, since multiple threads can reach this point.\n\n*Atomic details.* Since the atomic flag variable is accessed concurrently, we\nhave to think about the memory order of the accesses. There are two separate\ncases: The first, outer check outside the mutex lock, and the second, inner\ncheck under the lock. The outer check and the flag update form an\nacquire/release pair: *if* the load sees the value `true` (which must have been\nwritten by the store operation), then it also sees everything that happened\nbefore the store, namely the operation `f()`. By contrast, the inner check can\nuse relaxed memory ordering, since in that case the mutex operations provide the\nnecessary ordering: if the inner load sees the value `true`, it happened after\nthe `lock()`, which happened after the `unlock()`, which happened after the\nstore.\n\nThe C++ standard library, and Abseil, provide a ready-made solution of this\nalgorithm called `std::call_once`/`absl::call_once`. (The interface is the same,\nbut the Abseil implementation is possibly better.)\n\n```c++\n// The \"once\" mechanism:\nconstinit absl::once_flag init_flag;\n\n// The operation of interest:\nvoid f();\n\nvoid InitOnceWithCallOnce() {\n  absl::call_once(once_flag, f);\n}\n```\n\nEven though conceptually this is performing the same algorithm, this\nimplementation has some considerable advantages: The `once_flag` type is a small\nand trivial, integer-like type and is trivially destructible. Not only does it\ntake up less space than a mutex, it also generates less code since it does not\nhave to run a destructor, which would need to be added to the program's global\ndestructor list.\n\nThe final clou comes with the C++ semantics of a `static` variable declared at\nblock scope: According to [[stmt.dcl]](https://eel.is/c++draft/stmt.dcl#3):\n\n> Dynamic initialization of a block variable with static storage duration or\n> thread storage duration is performed the first time control passes through its\n> declaration; such a variable is considered initialized upon the completion of\n> its initialization. [...] If control enters the declaration concurrently while\n> the variable is being initialized, the concurrent execution shall wait for\n> completion of the initialization.\n\nThis is saying that the initialization of a local, `static` variable precisely\nhas the &ldquo;once&rdquo; semantics that we have been discussing. We can\ntherefore write the above example as follows:\n\n```c++\n// The operation of interest:\nvoid f();\n\nvoid InitOnceWithStatic() {\n  static int unused = (f(), 0);\n}\n```\n\nThis approach is by far the simplest and easiest, but the big difference is that\nthe mutex (or mutex-like object) in this implementation is no longer visible or\nin the user&rsquo;s control. This is perfectly fine if the initializer is\nsimple, but if the initializer itself attempts to lock any other mutex\n(including by initializing another static variable!), then we have no control\nover the lock ordering!\n\nFinally, you may have noticed the `constinit`s around the earlier code. Both\n`constinit` and `constexpr` specifiers on a declaration mean that the variable\nis *constant-initialized*, which means that no initialization is performed at\nruntime (the initial value is already known at compile time). This in turn means\nthat a static variable guard mutex may not be needed, and static initialization\nnever blocks. The difference between the two is that a `constexpr`-specified\nvariable is also `const`, and a variable cannot be `constexpr` if it has a\nnon-trivial destructor. Such a destructor also means that the guard mutex is\nneeded after all, since the destructor must be registered to run at exit,\nconditionally on initialization having happened.\n\n## Python, CPython, GIL\n\nWith CPython, a Python program can call into native code. To this end, the\nnative code registers callback functions with the Python runtime via the CPython\nAPI. In order to ensure that the internal state of the Python runtime remains\nconsistent, there is a single, shared mutex called the &ldquo;global interpreter\nlock&rdquo;, or GIL for short. Upon entry of one of the user-provided callback\nfunctions, the GIL is locked (or &ldquo;held&rdquo;), so that no other mutations\nof the Python runtime state can occur until the native callback returns.\n\nMany native extensions do not interact with the Python runtime for at least some\npart of them, and so it is common for native extensions to _release_ the GIL, do\nsome work, and then reacquire the GIL before returning. Similarly, when code is\ngenerally not holding the GIL but needs to interact with the runtime briefly, it\nwill first reacquire the GIL. The GIL is reentrant, and constructions to acquire\nand subsequently release the GIL are common, and often don't worry about whether\nthe GIL is already held.\n\nIf the native code is written in C++ and contains local, `static` variables,\nthen we are now dealing with at least _two_ mutexes: the static variable guard\nmutex, and the GIL from CPython.\n\nA common problem in such code is an operation with &ldquo;only once&rdquo;\nsemantics that also ends up requiring the GIL to be held at some point. As per\nthe above description of &ldquo;once&rdquo;-style techniques, one might find a\nstatic variable:\n\n```c++\n// CPython callback, assumes that the GIL is held on entry.\nPyObject* InvokeWidget(PyObject* self) {\n  static PyObject* impl = CreateWidget();\n  return PyObject_CallOneArg(impl, self);\n}\n```\n\nThis seems reasonable, but bear in mind that there are two mutexes (the \"guard\nmutex\" and \"the GIL\"), and we must think about the lock order. Otherwise, if the\ncallback is called from multiple threads, a deadlock may ensue.\n\nLet us consider what we can see here: On entry, the GIL is already locked, and\nwe are locking the guard mutex. This is one lock order. Inside the initializer\n`CreateWidget`, with both mutexes already locked, the function can freely access\nthe Python runtime.\n\nHowever, it is entirely possible that `CreateWidget` will want to release the\nGIL at one point and reacquire it later:\n\n```c++\n// Assumes that the GIL is held on entry.\n// Ensures that the GIL is held on exit.\nPyObject* CreateWidget() {\n  // ...\n  Py_BEGIN_ALLOW_THREADS  // releases GIL\n  // expensive work, not accessing the Python runtime\n  Py_END_ALLOW_THREADS    // acquires GIL, #!\n  // ...\n  return result;\n}\n```\n\nNow we have a second lock order: the guard mutex is locked, and then the GIL is\nlocked (at `#!`). To see how this deadlocks, consider threads T1 and T2 both\nhaving the runtime attempt to call `InvokeWidget`. T1 locks the GIL and\nproceeds, locking the guard mutex and calling `CreateWidget`; T2 is blocked\nwaiting for the GIL. Then T1 releases the GIL to do &ldquo;expensive\nwork&rdquo;, and T2 awakes and locks the GIL. Now T2 is blocked trying to\nacquire the guard mutex, but T1 is blocked reacquiring the GIL (at `#!`).\n\nIn other words: if we want to support &ldquo;once-called&rdquo; functions that\ncan arbitrarily release and reacquire the GIL, as is very common, then the only\nlock order that we can ensure is: guard mutex first, GIL second.\n\nTo implement this, we must rewrite our code. Naively, we could always release\nthe GIL before a `static` variable with blocking initializer:\n\n```c++\n// CPython callback, assumes that the GIL is held on entry.\nPyObject* InvokeWidget(PyObject* self) {\n  Py_BEGIN_ALLOW_THREADS  // releases GIL\n  static PyObject* impl = CreateWidget();\n  Py_END_ALLOW_THREADS    // acquires GIL\n\n  return PyObject_CallOneArg(impl, self);\n}\n```\n\nBut similar to the `InitOnceNaive` example above, this code cycles the GIL\n(possibly descheduling the thread) even when the static variable has already\nbeen initialized. If we want to avoid this, we need to abandon the use of a\nstatic variable, since we do not control the guard mutex well enough. Instead,\nwe use an operation whose mutex locking is under our control, such as\n`call_once`. For example:\n\n```c++\n// CPython callback, assumes that the GIL is held on entry.\nPyObject* InvokeWidget(PyObject* self) {\n  static constinit PyObject* impl = nullptr;\n  static constinit std::atomic<bool> init_done = false;\n  static constinit absl::once_flag init_flag;\n\n  if (!init_done.load(std::memory_order_acquire)) {\n    Py_BEGIN_ALLOW_THREADS                       // releases GIL\n    absl::call_once(init_flag, [&]() {\n      PyGILState_STATE s = PyGILState_Ensure();  // acquires GIL\n      impl = CreateWidget();\n      PyGILState_Release(s);                     // releases GIL\n      init_done.store(true, std::memory_order_release);\n    });\n    Py_END_ALLOW_THREADS                         // acquires GIL\n  }\n\n  return PyObject_CallOneArg(impl, self);\n}\n```\n\nThe lock order is now always guard mutex first, GIL second. Unfortunately we\nhave to duplicate the &ldquo;double-checked done flag&rdquo;, effectively\nleading to triple checking, because the flag state inside the `absl::once_flag`\nis not accessible to the user. In other words, we cannot ask `init_flag` whether\nit has been used yet.\n\nHowever, we can perform one last, minor optimisation: since we assume that the\nGIL is held on entry, and again when the initializing operation returns, the GIL\nactually serializes access to our done flag variable, which therefore does not\nneed to be atomic. (The difference to the previous, atomic code may be small,\ndepending on the architecture. For example, on x86-64, acquire/release on a bool\nis nearly free ([demo](https://godbolt.org/z/P9vYWf4fE)).)\n\n```c++\n// CPython callback, assumes that the GIL is held on entry, and indeed anywhere\n// directly in this function (i.e. the GIL can be released inside CreateWidget,\n// but must be reaqcuired when that call returns).\nPyObject* InvokeWidget(PyObject* self) {\n  static constinit PyObject* impl = nullptr;\n  static constinit bool init_done = false;       // guarded by GIL\n  static constinit absl::once_flag init_flag;\n\n  if (!init_done) {\n    Py_BEGIN_ALLOW_THREADS                       // releases GIL\n                                                 // (multiple threads may enter here)\n    absl::call_once(init_flag, [&]() {\n                                                 // (only one thread enters here)\n      PyGILState_STATE s = PyGILState_Ensure();  // acquires GIL\n      impl = CreateWidget();\n      init_done = true;                          // (GIL is held)\n      PyGILState_Release(s);                     // releases GIL\n    });\n\n    Py_END_ALLOW_THREADS                         // acquires GIL\n  }\n\n  return PyObject_CallOneArg(impl, self);\n}\n```\n\n## Debugging tips\n\n*   Build with symbols.\n*   <kbd>Ctrl</kbd>-<kbd>C</kbd> sends `SIGINT`, <kbd>Ctrl</kbd>-<kbd>\\\\</kbd>\n    sends `SIGQUIT`. Both have their uses.\n*   Useful `gdb` commands:\n    *   `py-bt` prints a Python backtrace if you are in a Python frame.\n    *   `thread apply all bt 10` prints the top-10 frames for each thread. A\n        full backtrace can be prohibitively expensive, and the top few frames\n        are often good enough.\n    *   `p PyGILState_Check()` shows whether a thread is holding the GIL. For\n        all threads, run `thread apply all p PyGILState_Check()` to find out\n        which thread is holding the GIL.\n    *   The `static` variable guard mutex is accessed with functions like\n        `cxa_guard_acquire` (though this depends on ABI details and can vary).\n        The guard mutex itself contains information about which thread is\n        currently holding it.\n\n## Links\n\n*   Article on\n    [double-checked locking](https://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/)\n*   [The Deadlock Empire](https://deadlockempire.github.io/), hands-on exercises\n    to construct deadlocks\n"
  },
  {
    "path": "docs/advanced/deprecated.rst",
    "content": ".. _deprecated:\n\nDeprecated\n##########\n\nSupport for Python 3.8 is deprecated and will be removed in 3.1.\n\nSupport for C++11 is deprecated and will be removed in a future version. Please\nuse at least C++14.\n\nSupport for FindPythonLibs (not available in CMake 3.26+ mode) is deprecated\nand will be removed in a future version. The default mode is also going to\nchange to ``\"new\"`` from ``\"compat\"`` in the future.\n\nThe following features were deprecated before pybind11 3.0, and may be removed\nin minor releases of pybind11 3.x.\n\n.. list-table:: Deprecated Features\n   :header-rows: 1\n   :widths: 30 15 10\n\n   * - Feature\n     - Deprecated Version\n     - Year\n   * - ``py::metaclass()``\n     - 2.1\n     - 2017\n   * - ``PYBIND11_PLUGIN``\n     - 2.2\n     - 2017\n   * - ``py::set_error()`` replacing ``operator()``\n     - 2.12\n     - 2024\n   * - ``get_type_overload``\n     - 2.6\n     - 2020\n   * - ``call()``\n     - 2.0\n     - 2016\n   * - ``.str()``\n     - ?\n     -\n   * - ``.get_type()``\n     - 2.6\n     -\n   * - ``==`` and ``!=``\n     - 2.2\n     - 2017\n   * - ``.check()``\n     - ?\n     -\n   * - ``object(handle, bool)``\n     - ?\n     -\n   * - ``error_already_set.clear()``\n     - 2.2\n     - 2017\n   * - ``obj.attr(…)`` as ``bool``\n     - ?\n     -\n   * - ``.contains``\n     - ? (maybe 2.4)\n     -\n   * - ``py::capsule`` two-argument with destructor\n     - ?\n     -\n\n\n\n.. _deprecated_enum:\n\n``py::enum_``\n=============\n\nThis is the original documentation for ``py::enum_``, which is deprecated\nbecause it is not `PEP 435 compatible <https://peps.python.org/pep-0435/>`_\n(see also `#2332 <https://github.com/pybind/pybind11/issues/2332>`_).\nPlease prefer ``py::native_enum`` (added with pybind11v3) when writing\nnew bindings. See :ref:`native_enum` for more information.\n\nLet's suppose that we have an example class that contains internal types\nlike enumerations, e.g.:\n\n.. code-block:: cpp\n\n    struct Pet {\n        enum Kind {\n            Dog = 0,\n            Cat\n        };\n\n        struct Attributes {\n            float age = 0;\n        };\n\n        Pet(const std::string &name, Kind type) : name(name), type(type) { }\n\n        std::string name;\n        Kind type;\n        Attributes attr;\n    };\n\nThe binding code for this example looks as follows:\n\n.. code-block:: cpp\n\n    py::class_<Pet> pet(m, \"Pet\");\n\n    pet.def(py::init<const std::string &, Pet::Kind>())\n        .def_readwrite(\"name\", &Pet::name)\n        .def_readwrite(\"type\", &Pet::type)\n        .def_readwrite(\"attr\", &Pet::attr);\n\n    py::enum_<Pet::Kind>(pet, \"Kind\")\n        .value(\"Dog\", Pet::Kind::Dog)\n        .value(\"Cat\", Pet::Kind::Cat)\n        .export_values();\n\n    py::class_<Pet::Attributes>(pet, \"Attributes\")\n        .def(py::init<>())\n        .def_readwrite(\"age\", &Pet::Attributes::age);\n\n\nTo ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the\n``pet`` ``py::class_`` instance must be supplied to the :class:`enum_` and ``py::class_``\nconstructor. The :func:`enum_::export_values` function exports the enum entries\ninto the parent scope, which should be skipped for newer C++11-style strongly\ntyped enums.\n\n.. code-block:: pycon\n\n    >>> p = Pet(\"Lucy\", Pet.Cat)\n    >>> p.type\n    Kind.Cat\n    >>> int(p.type)\n    1L\n\nThe entries defined by the enumeration type are exposed in the ``__members__`` property:\n\n.. code-block:: pycon\n\n    >>> Pet.Kind.__members__\n    {'Dog': Kind.Dog, 'Cat': Kind.Cat}\n\nThe ``name`` property returns the name of the enum value as a unicode string.\n\n.. note::\n\n    It is also possible to use ``str(enum)``, however these accomplish different\n    goals. The following shows how these two approaches differ.\n\n    .. code-block:: pycon\n\n        >>> p = Pet(\"Lucy\", Pet.Cat)\n        >>> pet_type = p.type\n        >>> pet_type\n        Pet.Cat\n        >>> str(pet_type)\n        'Pet.Cat'\n        >>> pet_type.name\n        'Cat'\n\n.. note::\n\n    When the special tag ``py::arithmetic()`` is specified to the ``enum_``\n    constructor, pybind11 creates an enumeration that also supports rudimentary\n    arithmetic and bit-level operations like comparisons, and, or, xor, negation,\n    etc.\n\n    .. code-block:: cpp\n\n        py::enum_<Pet::Kind>(pet, \"Kind\", py::arithmetic())\n           ...\n\n    By default, these are omitted to conserve space.\n\n.. warning::\n\n    Contrary to Python customs, enum values from the wrappers should not be compared using ``is``, but with ``==`` (see `#1177 <https://github.com/pybind/pybind11/issues/1177>`_ for background).\n"
  },
  {
    "path": "docs/advanced/embedding.rst",
    "content": ".. _embedding:\n\nEmbedding the interpreter\n#########################\n\nWhile pybind11 is mainly focused on extending Python using C++, it's also\npossible to do the reverse: embed the Python interpreter into a C++ program.\nAll of the other documentation pages still apply here, so refer to them for\ngeneral pybind11 usage. This section will cover a few extra things required\nfor embedding.\n\nGetting started\n===============\n\nA basic executable with an embedded interpreter can be created with just a few\nlines of CMake and the ``pybind11::embed`` target, as shown below. For more\ninformation, see :doc:`/compiling`.\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example)\n\n    find_package(pybind11 REQUIRED)  # or `add_subdirectory(pybind11)`\n\n    add_executable(example main.cpp)\n    target_link_libraries(example PRIVATE pybind11::embed)\n\nThe essential structure of the ``main.cpp`` file looks like this:\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h> // everything needed for embedding\n    namespace py = pybind11;\n\n    int main() {\n        py::scoped_interpreter guard{}; // start the interpreter and keep it alive\n\n        py::print(\"Hello, World!\"); // use the Python API\n    }\n\nThe interpreter must be initialized before using any Python API, which includes\nall the functions and classes in pybind11. The RAII guard class ``scoped_interpreter``\ntakes care of the interpreter lifetime. After the guard is destroyed, the interpreter\nshuts down and clears its memory. No Python functions can be called after this.\n\nExecuting Python code\n=====================\n\nThere are a few different ways to run Python code. One option is to use ``eval``,\n``exec`` or ``eval_file``, as explained in :ref:`eval`. Here is a quick example in\nthe context of an executable with an embedded interpreter:\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h>\n    namespace py = pybind11;\n\n    int main() {\n        py::scoped_interpreter guard{};\n\n        py::exec(R\"(\n            kwargs = dict(name=\"World\", number=42)\n            message = \"Hello, {name}! The answer is {number}\".format(**kwargs)\n            print(message)\n        )\");\n    }\n\nAlternatively, similar results can be achieved using pybind11's API (see\n:doc:`/advanced/pycpp/index` for more details).\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h>\n    namespace py = pybind11;\n    using namespace py::literals;\n\n    int main() {\n        py::scoped_interpreter guard{};\n\n        auto kwargs = py::dict(\"name\"_a=\"World\", \"number\"_a=42);\n        auto message = \"Hello, {name}! The answer is {number}\"_s.format(**kwargs);\n        py::print(message);\n    }\n\nThe two approaches can also be combined:\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h>\n    #include <iostream>\n\n    namespace py = pybind11;\n    using namespace py::literals;\n\n    int main() {\n        py::scoped_interpreter guard{};\n\n        auto locals = py::dict(\"name\"_a=\"World\", \"number\"_a=42);\n        py::exec(R\"(\n            message = \"Hello, {name}! The answer is {number}\".format(**locals())\n        )\", py::globals(), locals);\n\n        auto message = locals[\"message\"].cast<std::string>();\n        std::cout << message;\n    }\n\nImporting modules\n=================\n\nPython modules can be imported using ``module_::import()``:\n\n.. code-block:: cpp\n\n    py::module_ sys = py::module_::import(\"sys\");\n    py::print(sys.attr(\"path\"));\n\nFor convenience, the current working directory is included in ``sys.path`` when\nembedding the interpreter. This makes it easy to import local Python files:\n\n.. code-block:: python\n\n    \"\"\"calc.py located in the working directory\"\"\"\n\n\n    def add(i, j):\n        return i + j\n\n\n.. code-block:: cpp\n\n    py::module_ calc = py::module_::import(\"calc\");\n    py::object result = calc.attr(\"add\")(1, 2);\n    int n = result.cast<int>();\n    assert(n == 3);\n\nModules can be reloaded using ``module_::reload()`` if the source is modified e.g.\nby an external process. This can be useful in scenarios where the application\nimports a user defined data processing script which needs to be updated after\nchanges by the user. Note that this function does not reload modules recursively.\n\n.. _embedding_modules:\n\nAdding embedded modules\n=======================\n\nEmbedded binary modules can be added using the ``PYBIND11_EMBEDDED_MODULE`` macro.\nNote that the definition must be placed at global scope. They can be imported\nlike any other module.\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h>\n    namespace py = pybind11;\n\n    PYBIND11_EMBEDDED_MODULE(fast_calc, m) {\n        // `m` is a `py::module_` which is used to bind functions and classes\n        m.def(\"add\", [](int i, int j) {\n            return i + j;\n        });\n    }\n\n    int main() {\n        py::scoped_interpreter guard{};\n\n        auto fast_calc = py::module_::import(\"fast_calc\");\n        auto result = fast_calc.attr(\"add\")(1, 2).cast<int>();\n        assert(result == 3);\n    }\n\nUnlike extension modules where only a single binary module can be created, on\nthe embedded side an unlimited number of modules can be added using multiple\n``PYBIND11_EMBEDDED_MODULE`` definitions (as long as they have unique names).\n\nThese modules are added to Python's list of builtins, so they can also be\nimported in pure Python files loaded by the interpreter. Everything interacts\nnaturally:\n\n.. code-block:: python\n\n    \"\"\"py_module.py located in the working directory\"\"\"\n    import cpp_module\n\n    a = cpp_module.a\n    b = a + 1\n\n\n.. code-block:: cpp\n\n    #include <pybind11/embed.h>\n    namespace py = pybind11;\n\n    PYBIND11_EMBEDDED_MODULE(cpp_module, m) {\n        m.attr(\"a\") = 1;\n    }\n\n    int main() {\n        py::scoped_interpreter guard{};\n\n        auto py_module = py::module_::import(\"py_module\");\n\n        auto locals = py::dict(\"fmt\"_a=\"{} + {} = {}\", **py_module.attr(\"__dict__\"));\n        assert(locals[\"a\"].cast<int>() == 1);\n        assert(locals[\"b\"].cast<int>() == 2);\n\n        py::exec(R\"(\n            c = a + b\n            message = fmt.format(a, b, c)\n        )\", py::globals(), locals);\n\n        assert(locals[\"c\"].cast<int>() == 3);\n        assert(locals[\"message\"].cast<std::string>() == \"1 + 2 = 3\");\n    }\n\n``PYBIND11_EMBEDDED_MODULE`` also accepts\n:func:`py::mod_gil_not_used()`,\n:func:`py::multiple_interpreters::per_interpreter_gil()`, and\n:func:`py::multiple_interpreters::shared_gil()` tags just like ``PYBIND11_MODULE``.\nSee :ref:`misc_subinterp` and :ref:`misc_free_threading` for more information.\n\nInterpreter lifetime\n====================\n\nThe Python interpreter shuts down when ``scoped_interpreter`` is destroyed. After\nthis, creating a new instance will restart the interpreter. Alternatively, the\n``initialize_interpreter`` / ``finalize_interpreter`` pair of functions can be used\nto directly set the state at any time.\n\nModules created with pybind11 can be safely re-initialized after the interpreter\nhas been restarted. However, this may not apply to third-party extension modules.\nThe issue is that Python itself cannot completely unload extension modules and\nthere are several caveats with regard to interpreter restarting. In short, not\nall memory may be freed, either due to Python reference cycles or user-created\nglobal data. All the details can be found in the CPython documentation.\n\n.. warning::\n\n    Creating two concurrent ``scoped_interpreter`` guards is a fatal error. So is\n    calling ``initialize_interpreter`` for a second time after the interpreter\n    has already been initialized. Use :class:`scoped_subinterpreter` to create\n    a sub-interpreter.  See :ref:`subinterp` for important details on sub-interpreters.\n\n    Do not use the raw CPython API functions ``Py_Initialize`` and\n    ``Py_Finalize`` as these do not properly handle the lifetime of\n    pybind11's internal data.\n\n\n.. _subinterp:\n\nEmbedding Sub-interpreters\n==========================\n\nA sub-interpreter is a separate interpreter instance which provides a\nseparate, isolated interpreter environment within the same process as the main\ninterpreter.  Sub-interpreters are created and managed with a separate API from\nthe main interpreter. Beginning in Python 3.12, sub-interpreters each have\ntheir own Global Interpreter Lock (GIL), which means that running a\nsub-interpreter in a separate thread from the main interpreter can achieve true\nconcurrency.\n\npybind11's sub-interpreter API can be found in ``pybind11/subinterpreter.h``.\n\npybind11 :class:`subinterpreter` instances can be safely moved and shared between\nthreads as needed. However, managing multiple threads and the lifetimes of multiple\ninterpreters and their GILs can be challenging.\nProceed with caution (and lots of testing)!\n\nThe main interpreter must be initialized before creating a sub-interpreter, and\nthe main interpreter must outlive all sub-interpreters. Sub-interpreters are\nmanaged through a different API than the main interpreter.\n\nThe :class:`subinterpreter` class manages the lifetime of sub-interpreters.\nInstances are movable, but not copyable. Default constructing this class does\n*not* create a sub-interpreter (it creates an empty holder).  To create a\nsub-interpreter, call :func:`subinterpreter::create()`.\n\n.. warning::\n\n    Sub-interpreter creation acquires (and subsequently releases) the main\n    interpreter GIL. If another thread holds the main GIL, the function will\n    block until the main GIL can be acquired.\n\n    Sub-interpreter destruction temporarily activates the sub-interpreter. The\n    sub-interpreter must not be active (on any threads) at the time the\n    :class:`subinterpreter` destructor is called.\n\n    Both actions will re-acquire any interpreter's GIL that was held prior to\n    the call before returning (or return to no active interpreter if none was\n    active at the time of the call).\n\nEach sub-interpreter will import a separate copy of each ``PYBIND11_EMBEDDED_MODULE``\nwhen those modules specify a ``multiple_interpreters`` tag. If a module does not\nspecify a ``multiple_interpreters`` tag, then Python will report an ``ImportError``\nif it is imported in a sub-interpreter.\n\npybind11 also has a :class:`scoped_subinterpreter` class, which creates and\nactivates a sub-interpreter when it is constructed, and deactivates and deletes\nit when it goes out of scope.\n\nActivating a Sub-interpreter\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nOnce a sub-interpreter is created, you can \"activate\" it on a thread (and\nacquire its GIL) by creating a :class:`subinterpreter_scoped_activate`\ninstance and passing it the sub-interpreter to be activated.  The function\nwill acquire the sub-interpreter's GIL and make the sub-interpreter the\ncurrent active interpreter on the current thread for the lifetime of the\ninstance. When the :class:`subinterpreter_scoped_activate` instance goes out\nof scope, the sub-interpreter GIL is released and the prior interpreter that\nwas active on the thread (if any) is reactivated and it's GIL is re-acquired.\n\nWhen using ``subinterpreter_scoped_activate``:\n\n1. If the thread holds any interpreter's GIL:\n   - That GIL is released\n2. The new sub-interpreter's GIL is acquired\n3. The new sub-interpreter is made active.\n4. When the scope ends:\n    - The sub-interpreter's GIL is released\n    - If there was a previous interpreter:\n        - The old interpreter's GIL is re-acquired\n        - The old interpreter is made active\n    - Otherwise, no interpreter is currently active and no GIL is held.\n\nExample:\n\n.. code-block:: cpp\n\n    py::initialize_interpreter();\n    // Main GIL is held\n    {\n        py::subinterpreter sub = py::subinterpreter::create();\n        // Main interpreter is still active, main GIL re-acquired\n        {\n            py::subinterpreter_scoped_activate guard(sub);\n            // Sub-interpreter active, thread holds sub's GIL\n            {\n                py::subinterpreter_scoped_activate main_guard(py);\n                // Sub's GIL was automatically released\n                // Main interpreter active, thread holds main's GIL\n            }\n            // Back to sub-interpreter, thread holds sub's GIL again\n        }\n        // Main interpreter is active, main's GIL is held\n    }\n\n\nGIL API for sub-interpreters\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n:class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be used to\nmanage the GIL of a sub-interpreter just as they do for the main interpreter.\nThey both manage the GIL of the currently active interpreter, without the\nprogrammer having to do anything special or different. There is one important\ncaveat:\n\n.. note::\n\n    When no interpreter is active through a\n    :class:`subinterpreter_scoped_activate` instance (such as on a new thread),\n    :class:`gil_scoped_acquire` will acquire the **main** GIL and\n    activate the **main** interpreter.\n\n\nFull Sub-interpreter example\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nHere is an example showing how to create and activate sub-interpreters:\n\n.. code-block:: cpp\n\n    #include <iostream>\n    #include <pybind11/embed.h>\n    #include <pybind11/subinterpreter.h>\n\n    namespace py = pybind11;\n\n    PYBIND11_EMBEDDED_MODULE(printer, m, py::multiple_interpreters::per_interpreter_gil()) {\n        m.def(\"which\", [](const std::string& when) {\n            std::cout << when << \"; Current Interpreter is \"\n                    << py::subinterpreter::current().id()\n                    << std::endl;\n        });\n    }\n\n    int main() {\n        py::scoped_interpreter main_interp;\n\n        py::module_::import(\"printer\").attr(\"which\")(\"First init\");\n\n        {\n            py::subinterpreter sub = py::subinterpreter::create();\n\n            py::module_::import(\"printer\").attr(\"which\")(\"Created sub\");\n\n            {\n                py::subinterpreter_scoped_activate guard(sub);\n                try {\n                    py::module_::import(\"printer\").attr(\"which\")(\"Activated sub\");\n                }\n                catch (py::error_already_set &e) {\n                    std::cerr << \"EXCEPTION \" << e.what() << std::endl;\n                    return 1;\n                }\n            }\n\n            py::module_::import(\"printer\").attr(\"which\")(\"Deactivated sub\");\n\n            {\n                py::gil_scoped_release nogil;\n                {\n                    py::subinterpreter_scoped_activate guard(sub);\n                    try {\n                        {\n                            py::subinterpreter_scoped_activate main_guard(py::subinterpreter::main());\n                            try {\n                                py::module_::import(\"printer\").attr(\"which\")(\"Main within sub\");\n                            }\n                            catch (py::error_already_set &e) {\n                                std::cerr << \"EXCEPTION \" << e.what() << std::endl;\n                                return 1;\n                            }\n                        }\n                        py::module_::import(\"printer\").attr(\"which\")(\"After Main, still within sub\");\n                    }\n                    catch (py::error_already_set &e) {\n                        std::cerr << \"EXCEPTION \" << e.what() << std::endl;\n                        return 1;\n                    }\n                }\n            }\n        }\n\n        py::module_::import(\"printer\").attr(\"which\")(\"At end\");\n\n        return 0;\n    }\n\nExpected output:\n\n.. code-block:: text\n\n    First init; Current Interpreter is 0\n    Created sub; Current Interpreter is 0\n    Activated sub; Current Interpreter is 1\n    Deactivated sub; Current Interpreter is 0\n    Main within sub; Current Interpreter is 0\n    After Main, still within sub; Current Interpreter is 1\n    At end; Current Interpreter is 0\n\n.. warning::\n\n    In Python 3.12 sub-interpreters must be destroyed in the same OS thread\n    that created them.  Failure to follow this rule may result in deadlocks\n    or crashes when destroying the sub-interpreter on the wrong thread.\n\n    This constraint is not present in Python 3.13+.\n\n\nBest Practices for sub-interpreter safety\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- Never share Python objects across different interpreters.\n\n- :class:`error_already_set` objects contain a reference to the Python exception type,\n  and :func:`error_already_set::what()` acquires the GIL. So Python exceptions must\n  **never** be allowed to propagate past the enclosing\n  :class:`subinterpreter_scoped_activate` instance!\n  (So your try/catch should be *just inside* the scope covered by the\n  :class:`subinterpreter_scoped_activate`.)\n\n- Avoid global/static state whenever possible. Instead, keep state within each interpreter,\n  such as within the interpreter state dict, which can be accessed via\n  ``subinterpreter::current().state_dict()``, or within instance members and tied to\n  Python objects.\n\n- Avoid trying to \"cache\" Python objects in C++ variables across function calls (this is an easy\n  way to accidentally introduce sub-interpreter bugs). In the code example above, note that we\n  did not save the result of :func:`module_::import`, in order to avoid accidentally using the\n  resulting Python object when the wrong interpreter was active.\n\n- Avoid moving or disarming RAII objects managing GIL and sub-interpreter lifetimes. Doing so can\n  lead to confusion about lifetimes.  (For example, accidentally extending a\n  :class:`subinterpreter_scoped_activate` past the lifetime of it's :class:`subinterpreter`.)\n\n- While sub-interpreters each have their own GIL, there can now be multiple independent GILs in one\n  program so you need to consider the possibility of deadlocks caused by multiple GILs and/or the\n  interactions of the GIL(s) and your C++ code's own locking.\n\n- When using multiple threads to run independent sub-interpreters, the independent GILs allow\n  concurrent calls from different interpreters into the same C++ code from different threads.\n  So you must still consider the thread safety of your C++ code.  Remember, in Python 3.12\n  sub-interpreters must be destroyed on the same thread that they were created on.\n\n- When using sub-interpreters in free-threaded python builds, note that creating and destroying\n  sub-interpreters may initiate a \"stop-the-world\".  Be sure to detach long-running C++ threads\n  from Python thread state (similar to releasing the GIL) to avoid deadlocks.\n\n- Familiarize yourself with :ref:`misc_concurrency`.\n"
  },
  {
    "path": "docs/advanced/exceptions.rst",
    "content": "Exceptions\n##########\n\nBuilt-in C++ to Python exception translation\n============================================\n\nWhen Python calls C++ code through pybind11, pybind11 provides a C++ exception handler\nthat will trap C++ exceptions, translate them to the corresponding Python exception,\nand raise them so that Python code can handle them.\n\npybind11 defines translations for ``std::exception`` and its standard\nsubclasses, and several special exception classes that translate to specific\nPython exceptions. Note that these are not actually Python exceptions, so they\ncannot be examined using the Python C API. Instead, they are pure C++ objects\nthat pybind11 will translate the corresponding Python exception when they arrive\nat its exception handler.\n\n.. tabularcolumns:: |p{0.5\\textwidth}|p{0.45\\textwidth}|\n\n+--------------------------------------+--------------------------------------+\n|  Exception thrown by C++             |  Translated to Python exception type |\n+======================================+======================================+\n| :class:`std::exception`              | ``RuntimeError``                     |\n+--------------------------------------+--------------------------------------+\n| :class:`std::bad_alloc`              | ``MemoryError``                      |\n+--------------------------------------+--------------------------------------+\n| :class:`std::domain_error`           | ``ValueError``                       |\n+--------------------------------------+--------------------------------------+\n| :class:`std::invalid_argument`       | ``ValueError``                       |\n+--------------------------------------+--------------------------------------+\n| :class:`std::length_error`           | ``ValueError``                       |\n+--------------------------------------+--------------------------------------+\n| :class:`std::out_of_range`           | ``IndexError``                       |\n+--------------------------------------+--------------------------------------+\n| :class:`std::range_error`            | ``ValueError``                       |\n+--------------------------------------+--------------------------------------+\n| :class:`std::overflow_error`         | ``OverflowError``                    |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::stop_iteration`    | ``StopIteration`` (used to implement |\n|                                      | custom iterators)                    |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::index_error`       | ``IndexError`` (used to indicate out |\n|                                      | of bounds access in ``__getitem__``, |\n|                                      | ``__setitem__``, etc.)               |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::key_error`         | ``KeyError`` (used to indicate out   |\n|                                      | of bounds access in ``__getitem__``, |\n|                                      | ``__setitem__`` in dict-like         |\n|                                      | objects, etc.)                       |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::value_error`       | ``ValueError`` (used to indicate     |\n|                                      | wrong value passed in                |\n|                                      | ``container.remove(...)``)           |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::type_error`        | ``TypeError``                        |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::buffer_error`      | ``BufferError``                      |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::import_error`      | ``ImportError``                      |\n+--------------------------------------+--------------------------------------+\n| :class:`pybind11::attribute_error`   | ``AttributeError``                   |\n+--------------------------------------+--------------------------------------+\n| Any other exception                  | ``RuntimeError``                     |\n+--------------------------------------+--------------------------------------+\n\nException translation is not bidirectional. That is, *catching* the C++\nexceptions defined above will not trap exceptions that originate from\nPython. For that, catch :class:`pybind11::error_already_set`. See :ref:`below\n<handling_python_exceptions_cpp>` for further details.\n\nThere is also a special exception :class:`cast_error` that is thrown by\n:func:`handle::call` when the input arguments cannot be converted to Python\nobjects.\n\nRegistering custom translators\n==============================\n\nIf the default exception conversion policy described above is insufficient,\npybind11 also provides support for registering custom exception translators.\nSimilar to pybind11 classes, exception translators can be local to the module\nthey are defined in or global to the entire python session.  To register a simple\nexception conversion that translates a C++ exception into a new Python exception\nusing the C++ exception's ``what()`` method, a helper function is available:\n\n.. code-block:: cpp\n\n    py::register_exception<CppExp>(module, \"PyExp\");\n\nThis call creates a Python exception class with the name ``PyExp`` in the given\nmodule and automatically converts any encountered exceptions of type ``CppExp``\ninto Python exceptions of type ``PyExp``.\n\nA matching function is available for registering a local exception translator:\n\n.. code-block:: cpp\n\n    py::register_local_exception<CppExp>(module, \"PyExp\");\n\n\nIt is possible to specify base class for the exception using the third\nparameter, a ``handle``:\n\n.. code-block:: cpp\n\n    py::register_exception<CppExp>(module, \"PyExp\", PyExc_RuntimeError);\n    py::register_local_exception<CppExp>(module, \"PyExp\", PyExc_RuntimeError);\n\nThen ``PyExp`` can be caught both as ``PyExp`` and ``RuntimeError``.\n\nThe class objects of the built-in Python exceptions are listed in the Python\ndocumentation on `Standard Exceptions <https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_.\nThe default base class is ``PyExc_Exception``.\n\nWhen more advanced exception translation is needed, the functions\n``py::register_exception_translator(translator)`` and\n``py::register_local_exception_translator(translator)`` can be used to register\nfunctions that can translate arbitrary exception types (and which may include\nadditional logic to do so).  The functions takes a stateless callable (e.g. a\nfunction pointer or a lambda function without captured variables) with the call\nsignature ``void(std::exception_ptr)``.\n\nWhen a C++ exception is thrown, the registered exception translators are tried\nin reverse order of registration (i.e. the last registered translator gets the\nfirst shot at handling the exception). All local translators will be tried\nbefore a global translator is tried.\n\nInside the translator, ``std::rethrow_exception`` should be used within\na try block to re-throw the exception.  One or more catch clauses to catch\nthe appropriate exceptions should then be used with each clause using\n``py::set_error()`` (see below).\n\nTo declare a custom Python exception type, declare a ``py::exception`` variable\nand use this in the associated exception translator (note: it is often useful\nto make this a static declaration when using it inside a lambda expression\nwithout requiring capturing).\n\nThe following example demonstrates this for a hypothetical exception classes\n``MyCustomException`` and ``OtherException``: the first is translated to a\ncustom python exception ``MyCustomError``, while the second is translated to a\nstandard python RuntimeError:\n\n.. code-block:: cpp\n\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> exc_storage;\n    exc_storage.call_once_and_store_result(\n        [&]() { return py::exception<MyCustomException>(m, \"MyCustomError\"); });\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) std::rethrow_exception(p);\n        } catch (const MyCustomException &e) {\n            py::set_error(exc_storage.get_stored(), e.what());\n        } catch (const OtherException &e) {\n            py::set_error(PyExc_RuntimeError, e.what());\n        }\n    });\n\nMultiple exceptions can be handled by a single translator, as shown in the\nexample above. If the exception is not caught by the current translator, the\npreviously registered one gets a chance.\n\nIf none of the registered exception translators is able to handle the\nexception, it is handled by the default converter as described in the previous\nsection.\n\n.. seealso::\n\n    The file :file:`tests/test_exceptions.cpp` contains examples\n    of various custom exception translators and custom exception types.\n\n.. note::\n\n    Call ``py::set_error()`` for every exception caught in a custom exception\n    translator.  Failure to do so will cause Python to crash with ``SystemError:\n    error return without exception set``.\n\n    Exceptions that you do not plan to handle should simply not be caught, or\n    may be explicitly (re-)thrown to delegate it to the other,\n    previously-declared existing exception translators.\n\n    Note that ``libc++`` and ``libstdc++`` `behave differently under macOS\n    <https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure/28827430>`_\n    with ``-fvisibility=hidden``. Therefore exceptions that are used across ABI\n    boundaries need to be explicitly exported, as exercised in\n    ``tests/test_exceptions.h``. See also:\n    \"Problems with C++ exceptions\" under `GCC Wiki <https://gcc.gnu.org/wiki/Visibility>`_.\n\n\nLocal vs Global Exception Translators\n=====================================\n\nWhen a global exception translator is registered, it will be applied across all\nmodules in the reverse order of registration. This can create behavior where the\norder of module import influences how exceptions are translated.\n\nIf module1 has the following translator:\n\n.. code-block:: cpp\n\n      py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) std::rethrow_exception(p);\n        } catch (const std::invalid_argument &e) {\n            py::set_error(PyExc_ArgumentError, \"module1 handled this\");\n        }\n      }\n\nand module2 has the following similar translator:\n\n.. code-block:: cpp\n\n      py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) std::rethrow_exception(p);\n        } catch (const std::invalid_argument &e) {\n            py::set_error(PyExc_ArgumentError, \"module2 handled this\");\n        }\n      }\n\nthen which translator handles the invalid_argument will be determined by the\norder that module1 and module2 are imported. Since exception translators are\napplied in the reverse order of registration, which ever module was imported\nlast will \"win\" and that translator will be applied.\n\nIf there are multiple pybind11 modules that share exception types (either\nstandard built-in or custom) loaded into a single python instance and\nconsistent error handling behavior is needed, then local translators should be\nused.\n\nChanging the previous example to use ``register_local_exception_translator``\nwould mean that when invalid_argument is thrown in the module2 code, the\nmodule2 translator will always handle it, while in module1, the module1\ntranslator will do the same.\n\n.. _handling_python_exceptions_cpp:\n\nHandling exceptions from Python in C++\n======================================\n\nWhen C++ calls Python functions, such as in a callback function or when\nmanipulating Python objects, and Python raises an ``Exception``, pybind11\nconverts the Python exception into a C++ exception of type\n:class:`pybind11::error_already_set` whose payload contains a C++ string textual\nsummary and the actual Python exception. ``error_already_set`` is used to\npropagate Python exception back to Python (or possibly, handle them in C++).\n\n.. tabularcolumns:: |p{0.5\\textwidth}|p{0.45\\textwidth}|\n\n+--------------------------------------+--------------------------------------+\n|  Exception raised in Python          |  Thrown as C++ exception type        |\n+======================================+======================================+\n| Any Python ``Exception``             | :class:`pybind11::error_already_set` |\n+--------------------------------------+--------------------------------------+\n\nFor example:\n\n.. code-block:: cpp\n\n    try {\n        // open(\"missing.txt\", \"r\")\n        auto file = py::module_::import(\"io\").attr(\"open\")(\"missing.txt\", \"r\");\n        auto text = file.attr(\"read\")();\n        file.attr(\"close\")();\n    } catch (py::error_already_set &e) {\n        if (e.matches(PyExc_FileNotFoundError)) {\n            py::print(\"missing.txt not found\");\n        } else if (e.matches(PyExc_PermissionError)) {\n            py::print(\"missing.txt found but not accessible\");\n        } else {\n            throw;\n        }\n    }\n\nNote that C++ to Python exception translation does not apply here, since that is\na method for translating C++ exceptions to Python, not vice versa. The error raised\nfrom Python is always ``error_already_set``.\n\nThis example illustrates this behavior:\n\n.. code-block:: cpp\n\n    try {\n        py::eval(\"raise ValueError('The Ring')\");\n    } catch (py::value_error &boromir) {\n        // Boromir never gets the ring\n        assert(false);\n    } catch (py::error_already_set &frodo) {\n        // Frodo gets the ring\n        py::print(\"I will take the ring\");\n    }\n\n    try {\n        // py::value_error is a request for pybind11 to raise a Python exception\n        throw py::value_error(\"The ball\");\n    } catch (py::error_already_set &cat) {\n        // cat won't catch the ball since\n        // py::value_error is not a Python exception\n        assert(false);\n    } catch (py::value_error &dog) {\n        // dog will catch the ball\n        py::print(\"Run Spot run\");\n        throw;  // Throw it again (pybind11 will raise ValueError)\n    }\n\nHandling errors from the Python C API\n=====================================\n\nWhere possible, use :ref:`pybind11 wrappers <wrappers>` instead of calling\nthe Python C API directly. When calling the Python C API directly, in\naddition to manually managing reference counts, one must follow the pybind11\nerror protocol, which is outlined here.\n\nAfter calling the Python C API, if Python returns an error,\n``throw py::error_already_set();``, which allows pybind11 to deal with the\nexception and pass it back to the Python interpreter. This includes calls to\nthe error setting functions such as ``py::set_error()``.\n\n.. code-block:: cpp\n\n    py::set_error(PyExc_TypeError, \"C API type error demo\");\n    throw py::error_already_set();\n\n    // But it would be easier to simply...\n    throw py::type_error(\"pybind11 wrapper type error\");\n\nAlternately, to ignore the error, call `PyErr_Clear\n<https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear>`_.\n\nAny Python error must be thrown or cleared, or Python/pybind11 will be left in\nan invalid state.\n\nHandling warnings from the Python C API\n=======================================\n\nWrappers for handling Python warnings are provided in ``pybind11/warnings.h``.\nThis header must be included explicitly; it is not transitively included via\n``pybind11/pybind11.h``.\n\nWarnings can be raised with the ``warn`` function:\n\n.. code-block:: cpp\n\n    py::warnings::warn(\"This is a warning!\", PyExc_Warning);\n\n    // Optionally, a `stack_level` can be specified.\n    py::warnings::warn(\"Another one!\", PyExc_DeprecationWarning, 3);\n\nNew warning types can be registered at the module level using ``new_warning_type``:\n\n.. code-block:: cpp\n\n    py::warnings::new_warning_type(m, \"CustomWarning\", PyExc_RuntimeWarning);\n\nChaining exceptions ('raise from')\n==================================\n\nPython has a mechanism for indicating that exceptions were caused by other\nexceptions:\n\n.. code-block:: py\n\n    try:\n        print(1 / 0)\n    except Exception as exc:\n        raise RuntimeError(\"could not divide by zero\") from exc\n\nTo do a similar thing in pybind11, you can use the ``py::raise_from`` function. It\nsets the current python error indicator, so to continue propagating the exception\nyou should ``throw py::error_already_set()``.\n\n.. code-block:: cpp\n\n    try {\n        py::eval(\"print(1 / 0\"));\n    } catch (py::error_already_set &e) {\n        py::raise_from(e, PyExc_RuntimeError, \"could not divide by zero\");\n        throw py::error_already_set();\n    }\n\n.. versionadded:: 2.8\n\n.. _unraisable_exceptions:\n\nHandling unraisable exceptions\n==============================\n\nIf a Python function invoked from a C++ destructor or any function marked\n``noexcept(true)`` (collectively, \"noexcept functions\") throws an exception, there\nis no way to propagate the exception, as such functions may not throw.\nShould they throw or fail to catch any exceptions in their call graph,\nthe C++ runtime calls ``std::terminate()`` to abort immediately.\n\nSimilarly, Python exceptions raised in a class's ``__del__`` method do not\npropagate, but ``sys.unraisablehook()`` `is triggered\n<https://docs.python.org/3/library/sys.html#sys.unraisablehook>`_\nand an auditing event is logged.\n\nAny noexcept function should have a try-catch block that traps\nclass:`error_already_set` (or any other exception that can occur). Note that\npybind11 wrappers around Python exceptions such as\n:class:`pybind11::value_error` are *not* Python exceptions; they are C++\nexceptions that pybind11 catches and converts to Python exceptions. Noexcept\nfunctions cannot propagate these exceptions either. A useful approach is to\nconvert them to Python exceptions and then ``discard_as_unraisable`` as shown\nbelow.\n\n.. code-block:: cpp\n\n    void nonthrowing_func() noexcept(true) {\n        try {\n            // ...\n        } catch (py::error_already_set &eas) {\n            // Discard the Python error using Python APIs, using the C++ magic\n            // variable __func__. Python already knows the type and value and of the\n            // exception object.\n            eas.discard_as_unraisable(__func__);\n        } catch (const std::exception &e) {\n            // Log and discard C++ exceptions.\n            third_party::log(e);\n        }\n    }\n\n.. versionadded:: 2.6\n"
  },
  {
    "path": "docs/advanced/functions.rst",
    "content": "Functions\n#########\n\nBefore proceeding with this section, make sure that you are already familiar\nwith the basics of binding functions and classes, as explained in :doc:`/basics`\nand :doc:`/classes`. The following guide is applicable to both free and member\nfunctions, i.e. *methods* in Python.\n\n.. _return_value_policies:\n\nReturn value policies\n=====================\n\nPython and C++ use fundamentally different ways of managing the memory and\nlifetime of objects managed by them. This can lead to issues when creating\nbindings for functions that return a non-trivial type. Just by looking at the\ntype information, it is not clear whether Python should take charge of the\nreturned value and eventually free its resources, or if this is handled on the\nC++ side. For this reason, pybind11 provides several *return value policy*\nannotations that can be passed to the :func:`module_::def` and\n:func:`class_::def` functions. The default policy is\n:enum:`return_value_policy::automatic`.\n\nReturn value policies are tricky, and it's very important to get them right.\nJust to illustrate what can go wrong, consider the following simple example:\n\n.. code-block:: cpp\n\n    /* Function declaration */\n    Data *get_data() { return _data; /* (pointer to a static data structure) */ }\n    ...\n\n    /* Binding code */\n    m.def(\"get_data\", &get_data); // <-- KABOOM, will cause crash when called from Python\n\nWhat's going on here? When ``get_data()`` is called from Python, the return\nvalue (a native C++ type) must be wrapped to turn it into a usable Python type.\nIn this case, the default return value policy (:enum:`return_value_policy::automatic`)\ncauses pybind11 to assume ownership of the static ``_data`` instance.\n\nWhen Python's garbage collector eventually deletes the Python\nwrapper, pybind11 will also attempt to delete the C++ instance (via ``operator\ndelete()``) due to the implied ownership. At this point, the entire application\nwill come crashing down, though errors could also be more subtle and involve\nsilent data corruption.\n\nIn the above example, the policy :enum:`return_value_policy::reference` should have\nbeen specified so that the global data instance is only *referenced* without any\nimplied transfer of ownership, i.e.:\n\n.. code-block:: cpp\n\n    m.def(\"get_data\", &get_data, py::return_value_policy::reference);\n\nOn the other hand, this is not the right policy for many other situations,\nwhere ignoring ownership could lead to resource leaks.\nAs a developer using pybind11, it's important to be familiar with the different\nreturn value policies, including which situation calls for which one of them.\nThe following table provides an overview of available policies:\n\n.. tabularcolumns:: |p{0.5\\textwidth}|p{0.45\\textwidth}|\n\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| Return value policy                              | Description                                                                |\n+==================================================+============================================================================+\n| :enum:`return_value_policy::take_ownership`      | Reference an existing object (i.e. do not create a new copy) and take      |\n|                                                  | ownership. Python will call the destructor and delete operator when the    |\n|                                                  | object's reference count reaches zero. Undefined behavior ensues when the  |\n|                                                  | C++ side does the same, or when the data was not dynamically allocated.    |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::copy`                | Create a new copy of the returned object, which will be owned by Python.   |\n|                                                  | This policy is comparably safe because the lifetimes of the two instances  |\n|                                                  | are decoupled.                                                             |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::move`                | Use ``std::move`` to move the return value contents into a new instance    |\n|                                                  | that will be owned by Python. This policy is comparably safe because the   |\n|                                                  | lifetimes of the two instances (move source and destination) are decoupled.|\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::reference`           | Reference an existing object, but do not take ownership. The C++ side is   |\n|                                                  | responsible for managing the object's lifetime and deallocating it when    |\n|                                                  | it is no longer used. Warning: undefined behavior will ensue when the C++  |\n|                                                  | side deletes an object that is still referenced and used by Python.        |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::reference_internal`  | If the return value is an lvalue reference or a pointer, the parent object |\n|                                                  | (the implicit ``this``, or ``self`` argument of the called method or       |\n|                                                  | property) is kept alive for at least the lifespan of the return value.     |\n|                                                  | **Otherwise this policy falls back to** :enum:`return_value_policy::move`  |\n|                                                  | (see #5528). Internally, this policy works just like                       |\n|                                                  | :enum:`return_value_policy::reference` but additionally applies a          |\n|                                                  | ``keep_alive<0, 1>`` *call policy* (described in the next section) that    |\n|                                                  | prevents the parent object from being garbage collected as long as the     |\n|                                                  | return value is referenced by Python. This is the default policy for       |\n|                                                  | property getters created via ``def_property``, ``def_readwrite``, etc.     |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::automatic`           | This policy falls back to the policy                                       |\n|                                                  | :enum:`return_value_policy::take_ownership` when the return value is a     |\n|                                                  | pointer. Otherwise, it uses :enum:`return_value_policy::move` or           |\n|                                                  | :enum:`return_value_policy::copy` for rvalue and lvalue references,        |\n|                                                  | respectively. See above for a description of what all of these different   |\n|                                                  | policies do. This is the default policy for ``py::class_``-wrapped types.  |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n| :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the   |\n|                                                  | return value is a pointer. This is the default conversion policy for       |\n|                                                  | function arguments when calling Python functions manually from C++ code    |\n|                                                  | (i.e. via ``handle::operator()``) and the casters in ``pybind11/stl.h``.   |\n|                                                  | You probably won't need to use this explicitly.                            |\n+--------------------------------------------------+----------------------------------------------------------------------------+\n\nReturn value policies can also be applied to properties:\n\n.. code-block:: cpp\n\n    class_<MyClass>(m, \"MyClass\")\n        .def_property(\"data\", &MyClass::getData, &MyClass::setData,\n                      py::return_value_policy::copy);\n\nTechnically, the code above applies the policy to both the getter and the\nsetter function, however, the setter doesn't really care about *return*\nvalue policies which makes this a convenient terse syntax. Alternatively,\ntargeted arguments can be passed through the :class:`cpp_function` constructor:\n\n.. code-block:: cpp\n\n    class_<MyClass>(m, \"MyClass\")\n        .def_property(\"data\",\n            py::cpp_function(&MyClass::getData, py::return_value_policy::copy),\n            py::cpp_function(&MyClass::setData)\n        );\n\n.. warning::\n\n    Code with invalid return value policies might access uninitialized memory or\n    free data structures multiple times, which can lead to hard-to-debug\n    non-determinism and segmentation faults, hence it is worth spending the\n    time to understand all the different options in the table above.\n\n.. note::\n\n    One important aspect of the above policies is that they only apply to\n    instances which pybind11 has *not* seen before, in which case the policy\n    clarifies essential questions about the return value's lifetime and\n    ownership.  When pybind11 knows the instance already (as identified by its\n    type and address in memory), it will return the existing Python object\n    wrapper rather than creating a new copy.\n\n.. note::\n\n    The next section on :ref:`call_policies` discusses *call policies* that can be\n    specified *in addition* to a return value policy from the list above. Call\n    policies indicate reference relationships that can involve both return values\n    and parameters of functions.\n\n.. note::\n\n   As an alternative to elaborate call policies and lifetime management logic,\n   consider using smart pointers (see the section on :ref:`smart_pointers` for\n   details). Smart pointers can tell whether an object is still referenced from\n   C++ or Python, which generally eliminates the kinds of inconsistencies that\n   can lead to crashes or undefined behavior. For functions returning smart\n   pointers, it is not necessary to specify a return value policy.\n\n.. _call_policies:\n\nAdditional call policies\n========================\n\nIn addition to the above return value policies, further *call policies* can be\nspecified to indicate dependencies between parameters or ensure a certain state\nfor the function call.\n\nKeep alive\n----------\n\nIn general, this policy is required when the C++ object is any kind of container\nand another object is being added to the container. ``keep_alive<Nurse, Patient>``\nindicates that the argument with index ``Patient`` should be kept alive at least\nuntil the argument with index ``Nurse`` is freed by the garbage collector. Argument\nindices start at one, while zero refers to the return value. For methods, index\n``1`` refers to the implicit ``this`` pointer, while regular arguments begin at\nindex ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``\nwith value ``None`` is detected at runtime, the call policy does nothing.\n\nWhen the nurse is not a pybind11-registered type, the implementation internally\nrelies on the ability to create a *weak reference* to the nurse object. When\nthe nurse object is not a pybind11-registered type and does not support weak\nreferences, an exception will be thrown.\n\nIf you use an incorrect argument index, you will get a ``RuntimeError`` saying\n``Could not activate keep_alive!``. You should review the indices you're using.\n\nConsider the following example: here, the binding code for a list append\noperation ties the lifetime of the newly added element to the underlying\ncontainer:\n\n.. code-block:: cpp\n\n    py::class_<List>(m, \"List\")\n        .def(\"append\", &List::append, py::keep_alive<1, 2>());\n\nFor consistency, the argument indexing is identical for constructors. Index\n``1`` still refers to the implicit ``this`` pointer, i.e. the object which is\nbeing constructed. Index ``0`` refers to the return type which is presumed to\nbe ``void`` when a constructor is viewed like a function. The following example\nties the lifetime of the constructor element to the constructed object:\n\n.. code-block:: cpp\n\n    py::class_<Nurse>(m, \"Nurse\")\n        .def(py::init<Patient &>(), py::keep_alive<1, 2>());\n\n.. note::\n\n    ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,\n    Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==\n    0) policies from Boost.Python.\n\nCall guard\n----------\n\nThe ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed\naround the function call. For example, this definition:\n\n.. code-block:: cpp\n\n    m.def(\"foo\", foo, py::call_guard<T>());\n\nis equivalent to the following pseudocode:\n\n.. code-block:: cpp\n\n    m.def(\"foo\", [](args...) {\n        T scope_guard;\n        return foo(args...); // forwarded arguments\n    });\n\nThe only requirement is that ``T`` is default-constructible, but otherwise any\nscope guard will work. This is very useful in combination with ``gil_scoped_release``.\nSee :ref:`gil`.\n\nMultiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The\nconstructor order is left to right and destruction happens in reverse.\n\n.. seealso::\n\n    The file :file:`tests/test_call_policies.cpp` contains a complete example\n    that demonstrates using `keep_alive` and `call_guard` in more detail.\n\n.. _python_objects_as_args:\n\nPython objects as arguments\n===========================\n\npybind11 exposes all major Python types using thin C++ wrapper classes. These\nwrapper classes can also be used as parameters of functions in bindings, which\nmakes it possible to directly work with native Python types on the C++ side.\nFor instance, the following statement iterates over a Python ``dict``:\n\n.. code-block:: cpp\n\n    void print_dict(const py::dict& dict) {\n        /* Easily interact with Python types */\n        for (auto item : dict)\n            std::cout << \"key=\" << std::string(py::str(item.first)) << \", \"\n                      << \"value=\" << std::string(py::str(item.second)) << std::endl;\n    }\n\nIt can be exported:\n\n.. code-block:: cpp\n\n    m.def(\"print_dict\", &print_dict);\n\nAnd used in Python as usual:\n\n.. code-block:: pycon\n\n    >>> print_dict({\"foo\": 123, \"bar\": \"hello\"})\n    key=foo, value=123\n    key=bar, value=hello\n\nFor more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.\n\nAccepting \\*args and \\*\\*kwargs\n===============================\n\nPython provides a useful mechanism to define functions that accept arbitrary\nnumbers of arguments and keyword arguments:\n\n.. code-block:: python\n\n   def generic(*args, **kwargs):\n       ...  # do something with args and kwargs\n\nSuch functions can also be created using pybind11:\n\n.. code-block:: cpp\n\n   void generic(py::args args, const py::kwargs& kwargs) {\n       /// .. do something with args\n       if (kwargs)\n           /// .. do something with kwargs\n   }\n\n   /// Binding code\n   m.def(\"generic\", &generic);\n\nThe class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives\nfrom ``py::dict``.\n\nYou may also use just one or the other, and may combine these with other\narguments.  Note, however, that ``py::kwargs`` must always be the last argument\nof the function, and ``py::args`` implies that any further arguments are\nkeyword-only (see :ref:`keyword_only_arguments`).\n\nPlease refer to the other examples for details on how to iterate over these,\nand on how to cast their entries into C++ objects. A demonstration is also\navailable in ``tests/test_kwargs_and_defaults.cpp``.\n\n.. note::\n\n    When combining \\*args or \\*\\*kwargs with :ref:`keyword_args` you should\n    *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``\n    arguments.\n\nDefault arguments revisited\n===========================\n\nThe section on :ref:`default_args` previously discussed basic usage of default\narguments using pybind11. One noteworthy aspect of their implementation is that\ndefault arguments are converted to Python objects right at declaration time.\nConsider the following example:\n\n.. code-block:: cpp\n\n    py::class_<MyClass>(\"MyClass\")\n        .def(\"myFunction\", py::arg(\"arg\") = SomeType(123));\n\nIn this case, pybind11 must already be set up to deal with values of the type\n``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an\nexception will be thrown.\n\nAnother aspect worth highlighting is that the \"preview\" of the default argument\nin the function signature is generated using the object's ``__repr__`` method.\nIf not available, the signature may not be very helpful, e.g.:\n\n.. code-block:: pycon\n\n    FUNCTIONS\n    ...\n    |  myFunction(...)\n    |      Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType\n    ...\n\nThe first way of addressing this is by defining ``SomeType.__repr__``.\nAlternatively, it is possible to specify the human-readable preview of the\ndefault argument manually using the ``arg_v`` notation:\n\n.. code-block:: cpp\n\n    py::class_<MyClass>(\"MyClass\")\n        .def(\"myFunction\", py::arg_v(\"arg\", SomeType(123), \"SomeType(123)\"));\n\nSometimes it may be necessary to pass a null pointer value as a default\nargument. In this case, remember to cast it to the underlying type in question,\nlike so:\n\n.. code-block:: cpp\n\n    py::class_<MyClass>(\"MyClass\")\n        .def(\"myFunction\", py::arg(\"arg\") = static_cast<SomeType *>(nullptr));\n\n.. _keyword_only_arguments:\n\nKeyword-only arguments\n======================\n\nPython implements keyword-only arguments by specifying an unnamed ``*``\nargument in a function definition:\n\n.. code-block:: python\n\n    def f(a, *, b):  # a can be positional or via keyword; b must be via keyword\n        pass\n\n\n    f(a=1, b=2)  # good\n    f(b=2, a=1)  # good\n    f(1, b=2)  # good\n    f(1, 2)  # TypeError: f() takes 1 positional argument but 2 were given\n\nPybind11 provides a ``py::kw_only`` object that allows you to implement\nthe same behaviour by specifying the object between positional and keyword-only\nargument annotations when registering the function:\n\n.. code-block:: cpp\n\n    m.def(\"f\", [](int a, int b) { /* ... */ },\n          py::arg(\"a\"), py::kw_only(), py::arg(\"b\"));\n\n.. versionadded:: 2.6\n\nA ``py::args`` argument implies that any following arguments are keyword-only,\nas if ``py::kw_only()`` had been specified in the same relative location of the\nargument list as the ``py::args`` argument.  The ``py::kw_only()`` may be\nincluded to be explicit about this, but is not required.\n\n.. versionchanged:: 2.9\n   This can now be combined with ``py::args``. Before, ``py::args`` could only\n   occur at the end of the argument list, or immediately before a ``py::kwargs``\n   argument at the end.\n\n\nPositional-only arguments\n=========================\n\nPython 3.8 introduced a new positional-only argument syntax, using ``/`` in the\nfunction definition (note that this has been a convention for CPython\npositional arguments, such as in ``pow()``, since Python 2). You can\ndo the same thing in any version of Python using ``py::pos_only()``:\n\n.. code-block:: cpp\n\n   m.def(\"f\", [](int a, int b) { /* ... */ },\n          py::arg(\"a\"), py::pos_only(), py::arg(\"b\"));\n\nYou now cannot give argument ``a`` by keyword. This can be combined with\nkeyword-only arguments, as well.\n\n.. versionadded:: 2.6\n\n.. _nonconverting_arguments:\n\nNon-converting arguments\n========================\n\nCertain argument types may support conversion from one type to another.  Some\nexamples of conversions are:\n\n* :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``\n* Passing an argument that implements ``__float__`` or ``__index__`` to ``float`` or ``double``.\n* Passing an argument that implements ``__int__`` or ``__index__`` to ``int``.\n* Passing an argument that implements ``__complex__``, ``__float__``, or ``__index__`` to ``std::complex<float>``.\n  (Requires the optional ``pybind11/complex.h`` header).\n* Calling a function taking an Eigen matrix reference with a numpy array of the\n  wrong type or of an incompatible data layout.  (Requires the optional\n  ``pybind11/eigen.h`` header).\n\nThis behaviour is sometimes undesirable: the binding code may prefer to raise\nan error rather than convert the argument.  This behaviour can be obtained\nthrough ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``\nobject, such as:\n\n.. code-block:: cpp\n\n    m.def(\"supports_float\", [](double f) { return 0.5 * f; }, py::arg(\"f\"));\n    m.def(\"only_float\", [](double f) { return 0.5 * f; }, py::arg(\"f\").noconvert());\n\n``supports_float`` will accept any argument that implements ``__float__`` or ``__index__``.\n``only_float`` will only accept a float or int argument. Anything else will fail with a ``TypeError``:\n\n.. note::\n\n    The noconvert behaviour of float, double and complex has changed to match PEP 484.\n    A float/double argument marked noconvert will accept float or int.\n    A std::complex<float> argument will accept complex, float or int.\n\n.. code-block:: pycon\n\n    class MyFloat:\n        def __init__(self, value: float) -> None:\n            self._value = float(value)\n        def __repr__(self) -> str:\n            return f\"MyFloat({self._value})\"\n        def __float__(self) -> float:\n            return self._value\n\n    >>> supports_float(MyFloat(4))\n    2.0\n    >>> only_float(MyFloat(4))\n    Traceback (most recent call last):\n      File \"<stdin>\", line 1, in <module>\n    TypeError: only_float(): incompatible function arguments. The following argument types are supported:\n        1. (f: float) -> float\n\n    Invoked with: MyFloat(4)\n\nYou may, of course, combine this with the :var:`_a` shorthand notation (see\n:ref:`keyword_args`) and/or :ref:`default_args`.  It is also permitted to omit\nthe argument name by using the ``py::arg()`` constructor without an argument\nname, i.e. by specifying ``py::arg().noconvert()``.\n\n.. note::\n\n    When specifying ``py::arg`` options it is necessary to provide the same\n    number of options as the bound function has arguments.  Thus if you want to\n    enable no-convert behaviour for just one of several arguments, you will\n    need to specify a ``py::arg()`` annotation for each argument with the\n    no-convert argument modified to ``py::arg().noconvert()``.\n\n.. _none_arguments:\n\nAllow/Prohibiting None arguments\n================================\n\nWhen a C++ type registered with :class:`py::class_` is passed as an argument to\na function taking the instance as pointer or shared holder (e.g. ``shared_ptr``\nor a custom, copyable holder as described in :ref:`smart_pointers`), pybind\nallows ``None`` to be passed from Python which results in calling the C++\nfunction with ``nullptr`` (or an empty holder) for the argument.\n\nTo explicitly enable or disable this behaviour, using the\n``.none`` method of the :class:`py::arg` object:\n\n.. code-block:: cpp\n\n    py::class_<Dog>(m, \"Dog\").def(py::init<>());\n    py::class_<Cat>(m, \"Cat\").def(py::init<>());\n    m.def(\"bark\", [](Dog *dog) -> std::string {\n        if (dog) return \"woof!\"; /* Called with a Dog instance */\n        else return \"(no dog)\"; /* Called with None, dog == nullptr */\n    }, py::arg(\"dog\").none(true));\n    m.def(\"meow\", [](Cat *cat) -> std::string {\n        // Can't be called with None argument\n        return \"meow\";\n    }, py::arg(\"cat\").none(false));\n\nWith the above, the Python call ``bark(None)`` will return the string ``\"(no\ndog)\"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:\n\n.. code-block:: pycon\n\n    >>> from animals import Dog, Cat, bark, meow\n    >>> bark(Dog())\n    'woof!'\n    >>> meow(Cat())\n    'meow'\n    >>> bark(None)\n    '(no dog)'\n    >>> meow(None)\n    Traceback (most recent call last):\n      File \"<stdin>\", line 1, in <module>\n    TypeError: meow(): incompatible function arguments. The following argument types are supported:\n        1. (cat: animals.Cat) -> str\n\n    Invoked with: None\n\nThe default behaviour when the tag is unspecified is to allow ``None``.\n\n.. note::\n\n    Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a\n    ``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types\n    (``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``\n    is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will\n    not allow ``None`` as argument.  To pass optional argument of these copied types consider\n    using ``std::optional<T>``\n\n.. _overload_resolution:\n\nOverload resolution order\n=========================\n\nWhen a function or method with multiple overloads is called from Python,\npybind11 determines which overload to call in two passes.  The first pass\nattempts to call each overload without allowing argument conversion (as if\nevery argument had been specified as ``py::arg().noconvert()`` as described\nabove).\n\nIf no overload succeeds in the no-conversion first pass, a second pass is\nattempted in which argument conversion is allowed (except where prohibited via\nan explicit ``py::arg().noconvert()`` attribute in the function definition).\n\nIf the second pass also fails a ``TypeError`` is raised.\n\nWithin each pass, overloads are tried in the order they were registered with\npybind11. If the ``py::prepend()`` tag is added to the definition, a function\ncan be placed at the beginning of the overload sequence instead, allowing user\noverloads to proceed built in functions.\n\nWhat this means in practice is that pybind11 will prefer any overload that does\nnot require conversion of arguments to an overload that does, but otherwise\nprefers earlier-defined overloads to later-defined ones.\n\n.. note::\n\n    pybind11 does *not* further prioritize based on the number/pattern of\n    overloaded arguments.  That is, pybind11 does not prioritize a function\n    requiring one conversion over one requiring three, but only prioritizes\n    overloads requiring no conversion at all to overloads that require\n    conversion of at least one argument.\n\n.. versionadded:: 2.6\n\n    The ``py::prepend()`` tag.\n\nBinding functions with template parameters\n==========================================\n\nYou can bind functions that have template parameters. Here's a function:\n\n.. code-block:: cpp\n\n    template <typename T>\n    void set(T t);\n\nC++ templates cannot be instantiated at runtime, so you cannot bind the\nnon-instantiated function:\n\n.. code-block:: cpp\n\n    // BROKEN (this will not compile)\n    m.def(\"set\", &set);\n\nYou must bind each instantiated function template separately. You may bind\neach instantiation with the same name, which will be treated the same as\nan overloaded function:\n\n.. code-block:: cpp\n\n    m.def(\"set\", &set<int>);\n    m.def(\"set\", &set<std::string>);\n\nSometimes it's more clear to bind them with separate names, which is also\nan option:\n\n.. code-block:: cpp\n\n    m.def(\"setInt\", &set<int>);\n    m.def(\"setString\", &set<std::string>);\n"
  },
  {
    "path": "docs/advanced/misc.rst",
    "content": "Miscellaneous\n#############\n\n.. _macro_notes:\n\nGeneral notes regarding convenience macros\n==========================================\n\npybind11 provides a few convenience macros such as\n:func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERRIDE_*``. Since these\nare \"just\" macros that are evaluated in the preprocessor (which has no concept\nof types), they *will* get confused by commas in a template argument; for\nexample, consider:\n\n.. code-block:: cpp\n\n    PYBIND11_OVERRIDE(MyReturnType<T1, T2>, Class<T3, T4>, func)\n\nThe limitation of the C preprocessor interprets this as five arguments (with new\narguments beginning after each comma) rather than three.  To get around this,\nthere are two alternatives: you can use a type alias, or you can wrap the type\nusing the ``PYBIND11_TYPE`` macro:\n\n.. code-block:: cpp\n\n    // Version 1: using a type alias\n    using ReturnType = MyReturnType<T1, T2>;\n    using ClassType = Class<T3, T4>;\n    PYBIND11_OVERRIDE(ReturnType, ClassType, func);\n\n    // Version 2: using the PYBIND11_TYPE macro:\n    PYBIND11_OVERRIDE(PYBIND11_TYPE(MyReturnType<T1, T2>),\n                      PYBIND11_TYPE(Class<T3, T4>), func)\n\nThe ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.\n\n.. _gil:\n\nGlobal Interpreter Lock (GIL)\n=============================\n\nThe Python C API dictates that the Global Interpreter Lock (GIL) must always\nbe held by the current thread to safely access Python objects. As a result,\nwhen Python calls into C++ via pybind11 the GIL must be held, and pybind11\nwill never implicitly release the GIL.\n\n.. code-block:: cpp\n\n    void my_function() {\n        /* GIL is held when this function is called from Python */\n    }\n\n    PYBIND11_MODULE(example, m) {\n        m.def(\"my_function\", &my_function);\n    }\n\npybind11 will ensure that the GIL is held when it knows that it is calling\nPython code. For example, if a Python callback is passed to C++ code via\n``std::function``, when C++ code calls the function the built-in wrapper\nwill acquire the GIL before calling the Python callback. Similarly, the\n``PYBIND11_OVERRIDE`` family of macros will acquire the GIL before calling\nback into Python.\n\nWhen writing C++ code that is called from other C++ code, if that code accesses\nPython state, it must explicitly acquire and release the GIL. A separate\ndocument on deadlocks [#f8]_ elaborates on a particularly subtle interaction\nwith C++'s block-scope static variable initializer guard mutexes.\n\n.. [#f8] See docs/advanced/deadlock.md\n\nThe classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be\nused to acquire and release the global interpreter lock in the body of a C++\nfunction call. In this way, long-running C++ code can be parallelized using\nmultiple Python threads, **but great care must be taken** when any\n:class:`gil_scoped_release` appear: if there is any way that the C++ code\ncan access Python objects, :class:`gil_scoped_acquire` should be used to\nreacquire the GIL. Taking :ref:`overriding_virtuals` as an example, this\ncould be realized as follows (important changes highlighted):\n\n.. code-block:: cpp\n    :emphasize-lines: 8,30,31\n\n    class PyAnimal : public Animal, public py::trampoline_self_life_support {\n    public:\n        /* Inherit the constructors */\n        using Animal::Animal;\n\n        /* Trampoline (need one for each virtual function) */\n        std::string go(int n_times) {\n            /* PYBIND11_OVERRIDE_PURE will acquire the GIL before accessing Python state */\n            PYBIND11_OVERRIDE_PURE(\n                std::string, /* Return type */\n                Animal,      /* Parent class */\n                go,          /* Name of function */\n                n_times      /* Argument(s) */\n            );\n        }\n    };\n\n    PYBIND11_MODULE(example, m) {\n        py::class_<Animal, PyAnimal, py::smart_holder> animal(m, \"Animal\");\n        animal\n            .def(py::init<>())\n            .def(\"go\", &Animal::go);\n\n        py::class_<Dog, py::smart_holder>(m, \"Dog\", animal)\n            .def(py::init<>());\n\n        m.def(\"call_go\", [](Animal *animal) -> std::string {\n            // GIL is held when called from Python code. Release GIL before\n            // calling into (potentially long-running) C++ code\n            py::gil_scoped_release release;\n            return call_go(animal);\n        });\n    }\n\nThe ``call_go`` wrapper can also be simplified using the ``call_guard`` policy\n(see :ref:`call_policies`) which yields the same result:\n\n.. code-block:: cpp\n\n    m.def(\"call_go\", &call_go, py::call_guard<py::gil_scoped_release>());\n\n\n.. _commongilproblems:\n\nCommon Sources Of Global Interpreter Lock Errors\n==================================================================\n\nFailing to properly hold the Global Interpreter Lock (GIL) is one of the\nmore common sources of bugs within code that uses pybind11. If you are\nrunning into GIL related errors, we highly recommend you consult the\nfollowing checklist.\n\n- Do you have any global variables that are pybind11 objects or invoke\n  pybind11 functions in either their constructor or destructor? You are generally\n  not allowed to invoke any Python function in a global static context. We recommend\n  using lazy initialization and then intentionally leaking at the end of the program.\n\n- Do you have any pybind11 objects that are members of other C++ structures? One\n  commonly overlooked requirement is that pybind11 objects have to increase their reference count\n  whenever their copy constructor is called. Thus, you need to be holding the GIL to invoke\n  the copy constructor of any C++ class that has a pybind11 member. This can sometimes be very\n  tricky to track for complicated programs Think carefully when you make a pybind11 object\n  a member in another struct.\n\n- C++ destructors that invoke Python functions can be particularly troublesome as\n  destructors can sometimes get invoked in weird and unexpected circumstances as a result\n  of exceptions.\n\n- C++ static block-scope variable initialization that calls back into Python can\n  cause deadlocks; see [#f8]_ for a detailed discussion.\n\n- You should try running your code in a debug build. That will enable additional assertions\n  within pybind11 that will throw exceptions on certain GIL handling errors\n  (reference counting operations).\n\n.. _misc_free_threading:\n\nFree-threading support\n==================================================================\n\npybind11 supports the experimental free-threaded builds of Python versions 3.13+.\npybind11's internal data structures are thread safe. To enable your modules to be used with\nfree-threading, pass the :class:`mod_gil_not_used` tag as the third argument to\n``PYBIND11_MODULE``.\n\nFor example:\n\n.. code-block:: cpp\n    :emphasize-lines: 1\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Animal> animal(m, \"Animal\");\n        // etc\n    }\n\nImportantly, enabling your module to be used with free-threading is also your promise that\nyour code is thread safe.  Modules must still be built against the Python free-threading branch to\nenable free-threading, even if they specify this tag.  Adding this tag does not break\ncompatibility with non-free-threaded Python.\n\n.. _misc_subinterp:\n\nSub-interpreter support\n==================================================================\n\npybind11 supports isolated sub-interpreters, which are stable in Python 3.12+.  pybind11's\ninternal data structures are sub-interpreter safe. To enable your modules to be imported in\nisolated sub-interpreters, pass the :func:`multiple_interpreters::per_interpreter_gil()`\ntag as the third or later argument to ``PYBIND11_MODULE``.\n\nFor example:\n\n.. code-block:: cpp\n    :emphasize-lines: 1\n\n    PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil()) {\n        py::class_<Animal> animal(m, \"Animal\");\n        // etc\n    }\n\nBest Practices for Sub-interpreter Safety:\n\n- Your initialization function will run for each interpreter that imports your module.\n\n- Never share Python objects across different sub-interpreters.\n\n- Avoid global/static state whenever possible. Instead, keep state within each interpreter,\n  such as in instance members tied to Python objects, :func:`globals()`, and the interpreter\n  state dict.\n\n- Modules without any global/static state in their C++ code may already be sub-interpreter safe\n  without any additional work!\n\n- Avoid trying to \"cache\" Python objects in C++ variables across function calls (this is an easy\n  way to accidentally introduce sub-interpreter bugs).\n\n- While sub-interpreters each have their own GIL, there can now be multiple independent GILs in one\n  program, so concurrent calls into a module from two different sub-interpreters are still\n  possible. Therefore, your module still needs to consider thread safety.\n\npybind11 also supports \"legacy\" sub-interpreters which shared a single global GIL. You can enable\nlegacy-only behavior by using the :func:`multiple_interpreters::shared_gil()` tag in\n``PYBIND11_MODULE``.\n\nYou can explicitly disable sub-interpreter support in your module by using the\n:func:`multiple_interpreters::not_supported()` tag. This is the default behavior if you do not\nspecify a multiple_interpreters tag.\n\n.. _misc_concurrency:\n\nConcurrency and Parallelism in Python with pybind11\n===================================================\n\nSub-interpreter support does not imply free-threading support or vice versa.  Free-threading safe\nmodules can still have global/static state (as long as access to them is thread-safe), but\nsub-interpreter safe modules cannot.  Likewise, sub-interpreter safe modules can still rely on the\nGIL, but free-threading safe modules cannot.\n\nHere is a simple example module which has a function that calculates a value and returns the result\nof the previous calculation.\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m) {\n        static size_t seed = 0;\n        m.def(\"calc_next\", []() {\n            auto old = seed;\n            seed = (seed + 1) * 10;\n            return old;\n        });\n\nThis module is not free-threading safe because there is no synchronization on the number variable.\nIt is relatively easy to make this free-threading safe.  One way is by using atomics, like this:\n\n.. code-block:: cpp\n    :emphasize-lines: 1,2\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        static std::atomic<size_t> seed(0);\n        m.def(\"calc_next\", []() {\n            size_t old, next;\n            do {\n                old = seed.load();\n                next = (old + 1) * 10;\n            } while (!seed.compare_exchange_weak(old, next));\n            return old;\n        });\n    }\n\nThe atomic variable and the compare-exchange guarantee a consistent behavior from this function even\nwhen called currently from multiple threads at the same time.\n\nHowever, the global/static integer is not sub-interpreter safe, because the calls in one\nsub-interpreter will change what is seen in another. To fix it, the state needs to be specific to\neach interpreter.  One way to do that is by storing the state on another Python object, such as a\nmember of a class. For this simple example, we will store it in :func:`globals`.\n\n.. code-block:: cpp\n    :emphasize-lines: 1,6\n\n    PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil()) {\n        m.def(\"calc_next\", []() {\n            if (!py::globals().contains(\"myseed\"))\n                py::globals()[\"myseed\"] = 0;\n            size_t old = py::globals()[\"myseed\"];\n            py::globals()[\"myseed\"] = (old + 1) * 10;\n            return old;\n        });\n    }\n\nThis module is sub-interpreter safe, for both ``shared_gil`` (\"legacy\") and\n``per_interpreter_gil`` (\"default\") varieties. Multiple sub-interpreters could each call this same\nfunction concurrently from different threads. This is safe because each sub-interpreter's GIL\nprotects it's own Python objects from concurrent access.\n\nHowever, the module is no longer free-threading safe, for the same reason as\nbefore, because the calculation is not synchronized. We can synchronize it\nusing a Python critical section. This will do nothing if not in free-threaded\nPython. You can have it lock one or two Python objects. You cannot nest it.\n\n.. warning::\n\n   When using a ``py::scoped_critical_section``, make sure it is not nested and\n   that no other synchronization primitives (such as a ``std::mutex``) are\n   held, which could lead to deadlocks. In 3.13, taking the same lock causes it\n   to release then reacquire, which means you can't use it to, for example, read\n   and write to a dictionary, because the dictionary uses a critical section\n   internally in CPython. Use a ``std::mutex`` instead if you need this on\n   Python 3.13. In 3.14, taking a lock on a locked object no longer releases\n   and relocks as an optimization, which also fixes this case.\n\n.. code-block:: cpp\n    :emphasize-lines: 1,4,8\n\n    #include <pybind11/critical_section.h>\n    // ...\n\n    PYBIND11_MODULE(example, m, py::multiple_interpreters::per_interpreter_gil(), py::mod_gil_not_used()) {\n        m.def(\"calc_next\", []() {\n            size_t old;\n            py::dict g = py::globals();\n            py::scoped_critical_section guard(g);\n            if (!g.contains(\"myseed\"))\n                g[\"myseed\"] = 0;\n            old = g[\"myseed\"];\n            g[\"myseed\"] = (old + 1) * 10;\n            return old;\n        });\n    }\n\nThe module is now both sub-interpreter safe and free-threading safe.\n\nBinding sequence data types, iterators, the slicing protocol, etc.\n==================================================================\n\nPlease refer to the supplemental example for details.\n\n.. seealso::\n\n    The file :file:`tests/test_sequences_and_iterators.cpp` contains a\n    complete example that shows how to bind a sequence data type, including\n    length queries (``__len__``), iterators (``__iter__``), the slicing\n    protocol and other kinds of useful operations.\n\n\nPartitioning code over multiple extension modules\n=================================================\n\nIt's straightforward to split binding code over multiple extension modules,\nwhile referencing types that are declared elsewhere. Everything \"just\" works\nwithout any special precautions. One exception to this rule occurs when\nextending a type declared in another extension module. Recall the basic example\nfrom Section :ref:`inheritance`.\n\n.. code-block:: cpp\n\n    py::class_<Pet> pet(m, \"Pet\");\n    pet.def(py::init<const std::string &>())\n       .def_readwrite(\"name\", &Pet::name);\n\n    py::class_<Dog>(m, \"Dog\", pet /* <- specify parent */)\n        .def(py::init<const std::string &>())\n        .def(\"bark\", &Dog::bark);\n\nSuppose now that ``Pet`` bindings are defined in a module named ``basic``,\nwhereas the ``Dog`` bindings are defined somewhere else. The challenge is of\ncourse that the variable ``pet`` is not available anymore though it is needed\nto indicate the inheritance relationship to the constructor of ``py::class_<Dog>``.\nHowever, it can be acquired as follows:\n\n.. code-block:: cpp\n\n    py::object pet = (py::object) py::module_::import(\"basic\").attr(\"Pet\");\n\n    py::class_<Dog>(m, \"Dog\", pet)\n        .def(py::init<const std::string &>())\n        .def(\"bark\", &Dog::bark);\n\nAlternatively, you can specify the base class as a template parameter option to\n``py::class_``, which performs an automated lookup of the corresponding Python\ntype. Like the above code, however, this also requires invoking the ``import``\nfunction once to ensure that the pybind11 binding code of the module ``basic``\nhas been executed:\n\n.. code-block:: cpp\n\n    py::module_::import(\"basic\");\n\n    py::class_<Dog, Pet>(m, \"Dog\")\n        .def(py::init<const std::string &>())\n        .def(\"bark\", &Dog::bark);\n\nNaturally, both methods will fail when there are cyclic dependencies.\n\nNote that pybind11 code compiled with hidden-by-default symbol visibility (e.g.\nvia the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is\nrequired for proper pybind11 functionality, can interfere with the ability to\naccess types defined in another extension module.  Working around this requires\nmanually exporting types that are accessed by multiple extension modules;\npybind11 provides a macro to do just this:\n\n.. code-block:: cpp\n\n    class PYBIND11_EXPORT Dog : public Animal {\n        ...\n    };\n\nNote also that it is possible (although would rarely be required) to share arbitrary\nC++ objects between extension modules at runtime. Internal library data is shared\nbetween modules using capsule machinery [#f6]_ which can be also utilized for\nstoring, modifying and accessing user-defined data. Note that an extension module\nwill \"see\" other extensions' data if and only if they were built with the same\npybind11 version. Consider the following example:\n\n.. code-block:: cpp\n\n    auto data = reinterpret_cast<MyData *>(py::get_shared_data(\"mydata\"));\n    if (!data)\n        data = static_cast<MyData *>(py::set_shared_data(\"mydata\", new MyData(42)));\n\nIf the above snippet was used in several separately compiled extension modules,\nthe first one to be imported would create a ``MyData`` instance and associate\na ``\"mydata\"`` key with a pointer to it. Extensions that are imported later\nwould be then able to access the data behind the same pointer.\n\n.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules\n\nModule Destructors\n==================\n\npybind11 does not provide an explicit mechanism to invoke cleanup code at\nmodule destruction time. In rare cases where such functionality is required, it\nis possible to emulate it using Python capsules or weak references with a\ndestruction callback.\n\n.. code-block:: cpp\n\n    auto cleanup_callback = []() {\n        // perform cleanup here -- this function is called with the GIL held\n    };\n\n    m.add_object(\"_cleanup\", py::capsule(cleanup_callback));\n\nThis approach has the potential downside that instances of classes exposed\nwithin the module may still be alive when the cleanup callback is invoked\n(whether this is acceptable will generally depend on the application).\n\nAlternatively, the capsule may also be stashed within a type object, which\nensures that it not called before all instances of that type have been\ncollected:\n\n.. code-block:: cpp\n\n    auto cleanup_callback = []() { /* ... */ };\n    m.attr(\"BaseClass\").attr(\"_cleanup\") = py::capsule(cleanup_callback);\n\nBoth approaches also expose a potentially dangerous ``_cleanup`` attribute in\nPython, which may be undesirable from an API standpoint (a premature explicit\ncall from Python might lead to undefined behavior). Yet another approach that\navoids this issue involves weak reference with a cleanup callback:\n\n.. code-block:: cpp\n\n    // Register a callback function that is invoked when the BaseClass object is collected\n    py::cpp_function cleanup_callback(\n        [](py::handle weakref) {\n            // perform cleanup here -- this function is called with the GIL held\n\n            weakref.dec_ref(); // release weak reference\n        }\n    );\n\n    // Create a weak reference with a cleanup callback and initially leak it\n    (void) py::weakref(m.attr(\"BaseClass\"), cleanup_callback).release();\n\n.. note::\n\n    PyPy does not garbage collect objects when the interpreter exits. An alternative\n    approach (which also works on CPython) is to use the :py:mod:`atexit` module [#f7]_,\n    for example:\n\n    .. code-block:: cpp\n\n        auto atexit = py::module_::import(\"atexit\");\n        atexit.attr(\"register\")(py::cpp_function([]() {\n            // perform cleanup here -- this function is called with the GIL held\n        }));\n\n    .. [#f7] https://docs.python.org/3/library/atexit.html\n\n\nGenerating documentation using Sphinx\n=====================================\n\nSphinx [#f4]_ has the ability to inspect the signatures and documentation\nstrings in pybind11-based extension modules to automatically generate beautiful\ndocumentation in a variety formats. The python_example repository [#f5]_ contains a\nsimple example repository which uses this approach.\n\nThere are two potential gotchas when using this approach: first, make sure that\nthe resulting strings do not contain any :kbd:`TAB` characters, which break the\ndocstring parsing routines. You may want to use C++11 raw string literals,\nwhich are convenient for multi-line comments. Conveniently, any excess\nindentation will be automatically be removed by Sphinx. However, for this to\nwork, it is important that all lines are indented consistently, i.e.:\n\n.. code-block:: cpp\n\n    // ok\n    m.def(\"foo\", &foo, R\"mydelimiter(\n        The foo function\n\n        Parameters\n        ----------\n    )mydelimiter\");\n\n    // *not ok*\n    m.def(\"foo\", &foo, R\"mydelimiter(The foo function\n\n        Parameters\n        ----------\n    )mydelimiter\");\n\nBy default, pybind11 automatically generates and prepends a signature to the docstring of a function\nregistered with ``module_::def()`` and ``class_::def()``. Sometimes this\nbehavior is not desirable, because you want to provide your own signature or remove\nthe docstring completely to exclude the function from the Sphinx documentation.\nThe class ``options`` allows you to selectively suppress auto-generated signatures:\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m) {\n        py::options options;\n        options.disable_function_signatures();\n\n        m.def(\"add\", [](int a, int b) { return a + b; }, \"A function which adds two numbers\");\n    }\n\npybind11 also appends all members of an enum to the resulting enum docstring.\nThis default behavior can be disabled by using the ``disable_enum_members_docstring()``\nfunction of the ``options`` class.\n\nWith ``disable_user_defined_docstrings()`` all user defined docstrings of\n``module_::def()``, ``class_::def()`` and ``enum_()`` are disabled, but the\nfunction signatures and enum members are included in the docstring, unless they\nare disabled separately.\n\nNote that changes to the settings affect only function bindings created during the\nlifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,\nthe default settings are restored to prevent unwanted side effects.\n\n.. [#f4] http://www.sphinx-doc.org\n.. [#f5] http://github.com/pybind/python_example\n\n.. _avoiding-cpp-types-in-docstrings:\n\nAvoiding C++ types in docstrings\n================================\n\nDocstrings are generated at the time of the declaration, e.g. when ``.def(...)`` is called.\nAt this point parameter and return types should be known to pybind11.\nIf a custom type is not exposed yet through a ``py::class_`` constructor or a custom type caster,\nits C++ type name will be used instead to generate the signature in the docstring:\n\n.. code-block:: text\n\n     |  __init__(...)\n     |      __init__(self: example.Foo, arg0: ns::Bar) -> None\n                                              ^^^^^^^\n\n\nThis limitation can be circumvented by ensuring that C++ classes are registered with pybind11\nbefore they are used as a parameter or return type of a function:\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m) {\n\n        auto pyFoo = py::class_<ns::Foo>(m, \"Foo\");\n        auto pyBar = py::class_<ns::Bar>(m, \"Bar\");\n\n        pyFoo.def(py::init<const ns::Bar&>());\n        pyBar.def(py::init<const ns::Foo&>());\n    }\n\nSetting inner type hints in docstrings\n======================================\n\nWhen you use pybind11 wrappers for ``list``, ``dict``, and other generic python\ntypes, the docstring will just display the generic type. You can convey the\ninner types in the docstring by using a special 'typed' version of the generic\ntype.\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m) {\n        m.def(\"pass_list_of_str\", [](py::typing::List<py::str> arg) {\n            // arg can be used just like py::list\n        ));\n    }\n\nThe resulting docstring will be ``pass_list_of_str(arg0: list[str]) -> None``.\n\nThe following special types are available in ``pybind11/typing.h``:\n\n* ``py::Tuple<Args...>``\n* ``py::Dict<K, V>``\n* ``py::List<V>``\n* ``py::Set<V>``\n* ``py::Callable<Signature>``\n\n.. warning:: Just like in python, these are merely hints. They don't actually\n             enforce the types of their contents at runtime or compile time.\n"
  },
  {
    "path": "docs/advanced/pycpp/index.rst",
    "content": "Python C++ interface\n####################\n\npybind11 exposes Python types and functions using thin C++ wrappers, which\nmakes it possible to conveniently call Python code from C++ without resorting\nto Python's C API.\n\n.. toctree::\n   :maxdepth: 2\n\n   object\n   numpy\n   utilities\n"
  },
  {
    "path": "docs/advanced/pycpp/numpy.rst",
    "content": ".. _numpy:\n\nNumPy\n#####\n\nBuffer protocol\n===============\n\nPython supports an extremely general and convenient approach for exchanging\ndata between plugin libraries. Types can expose a buffer view [#f2]_, which\nprovides fast direct access to the raw internal data representation. Suppose we\nwant to bind the following simplistic Matrix class:\n\n.. code-block:: cpp\n\n    class Matrix {\n    public:\n        Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {\n            m_data = new float[rows*cols];\n        }\n        float *data() { return m_data; }\n        size_t rows() const { return m_rows; }\n        size_t cols() const { return m_cols; }\n    private:\n        size_t m_rows, m_cols;\n        float *m_data;\n    };\n\nThe following binding code exposes the ``Matrix`` contents as a buffer object,\nmaking it possible to cast Matrices into NumPy arrays. It is even possible to\ncompletely avoid copy operations with Python expressions like\n``np.array(matrix_instance, copy = False)``.\n\n.. code-block:: cpp\n\n    py::class_<Matrix>(m, \"Matrix\", py::buffer_protocol())\n       .def_buffer([](Matrix &m) -> py::buffer_info {\n            return py::buffer_info(\n                m.data(),                               /* Pointer to buffer */\n                sizeof(float),                          /* Size of one scalar */\n                py::format_descriptor<float>::format(), /* Python struct-style format descriptor */\n                2,                                      /* Number of dimensions */\n                { m.rows(), m.cols() },                 /* Buffer dimensions */\n                { sizeof(float) * m.cols(),             /* Strides (in bytes) for each index */\n                  sizeof(float) }\n            );\n        });\n\nSupporting the buffer protocol in a new type involves specifying the special\n``py::buffer_protocol()`` tag in the ``py::class_`` constructor and calling the\n``def_buffer()`` method with a lambda function that creates a\n``py::buffer_info`` description record on demand describing a given matrix\ninstance. The contents of ``py::buffer_info`` mirror the Python buffer protocol\nspecification.\n\n.. code-block:: cpp\n\n    struct buffer_info {\n        void *ptr;\n        py::ssize_t itemsize;\n        std::string format;\n        py::ssize_t ndim;\n        std::vector<py::ssize_t> shape;\n        std::vector<py::ssize_t> strides;\n    };\n\nTo create a C++ function that can take a Python buffer object as an argument,\nsimply use the type ``py::buffer`` as one of its arguments. Buffers can exist\nin a great variety of configurations, hence some safety checks are usually\nnecessary in the function body. Below, you can see a basic example on how to\ndefine a custom constructor for the Eigen double precision matrix\n(``Eigen::MatrixXd``) type, which supports initialization from compatible\nbuffer objects (e.g. a NumPy matrix).\n\n.. code-block:: cpp\n\n    /* Bind MatrixXd (or some other Eigen type) to Python */\n    typedef Eigen::MatrixXd Matrix;\n\n    typedef Matrix::Scalar Scalar;\n    constexpr bool rowMajor = Matrix::Flags & Eigen::RowMajorBit;\n\n    py::class_<Matrix>(m, \"Matrix\", py::buffer_protocol())\n        .def(py::init([](py::buffer b) {\n            typedef Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic> Strides;\n\n            /* Request a buffer descriptor from Python */\n            py::buffer_info info = b.request();\n\n            /* Some basic validation checks ... */\n            if (!info.item_type_is_equivalent_to<Scalar>())\n                throw std::runtime_error(\"Incompatible format: expected a double array!\");\n\n            if (info.ndim != 2)\n                throw std::runtime_error(\"Incompatible buffer dimension!\");\n\n            auto strides = Strides(\n                info.strides[rowMajor ? 0 : 1] / (py::ssize_t)sizeof(Scalar),\n                info.strides[rowMajor ? 1 : 0] / (py::ssize_t)sizeof(Scalar));\n\n            auto map = Eigen::Map<Matrix, 0, Strides>(\n                static_cast<Scalar *>(info.ptr), info.shape[0], info.shape[1], strides);\n\n            return Matrix(map);\n        }));\n\nFor reference, the ``def_buffer()`` call for this Eigen data type should look\nas follows:\n\n.. code-block:: cpp\n\n    .def_buffer([](Matrix &m) -> py::buffer_info {\n        return py::buffer_info(\n            m.data(),                                /* Pointer to buffer */\n            sizeof(Scalar),                          /* Size of one scalar */\n            py::format_descriptor<Scalar>::format(), /* Python struct-style format descriptor */\n            2,                                       /* Number of dimensions */\n            { m.rows(), m.cols() },                  /* Buffer dimensions */\n            { sizeof(Scalar) * (rowMajor ? m.cols() : 1),\n              sizeof(Scalar) * (rowMajor ? 1 : m.rows()) }\n                                                     /* Strides (in bytes) for each index */\n        );\n     })\n\nFor a much easier approach of binding Eigen types (although with some\nlimitations), refer to the section on :doc:`/advanced/cast/eigen`.\n\n.. seealso::\n\n    The file :file:`tests/test_buffers.cpp` contains a complete example\n    that demonstrates using the buffer protocol with pybind11 in more detail.\n\n.. [#f2] http://docs.python.org/3/c-api/buffer.html\n\nArrays\n======\n\nBy exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can\nrestrict the function so that it only accepts NumPy arrays (rather than any\ntype of Python object satisfying the buffer protocol).\n\nIn many situations, we want to define a function which only accepts a NumPy\narray of a certain data type. This is possible via the ``py::array_t<T>``\ntemplate. For instance, the following function requires the argument to be a\nNumPy array containing double precision values.\n\n.. code-block:: cpp\n\n    void f(py::array_t<double> array);\n\nWhen it is invoked with a different type (e.g. an integer or a list of\nintegers), the binding code will attempt to cast the input into a NumPy array\nof the requested type. This feature requires the :file:`pybind11/numpy.h`\nheader to be included. Note that :file:`pybind11/numpy.h` does not depend on\nthe NumPy headers, and thus can be used without declaring a build-time\ndependency on NumPy; NumPy>=1.7.0 is a runtime dependency.\n\nData in NumPy arrays is not guaranteed to packed in a dense manner;\nfurthermore, entries can be separated by arbitrary column and row strides.\nSometimes, it can be useful to require a function to only accept dense arrays\nusing either the C (row-major) or Fortran (column-major) ordering. This can be\naccomplished via a second template argument with values ``py::array::c_style``\nor ``py::array::f_style``.\n\n.. code-block:: cpp\n\n    void f(py::array_t<double, py::array::c_style | py::array::forcecast> array);\n\nThe ``py::array::forcecast`` argument is the default value of the second\ntemplate parameter, and it ensures that non-conforming arguments are converted\ninto an array satisfying the specified requirements instead of trying the next\nfunction overload.\n\nThere are several methods on arrays; the methods listed below under references\nwork, as well as the following functions based on the NumPy API:\n\n- ``.dtype()`` returns the type of the contained values.\n\n- ``.strides()`` returns a pointer to the strides of the array (optionally pass\n  an integer axis to get a number).\n\n- ``.flags()`` returns the flag settings. ``.writable()`` and ``.owndata()``\n  are directly available.\n\n- ``.offset_at()`` returns the offset (optionally pass indices).\n\n- ``.squeeze()`` returns a view with length-1 axes removed.\n\n- ``.view(dtype)`` returns a view of the array with a different dtype.\n\n- ``.reshape({i, j, ...})`` returns a view of the array with a different shape.\n  ``.resize({...})`` is also available.\n\n- ``.index_at(i, j, ...)`` gets the count from the beginning to a given index.\n\n\nThere are also several methods for getting references (described below).\n\nStructured types\n================\n\nIn order for ``py::array_t`` to work with structured (record) types, we first\nneed to register the memory layout of the type. This can be done via\n``PYBIND11_NUMPY_DTYPE`` macro, called in the plugin definition code, which\nexpects the type followed by field names:\n\n.. code-block:: cpp\n\n    struct A {\n        int x;\n        double y;\n    };\n\n    struct B {\n        int z;\n        A a;\n    };\n\n    // ...\n    PYBIND11_MODULE(test, m, py::mod_gil_not_used()) {\n        // ...\n\n        PYBIND11_NUMPY_DTYPE(A, x, y);\n        PYBIND11_NUMPY_DTYPE(B, z, a);\n        /* now both A and B can be used as template arguments to py::array_t */\n    }\n\nThe structure should consist of fundamental arithmetic types, ``std::complex``,\npreviously registered substructures, and arrays of any of the above. Both C++\narrays and ``std::array`` are supported. While there is a static assertion to\nprevent many types of unsupported structures, it is still the user's\nresponsibility to use only \"plain\" structures that can be safely manipulated as\nraw memory without violating invariants.\n\nScalar types\n============\n\nIn some cases we may want to accept or return NumPy scalar values such as\n``np.float32`` or ``np.float64``. We hope to be able to handle single-precision\nand double-precision on the C-side. However, both are bound to Python's\ndouble-precision builtin float by default, so they cannot be processed separately.\nWe used the ``py::buffer`` trick to implement the previous approach, which\nwill cause the readability of the code to drop significantly.\n\nLuckily, there's a helper type for this occasion - ``py::numpy_scalar``:\n\n.. code-block:: cpp\n\n    m.def(\"add\", [](py::numpy_scalar<float> a, py::numpy_scalar<float> b) {\n        return py::make_scalar(a + b);\n    });\n    m.def(\"add\", [](py::numpy_scalar<double> a, py::numpy_scalar<double> b) {\n        return py::make_scalar(a + b);\n    });\n\nThis type is trivially convertible to and from the type it wraps; currently\nsupported scalar types are NumPy arithmetic types: ``bool_``, ``int8``,\n``int16``, ``int32``, ``int64``, ``uint8``, ``uint16``, ``uint32``,\n``uint64``, ``float32``, ``float64``, ``complex64``, ``complex128``, all of\nthem mapping to respective C++ counterparts.\n\n.. note::\n\n    ``py::numpy_scalar<T>`` strictly matches NumPy scalar types. For example,\n    ``py::numpy_scalar<int64_t>`` will accept ``np.int64(123)``,\n    but **not** a regular Python ``int`` like ``123``.\n\n.. note::\n\n    Native C types are mapped to NumPy types in a platform specific way: for\n    instance, ``char`` may be mapped to either ``np.int8`` or ``np.uint8``\n    and ``long`` may use 4 or 8 bytes depending on the platform. Unless you\n    clearly understand the difference and your needs, please use ``<cstdint>``.\n\nVectorizing functions\n=====================\n\nSuppose we want to bind a function with the following signature to Python so\nthat it can process arbitrary NumPy array arguments (vectors, matrices, general\nN-D arrays) in addition to its normal arguments:\n\n.. code-block:: cpp\n\n    double my_func(int x, float y, double z);\n\nAfter including the ``pybind11/numpy.h`` header, this is extremely simple:\n\n.. code-block:: cpp\n\n    m.def(\"vectorized_func\", py::vectorize(my_func));\n\nInvoking the function like below causes 4 calls to be made to ``my_func`` with\neach of the array elements. The significant advantage of this compared to\nsolutions like ``numpy.vectorize()`` is that the loop over the elements runs\nentirely on the C++ side and can be crunched down into a tight, optimized loop\nby the compiler. The result is returned as a NumPy array of type\n``numpy.dtype.float64``.\n\n.. code-block:: pycon\n\n    >>> x = np.array([[1, 3], [5, 7]])\n    >>> y = np.array([[2, 4], [6, 8]])\n    >>> z = 3\n    >>> result = vectorized_func(x, y, z)\n\nThe scalar argument ``z`` is transparently replicated 4 times.  The input\narrays ``x`` and ``y`` are automatically converted into the right types (they\nare of type  ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and\n``numpy.dtype.float32``, respectively).\n\n.. note::\n\n    Only arithmetic, complex, and POD types passed by value or by ``const &``\n    reference are vectorized; all other arguments are passed through as-is.\n    Functions taking rvalue reference arguments cannot be vectorized.\n\nIn cases where the computation is too complicated to be reduced to\n``vectorize``, it will be necessary to create and access the buffer contents\nmanually. The following snippet contains a complete example that shows how this\nworks (the code is somewhat contrived, since it could have been done more\nsimply using ``vectorize``).\n\n.. code-block:: cpp\n\n    #include <pybind11/pybind11.h>\n    #include <pybind11/numpy.h>\n\n    namespace py = pybind11;\n\n    py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {\n        py::buffer_info buf1 = input1.request(), buf2 = input2.request();\n\n        if (buf1.ndim != 1 || buf2.ndim != 1)\n            throw std::runtime_error(\"Number of dimensions must be one\");\n\n        if (buf1.size != buf2.size)\n            throw std::runtime_error(\"Input shapes must match\");\n\n        /* No pointer is passed, so NumPy will allocate the buffer */\n        auto result = py::array_t<double>(buf1.size);\n\n        py::buffer_info buf3 = result.request();\n\n        double *ptr1 = static_cast<double *>(buf1.ptr);\n        double *ptr2 = static_cast<double *>(buf2.ptr);\n        double *ptr3 = static_cast<double *>(buf3.ptr);\n\n        for (size_t idx = 0; idx < buf1.shape[0]; idx++)\n            ptr3[idx] = ptr1[idx] + ptr2[idx];\n\n        return result;\n    }\n\n    PYBIND11_MODULE(test, m, py::mod_gil_not_used()) {\n        m.def(\"add_arrays\", &add_arrays, \"Add two NumPy arrays\");\n    }\n\n.. seealso::\n\n    The file :file:`tests/test_numpy_vectorize.cpp` contains a complete\n    example that demonstrates using :func:`vectorize` in more detail.\n\nDirect access\n=============\n\nFor performance reasons, particularly when dealing with very large arrays, it\nis often desirable to directly access array elements without internal checking\nof dimensions and bounds on every access when indices are known to be already\nvalid.  To avoid such checks, the ``array`` class and ``array_t<T>`` template\nclass offer an unchecked proxy object that can be used for this unchecked\naccess through the ``unchecked<N>`` and ``mutable_unchecked<N>`` methods,\nwhere ``N`` gives the required dimensionality of the array:\n\n.. code-block:: cpp\n\n    m.def(\"sum_3d\", [](py::array_t<double> x) {\n        auto r = x.unchecked<3>(); // x must have ndim = 3; can be non-writeable\n        double sum = 0;\n        for (py::ssize_t i = 0; i < r.shape(0); i++)\n            for (py::ssize_t j = 0; j < r.shape(1); j++)\n                for (py::ssize_t k = 0; k < r.shape(2); k++)\n                    sum += r(i, j, k);\n        return sum;\n    });\n    m.def(\"increment_3d\", [](py::array_t<double> x) {\n        auto r = x.mutable_unchecked<3>(); // Will throw if ndim != 3 or flags.writeable is false\n        for (py::ssize_t i = 0; i < r.shape(0); i++)\n            for (py::ssize_t j = 0; j < r.shape(1); j++)\n                for (py::ssize_t k = 0; k < r.shape(2); k++)\n                    r(i, j, k) += 1.0;\n    }, py::arg().noconvert());\n\nTo obtain the proxy from an ``array`` object, you must specify both the data\ntype and number of dimensions as template arguments, such as ``auto r =\nmyarray.mutable_unchecked<float, 2>()``.\n\nIf the number of dimensions is not known at compile time, you can omit the\ndimensions template parameter (i.e. calling ``arr_t.unchecked()`` or\n``arr.unchecked<T>()``.  This will give you a proxy object that works in the\nsame way, but results in less optimizable code and thus a small efficiency\nloss in tight loops.\n\nNote that the returned proxy object directly references the array's data, and\nonly reads its shape, strides, and writeable flag when constructed.  You must\ntake care to ensure that the referenced array is not destroyed or reshaped for\nthe duration of the returned object, typically by limiting the scope of the\nreturned instance.\n\nThe returned proxy object supports some of the same methods as ``py::array`` so\nthat it can be used as a drop-in replacement for some existing, index-checked\nuses of ``py::array``:\n\n- ``.ndim()`` returns the number of dimensions\n\n- ``.data(1, 2, ...)`` and ``r.mutable_data(1, 2, ...)``` returns a pointer to\n  the ``const T`` or ``T`` data, respectively, at the given indices.  The\n  latter is only available to proxies obtained via ``a.mutable_unchecked()``.\n\n- ``.itemsize()`` returns the size of an item in bytes, i.e. ``sizeof(T)``.\n\n- ``.shape(n)`` returns the size of dimension ``n``\n\n- ``.size()`` returns the total number of elements (i.e. the product of the shapes).\n\n- ``.nbytes()`` returns the number of bytes used by the referenced elements\n  (i.e. ``itemsize()`` times ``size()``).\n\n.. seealso::\n\n    The file :file:`tests/test_numpy_array.cpp` contains additional examples\n    demonstrating the use of this feature.\n\nEllipsis\n========\n\nPython provides a convenient ``...`` ellipsis notation that is often used to\nslice multidimensional arrays. For instance, the following snippet extracts the\nmiddle dimensions of a tensor with the first and last index set to zero.\n\n.. code-block:: python\n\n   a = ...  # a NumPy array\n   b = a[0, ..., 0]\n\nThe function ``py::ellipsis()`` function can be used to perform the same\noperation on the C++ side:\n\n.. code-block:: cpp\n\n   py::array a = /* A NumPy array */;\n   py::array b = a[py::make_tuple(0, py::ellipsis(), 0)];\n\n\nMemory view\n===========\n\nFor a case when we simply want to provide a direct accessor to C/C++ buffer\nwithout a concrete class object, we can return a ``memoryview`` object. Suppose\nwe wish to expose a ``memoryview`` for 2x4 uint8_t array, we can do the\nfollowing:\n\n.. code-block:: cpp\n\n    const uint8_t buffer[] = {\n        0, 1, 2, 3,\n        4, 5, 6, 7\n    };\n    m.def(\"get_memoryview2d\", []() {\n        return py::memoryview::from_buffer(\n            buffer,                                    // buffer pointer\n            { 2, 4 },                                  // shape (rows, cols)\n            { sizeof(uint8_t) * 4, sizeof(uint8_t) }   // strides in bytes\n        );\n    });\n\nThis approach is meant for providing a ``memoryview`` for a C/C++ buffer not\nmanaged by Python. The user is responsible for managing the lifetime of the\nbuffer. Using a ``memoryview`` created in this way after deleting the buffer in\nC++ side results in undefined behavior.\n\nWe can also use ``memoryview::from_memory`` for a simple 1D contiguous buffer:\n\n.. code-block:: cpp\n\n    m.def(\"get_memoryview1d\", []() {\n        return py::memoryview::from_memory(\n            buffer,               // buffer pointer\n            sizeof(uint8_t) * 8   // buffer size\n        );\n    });\n\n.. versionchanged:: 2.6\n    ``memoryview::from_memory`` added.\n"
  },
  {
    "path": "docs/advanced/pycpp/object.rst",
    "content": "Python types\n############\n\n.. _wrappers:\n\nAvailable wrappers\n==================\n\nAll major Python types are available as thin C++ wrapper classes. These\ncan also be used as function parameters -- see :ref:`python_objects_as_args`.\n\nAvailable types include :class:`handle`, :class:`object`, :class:`bool_`,\n:class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,\n:class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,\n:class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,\n:class:`array`, and :class:`array_t`.\n\n.. warning::\n\n    Be sure to review the :ref:`pytypes_gotchas` before using this heavily in\n    your C++ API.\n\n.. _instantiating_compound_types:\n\nInstantiating compound Python types from C++\n============================================\n\nDictionaries can be initialized in the :class:`dict` constructor:\n\n.. code-block:: cpp\n\n    using namespace pybind11::literals; // to bring in the `_a` literal\n    py::dict d(\"spam\"_a=py::none(), \"eggs\"_a=42);\n\nA tuple of python objects can be instantiated using :func:`py::make_tuple`:\n\n.. code-block:: cpp\n\n    py::tuple tup = py::make_tuple(42, py::none(), \"spam\");\n\nEach element is converted to a supported Python type.\n\nA `simple namespace`_ can be instantiated using\n\n.. code-block:: cpp\n\n    using namespace pybind11::literals;  // to bring in the `_a` literal\n    py::object SimpleNamespace = py::module_::import(\"types\").attr(\"SimpleNamespace\");\n    py::object ns = SimpleNamespace(\"spam\"_a=py::none(), \"eggs\"_a=42);\n\nAttributes on a namespace can be modified with the :func:`py::delattr`,\n:func:`py::getattr`, and :func:`py::setattr` functions. Simple namespaces can\nbe useful as lightweight stand-ins for class instances.\n\n.. _simple namespace: https://docs.python.org/3/library/types.html#types.SimpleNamespace\n\n.. _casting_back_and_forth:\n\nCasting back and forth\n======================\n\nIn this kind of mixed code, it is often necessary to convert arbitrary C++\ntypes to Python, which can be done using :func:`py::cast`:\n\n.. code-block:: cpp\n\n    MyClass *cls = ...;\n    py::object obj = py::cast(cls);\n\nThe reverse direction uses the following syntax:\n\n.. code-block:: cpp\n\n    py::object obj = ...;\n    MyClass *cls = obj.cast<MyClass *>();\n\nWhen conversion fails, both directions throw the exception :class:`cast_error`.\n\n.. _python_libs:\n\nAccessing Python libraries from C++\n===================================\n\nIt is also possible to import objects defined in the Python standard\nlibrary or available in the current Python environment (``sys.path``) and work\nwith these in C++.\n\nThis example obtains a reference to the Python ``Decimal`` class.\n\n.. code-block:: cpp\n\n    // Equivalent to \"from decimal import Decimal\"\n    py::object Decimal = py::module_::import(\"decimal\").attr(\"Decimal\");\n\n.. code-block:: cpp\n\n    // Try to import scipy\n    py::object scipy = py::module_::import(\"scipy\");\n    return scipy.attr(\"__version__\");\n\n\n.. _calling_python_functions:\n\nCalling Python functions\n========================\n\nIt is also possible to call Python classes, functions and methods\nvia ``operator()``.\n\n.. code-block:: cpp\n\n    // Construct a Python object of class Decimal\n    py::object pi = Decimal(\"3.14159\");\n\n.. code-block:: cpp\n\n    // Use Python to make our directories\n    py::object os = py::module_::import(\"os\");\n    py::object makedirs = os.attr(\"makedirs\");\n    makedirs(\"/tmp/path/to/somewhere\");\n\nOne can convert the result obtained from Python to a pure C++ version\nif a ``py::class_`` or type conversion is defined.\n\n.. code-block:: cpp\n\n    py::function f = <...>;\n    py::object result_py = f(1234, \"hello\", some_instance);\n    MyClass &result = result_py.cast<MyClass>();\n\n.. _calling_python_methods:\n\nCalling Python methods\n========================\n\nTo call an object's method, one can again use ``.attr`` to obtain access to the\nPython method.\n\n.. code-block:: cpp\n\n    // Calculate e^π in decimal\n    py::object exp_pi = pi.attr(\"exp\")();\n    py::print(py::str(exp_pi));\n\nIn the example above ``pi.attr(\"exp\")`` is a *bound method*: it will always call\nthe method for that same instance of the class. Alternately one can create an\n*unbound method* via the Python class (instead of instance) and pass the ``self``\nobject explicitly, followed by other arguments.\n\n.. code-block:: cpp\n\n    py::object decimal_exp = Decimal.attr(\"exp\");\n\n    // Compute the e^n for n=0..4\n    for (int n = 0; n < 5; n++) {\n        py::print(decimal_exp(Decimal(n));\n    }\n\nKeyword arguments\n=================\n\nKeyword arguments are also supported. In Python, there is the usual call syntax:\n\n.. code-block:: python\n\n    def f(number, say, to):\n        ...  # function code\n\n\n    f(1234, say=\"hello\", to=some_instance)  # keyword call in Python\n\nIn C++, the same call can be made using:\n\n.. code-block:: cpp\n\n    using namespace pybind11::literals; // to bring in the `_a` literal\n    f(1234, \"say\"_a=\"hello\", \"to\"_a=some_instance); // keyword call in C++\n\nUnpacking arguments\n===================\n\nUnpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with\nother arguments:\n\n.. code-block:: cpp\n\n    // * unpacking\n    py::tuple args = py::make_tuple(1234, \"hello\", some_instance);\n    f(*args);\n\n    // ** unpacking\n    py::dict kwargs = py::dict(\"number\"_a=1234, \"say\"_a=\"hello\", \"to\"_a=some_instance);\n    f(**kwargs);\n\n    // mixed keywords, * and ** unpacking\n    py::tuple args = py::make_tuple(1234);\n    py::dict kwargs = py::dict(\"to\"_a=some_instance);\n    f(*args, \"say\"_a=\"hello\", **kwargs);\n\nGeneralized unpacking according to PEP448_ is also supported:\n\n.. code-block:: cpp\n\n    py::dict kwargs1 = py::dict(\"number\"_a=1234);\n    py::dict kwargs2 = py::dict(\"to\"_a=some_instance);\n    f(**kwargs1, \"say\"_a=\"hello\", **kwargs2);\n\n.. seealso::\n\n    The file :file:`tests/test_pytypes.cpp` contains a complete\n    example that demonstrates passing native Python types in more detail. The\n    file :file:`tests/test_callbacks.cpp` presents a few examples of calling\n    Python functions from C++, including keywords arguments and unpacking.\n\n.. _PEP448: https://www.python.org/dev/peps/pep-0448/\n\n.. _implicit_casting:\n\nImplicit casting\n================\n\nWhen using the C++ interface for Python types, or calling Python functions,\nobjects of type :class:`object` are returned. It is possible to invoke implicit\nconversions to subclasses like :class:`dict`. The same holds for the proxy objects\nreturned by ``operator[]`` or ``obj.attr()``.\nCasting to subtypes improves code readability and allows values to be passed to\nC++ functions that require a specific subtype rather than a generic :class:`object`.\n\n.. code-block:: cpp\n\n    #include <pybind11/numpy.h>\n    using namespace pybind11::literals;\n\n    py::module_ os = py::module_::import(\"os\");\n    py::module_ path = py::module_::import(\"os.path\");  // like 'import os.path as path'\n    py::module_ np = py::module_::import(\"numpy\");  // like 'import numpy as np'\n\n    py::str curdir_abs = path.attr(\"abspath\")(path.attr(\"curdir\"));\n    py::print(py::str(\"Current directory: \") + curdir_abs);\n    py::dict environ = os.attr(\"environ\");\n    py::print(environ[\"HOME\"]);\n    py::array_t<float> arr = np.attr(\"ones\")(3, \"dtype\"_a=\"float32\");\n    py::print(py::repr(arr + py::int_(1)));\n\nThese implicit conversions are available for subclasses of :class:`object`; there\nis no need to call ``obj.cast()`` explicitly as for custom classes, see\n:ref:`casting_back_and_forth`.\n\n.. note::\n    If a trivial conversion via move constructor is not possible, both implicit and\n    explicit casting (calling ``obj.cast()``) will attempt a \"rich\" conversion.\n    For instance, ``py::list env = os.attr(\"environ\");`` will succeed and is\n    equivalent to the Python code ``env = list(os.environ)`` that produces a\n    list of the dict keys.\n\n..  TODO: Adapt text once PR #2349 has landed\n\nHandling exceptions\n===================\n\nPython exceptions from wrapper classes will be thrown as a ``py::error_already_set``.\nSee :ref:`Handling exceptions from Python in C++\n<handling_python_exceptions_cpp>` for more information on handling exceptions\nraised when calling C++ wrapper classes.\n\n.. _pytypes_gotchas:\n\nGotchas\n=======\n\nDefault-Constructed Wrappers\n----------------------------\n\nWhen a wrapper type is default-constructed, it is **not** a valid Python object (i.e. it is not ``py::none()``). It is simply the same as\n``PyObject*`` null pointer. To check for this, use\n``static_cast<bool>(my_wrapper)``.\n\nAssigning py::none() to wrappers\n--------------------------------\n\nYou may be tempted to use types like ``py::str`` and ``py::dict`` in C++\nsignatures (either pure C++, or in bound signatures), and assign them default\nvalues of ``py::none()``. However, in a best case scenario, it will fail fast\nbecause ``None`` is not convertible to that type (e.g. ``py::dict``), or in a\nworse case scenario, it will silently work but corrupt the types you want to\nwork with (e.g. ``py::str(py::none())`` will yield ``\"None\"`` in Python).\n"
  },
  {
    "path": "docs/advanced/pycpp/utilities.rst",
    "content": "Utilities\n#########\n\nUsing Python's print function in C++\n====================================\n\nThe usual way to write output in C++ is using ``std::cout`` while in Python one\nwould use ``print``. Since these methods use different buffers, mixing them can\nlead to output order issues. To resolve this, pybind11 modules can use the\n:func:`py::print` function which writes to Python's ``sys.stdout`` for consistency.\n\nPython's ``print`` function is replicated in the C++ API including optional\nkeyword arguments ``sep``, ``end``, ``file``, ``flush``. Everything works as\nexpected in Python:\n\n.. code-block:: cpp\n\n    py::print(1, 2.0, \"three\"); // 1 2.0 three\n    py::print(1, 2.0, \"three\", \"sep\"_a=\"-\"); // 1-2.0-three\n\n    auto args = py::make_tuple(\"unpacked\", true);\n    py::print(\"->\", *args, \"end\"_a=\"<-\"); // -> unpacked True <-\n\n.. _ostream_redirect:\n\nCapturing standard output from ostream\n======================================\n\nOften, a library will use the streams ``std::cout`` and ``std::cerr`` to print,\nbut this does not play well with Python's standard ``sys.stdout`` and ``sys.stderr``\nredirection. Replacing a library's printing with ``py::print <print>`` may not\nbe feasible. This can be fixed using a guard around the library function that\nredirects output to the corresponding Python streams:\n\n.. code-block:: cpp\n\n    #include <pybind11/iostream.h>\n\n    ...\n\n    // Add a scoped redirect for your noisy code\n    m.def(\"noisy_func\", []() {\n        py::scoped_ostream_redirect stream(\n            std::cout,                               // std::ostream&\n            py::module_::import(\"sys\").attr(\"stdout\") // Python output\n        );\n        call_noisy_func();\n    });\n\n.. warning::\n\n    The implementation in ``pybind11/iostream.h`` is NOT thread safe. Multiple\n    threads writing to a redirected ostream concurrently cause data races\n    and potentially buffer overflows. Therefore it is currently a requirement\n    that all (possibly) concurrent redirected ostream writes are protected by\n    a mutex. #HelpAppreciated: Work on iostream.h thread safety. For more\n    background see the discussions under\n    `PR #2982 <https://github.com/pybind/pybind11/pull/2982>`_ and\n    `PR #2995 <https://github.com/pybind/pybind11/pull/2995>`_.\n\nThis method respects flushes on the output streams and will flush if needed\nwhen the scoped guard is destroyed. This allows the output to be redirected in\nreal time, such as to a Jupyter notebook. The two arguments, the C++ stream and\nthe Python output, are optional, and default to standard output if not given. An\nextra type, ``py::scoped_estream_redirect <scoped_estream_redirect>``, is identical\nexcept for defaulting to ``std::cerr`` and ``sys.stderr``; this can be useful with\n``py::call_guard``, which allows multiple items, but uses the default constructor:\n\n.. code-block:: cpp\n\n    // Alternative: Call single function using call guard\n    m.def(\"noisy_func\", &call_noisy_function,\n          py::call_guard<py::scoped_ostream_redirect,\n                         py::scoped_estream_redirect>());\n\nThe redirection can also be done in Python with the addition of a context\nmanager, using the ``py::add_ostream_redirect() <add_ostream_redirect>`` function:\n\n.. code-block:: cpp\n\n    py::add_ostream_redirect(m, \"ostream_redirect\");\n\nThe name in Python defaults to ``ostream_redirect`` if no name is passed.  This\ncreates the following context manager in Python:\n\n.. code-block:: python\n\n    with ostream_redirect(stdout=True, stderr=True):\n        noisy_function()\n\nIt defaults to redirecting both streams, though you can use the keyword\narguments to disable one of the streams if needed.\n\n.. note::\n\n    The above methods will not redirect C-level output to file descriptors, such\n    as ``fprintf``. For those cases, you'll need to redirect the file\n    descriptors either directly in C or with Python's ``os.dup2`` function\n    in an operating-system dependent way.\n\n.. _eval:\n\nEvaluating Python expressions from strings and files\n====================================================\n\npybind11 provides the ``eval``, ``exec`` and ``eval_file`` functions to evaluate\nPython expressions and statements. The following example illustrates how they\ncan be used.\n\n.. code-block:: cpp\n\n    // At beginning of file\n    #include <pybind11/eval.h>\n\n    ...\n\n    // Evaluate in scope of main module\n    py::object scope = py::module_::import(\"__main__\").attr(\"__dict__\");\n\n    // Evaluate an isolated expression\n    int result = py::eval(\"my_variable + 10\", scope).cast<int>();\n\n    // Evaluate a sequence of statements\n    py::exec(\n        \"print('Hello')\\n\"\n        \"print('world!');\",\n        scope);\n\n    // Evaluate the statements in an separate Python file on disk\n    py::eval_file(\"script.py\", scope);\n\nC++11 raw string literals are also supported and quite handy for this purpose.\nThe only requirement is that the first statement must be on a new line following\nthe raw string delimiter ``R\"(``, ensuring all lines have common leading indent:\n\n.. code-block:: cpp\n\n    py::exec(R\"(\n        x = get_answer()\n        if x == 42:\n            print('Hello World!')\n        else:\n            print('Bye!')\n        )\", scope\n    );\n\n.. note::\n\n    `eval` and `eval_file` accept a template parameter that describes how the\n    string/file should be interpreted. Possible choices include ``eval_expr``\n    (isolated expression), ``eval_single_statement`` (a single statement, return\n    value is always ``none``), and ``eval_statements`` (sequence of statements,\n    return value is always ``none``). `eval` defaults to  ``eval_expr``,\n    `eval_file` defaults to ``eval_statements`` and `exec` is just a shortcut\n    for ``eval<eval_statements>``.\n"
  },
  {
    "path": "docs/advanced/smart_ptrs.rst",
    "content": ".. _py_class_holder:\n\nSmart pointers & ``py::class_``\n###############################\n\nThe binding generator for classes, ``py::class_``, can be passed a template\ntype that denotes a special *holder* type that is used to manage references to\nthe object. If no such holder type template argument is given, the default for\na type ``T`` is ``std::unique_ptr<T>``.\n\n.. note::\n\n    A ``py::class_`` for a given C++ type ``T`` — and all its derived types —\n    can only use a single holder type.\n\n\n.. _smart_holder:\n\n``py::smart_holder``\n====================\n\nStarting with pybind11v3, ``py::smart_holder`` is built into pybind11. It is\nthe recommended ``py::class_`` holder for most situations. However, for\nbackward compatibility it is **not** the default holder, and there are no\nplans to make it the default holder in the future.\n\nIt is extremely easy to use the safer and more versatile ``py::smart_holder``:\nsimply add ``py::smart_holder`` to ``py::class_``:\n\n* ``py::class_<T>`` to\n\n* ``py::class_<T, py::smart_holder>``.\n\n.. note::\n\n    A shorthand, ``py::classh<T>``, is provided for\n    ``py::class_<T, py::smart_holder>``. The ``h`` in ``py::classh`` stands\n    for **smart_holder** but is shortened for brevity, ensuring it has the\n    same number of characters as ``py::class_``. This design choice facilitates\n    easy experimentation with ``py::smart_holder`` without introducing\n    distracting whitespace noise in diffs.\n\nThe ``py::smart_holder`` functionality includes the following:\n\n* Support for **two-way** Python/C++ conversions for both\n  ``std::unique_ptr<T>`` and ``std::shared_ptr<T>`` **simultaneously**.\n\n* Passing a Python object back to C++ via ``std::unique_ptr<T>``, safely\n  **disowning** the Python object.\n\n* Safely passing \"trampoline\" objects (objects with C++ virtual function\n  overrides implemented in Python, see :ref:`overriding_virtuals`) via\n  ``std::unique_ptr<T>`` or ``std::shared_ptr<T>`` back to C++:\n  associated Python objects are automatically kept alive for the lifetime\n  of the smart-pointer.\n\n* Full support for ``std::enable_shared_from_this`` (`cppreference\n  <http://en.cppreference.com/w/cpp/memory/enable_shared_from_this>`_).\n\n\n``std::unique_ptr``\n===================\n\nThis is the default ``py::class_`` holder and works as expected in\nmost situations. However, handling base-and-derived classes involves a\n``reinterpret_cast``, which is, strictly speaking, undefined behavior.\nAlso note that the ``std::unique_ptr`` holder only supports passing a\n``std::unique_ptr`` from C++ to Python, but not the other way around.\nFor example, the following code works as expected with ``py::class_<Example>``:\n\n.. code-block:: cpp\n\n    std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }\n\n.. code-block:: cpp\n\n    m.def(\"create_example\", &create_example);\n\nHowever, this will fail with ``py::class_<Example>`` (but works with\n``py::class_<Example, py::smart_holder>``):\n\n.. code-block:: cpp\n\n    void do_something_with_example(std::unique_ptr<Example> ex) { ... }\n\n.. note::\n\n    The ``reinterpret_cast`` mentioned above is `here\n    <https://github.com/pybind/pybind11/blob/30eb39ed79d1e2eeff15219ac00773034300a5e6/include/pybind11/cast.h#L235>`_.\n    For completeness: The same cast is also applied to ``py::smart_holder``,\n    but that is safe, because ``py::smart_holder`` is not templated.\n\n\n``std::shared_ptr``\n===================\n\nIt is possible to use ``std::shared_ptr`` as the holder, for example:\n\n.. code-block:: cpp\n\n    py::class_<Example, std::shared_ptr<Example> /* <- holder type */>(m, \"Example\");\n\nCompared to using ``py::class_<Example, py::smart_holder>``, there are two noteworthy disadvantages:\n\n* Because a ``py::class_`` for a given C++ type ``T`` can only use a\n  single holder type, ``std::unique_ptr<T>`` cannot even be passed from C++\n  to Python. This will become apparent only at runtime, often through a\n  segmentation fault.\n\n* Similar to the ``std::unique_ptr`` holder, the handling of base-and-derived\n  classes involves a ``reinterpret_cast`` that has strictly speaking undefined\n  behavior, although it works as expected in most situations.\n\n\n.. _smart_pointers:\n\nCustom smart pointers\n=====================\n\nFor custom smart pointers (e.g. ``c10::intrusive_ptr`` in pytorch), transparent\nconversions can be enabled using a macro invocation similar to the following.\nIt must be declared at the top namespace level before any binding code:\n\n.. code-block:: cpp\n\n    PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>)\n\nThe first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a\nplaceholder name that is used as a template parameter of the second argument.\nThus, feel free to use any identifier, but use it consistently on both sides;\nalso, don't use the name of a type that already exists in your codebase.\n\nThe macro also accepts a third optional boolean parameter that is set to false\nby default. Specify\n\n.. code-block:: cpp\n\n    PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>, true)\n\nif ``SmartPtr<T>`` can always be initialized from a ``T*`` pointer without the\nrisk of inconsistencies (such as multiple independent ``SmartPtr`` instances\nbelieving that they are the sole owner of the ``T*`` pointer). A common\nsituation where ``true`` should be passed is when the ``T`` instances use\n*intrusive* reference counting.\n\nPlease take a look at the :ref:`macro_notes` before using this feature.\n\nBy default, pybind11 assumes that your custom smart pointer has a standard\ninterface, i.e. provides a ``.get()`` member function to access the underlying\nraw pointer. If this is not the case, pybind11's ``holder_helper`` must be\nspecialized:\n\n.. code-block:: cpp\n\n    // Always needed for custom holder types\n    PYBIND11_DECLARE_HOLDER_TYPE(T, SmartPtr<T>)\n\n    // Only needed if the type's `.get()` goes by another name\n    namespace PYBIND11_NAMESPACE { namespace detail {\n        template <typename T>\n        struct holder_helper<SmartPtr<T>> { // <-- specialization\n            static const T *get(const SmartPtr<T> &p) { return p.getPointer(); }\n        };\n    }}\n\nThe above specialization informs pybind11 that the custom ``SmartPtr`` class\nprovides ``.get()`` functionality via ``.getPointer()``.\n\n.. note::\n\n    The two noteworthy disadvantages mentioned under the ``std::shared_ptr``\n    section apply similarly to custom smart pointer holders, but there is no\n    established safe alternative in this case.\n\n.. seealso::\n\n    The file :file:`tests/test_smart_ptr.cpp` contains a complete example\n    that demonstrates how to work with custom reference-counting holder types\n    in more detail.\n"
  },
  {
    "path": "docs/basics.rst",
    "content": ".. _basics:\n\nFirst steps\n###########\n\nThis sections demonstrates the basic features of pybind11. Before getting\nstarted, make sure that development environment is set up to compile the\nincluded set of test cases.\n\n\nCompiling the test cases\n========================\n\nLinux/macOS\n-----------\n\nOn Linux  you'll need to install the **python-dev** or **python3-dev** packages as\nwell as **cmake**. On macOS, the included python version works out of the box,\nbut **cmake** must still be installed.\n\nAfter installing the prerequisites, run\n\n.. code-block:: bash\n\n   mkdir build\n   cd build\n   cmake ..\n   make check -j 4\n\nThe last line will both compile and run the tests.\n\nWindows\n-------\n\nOn Windows, only **Visual Studio 2017** and newer are supported.\n\n.. Note::\n\n    To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag\n    ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When\n    building with Visual Studio 2019, this is not strictly necessary, but still advised.\n\n..  _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017\n\nTo compile and run the tests:\n\n.. code-block:: batch\n\n   mkdir build\n   cd build\n   cmake ..\n   cmake --build . --config Release --target check\n\nThis will create a Visual Studio project, compile and run the target, all from the\ncommand line.\n\n.. Note::\n\n    If all tests fail, make sure that the Python binary and the testcases are compiled\n    for the same processor type and bitness (i.e. either **i386** or **x86_64**). You\n    can specify **x86_64** as the target architecture for the generated Visual Studio\n    project using ``cmake -A x64 ..``.\n\n.. seealso::\n\n    Advanced users who are already familiar with Boost.Python may want to skip\n    the tutorial and look at the test cases in the :file:`tests` directory,\n    which exercise all features of pybind11.\n\nHeader and namespace conventions\n================================\n\nFor brevity, all code examples assume that the following two lines are present:\n\n.. code-block:: cpp\n\n    #include <pybind11/pybind11.h>\n\n    namespace py = pybind11;\n\n.. note::\n\n    ``pybind11/pybind11.h`` includes ``Python.h``, as such it must be the first file\n    included in any source file or header for `the same reasons as Python.h`_.\n\n.. _`the same reasons as Python.h`: https://docs.python.org/3/extending/extending.html#a-simple-example\n\nSome features may require additional headers, but those will be specified as needed.\n\n.. _simple_example:\n\nCreating bindings for a simple function\n=======================================\n\nLet's start by creating Python bindings for an extremely simple function, which\nadds two numbers and returns their result:\n\n.. code-block:: cpp\n\n    int add(int i, int j) {\n        return i + j;\n    }\n\nFor simplicity [#f1]_, we'll put both this function and the binding code into\na file named :file:`example.cpp` with the following contents:\n\n.. code-block:: cpp\n\n    #include <pybind11/pybind11.h>\n\n    namespace py = pybind11;\n\n    int add(int i, int j) {\n        return i + j;\n    }\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        m.doc() = \"pybind11 example plugin\"; // optional module docstring\n\n        m.def(\"add\", &add, \"A function that adds two numbers\");\n    }\n\n.. [#f1] In practice, implementation and binding code will generally be located\n         in separate files.\n\nThe :func:`PYBIND11_MODULE` macro creates a function that will be called when an\n``import`` statement is issued from within Python. The module name (``example``)\nis given as the first macro argument (it should not be in quotes). The second\nargument (``m``) defines a variable of type :class:`py::module_ <module>` which\nis the main interface for creating bindings. The method :func:`module_::def`\ngenerates binding code that exposes the ``add()`` function to Python.\n\n.. note::\n\n    Notice how little code was needed to expose our function to Python: all\n    details regarding the function's parameters and return value were\n    automatically inferred using template metaprogramming. This overall\n    approach and the used syntax are borrowed from Boost.Python, though the\n    underlying implementation is very different.\n\npybind11 is a header-only library, hence it is not necessary to link against\nany special libraries and there are no intermediate (magic) translation steps.\nOn Linux, the above example can be compiled using the following command:\n\n.. code-block:: bash\n\n    $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3 -m pybind11 --extension-suffix)\n\n.. note::\n\n    If you used :ref:`include_as_a_submodule` to get the pybind11 source, then\n    use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of\n    ``$(python3 -m pybind11 --includes)`` in the above compilation, as\n    explained in :ref:`building_manually`.\n\nFor more details on the required compiler flags on Linux and macOS, see\n:ref:`building_manually`. For complete cross-platform compilation instructions,\nrefer to the :ref:`compiling` page.\n\nThe `python_example`_ and `cmake_example`_ repositories are also a good place\nto start. They are both complete project examples with cross-platform build\nsystems. The only difference between the two is that `python_example`_ uses\nPython's ``setuptools`` to build the module, while `cmake_example`_ uses CMake\n(which may be preferable for existing C++ projects).\n\n.. _python_example: https://github.com/pybind/python_example\n.. _cmake_example: https://github.com/pybind/cmake_example\n\nBuilding the above C++ code will produce a binary module file that can be\nimported to Python. Assuming that the compiled module is located in the\ncurrent directory, the following interactive Python session shows how to\nload and execute the example:\n\n.. code-block:: pycon\n\n    $ python\n    Python 3.9.10 (main, Jan 15 2022, 11:48:04)\n    [Clang 13.0.0 (clang-1300.0.29.3)] on darwin\n    Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n    >>> import example\n    >>> example.add(1, 2)\n    3\n    >>>\n\n.. _keyword_args:\n\nKeyword arguments\n=================\n\nWith a simple code modification, it is possible to inform Python about the\nnames of the arguments (\"i\" and \"j\" in this case).\n\n.. code-block:: cpp\n\n    m.def(\"add\", &add, \"A function which adds two numbers\",\n          py::arg(\"i\"), py::arg(\"j\"));\n\n:class:`arg` is one of several special tag classes which can be used to pass\nmetadata into :func:`module_::def`. With this modified binding code, we can now\ncall the function using keyword arguments, which is a more readable alternative\nparticularly for functions taking many parameters:\n\n.. code-block:: pycon\n\n    >>> import example\n    >>> example.add(i=1, j=2)\n    3L\n\nThe keyword names also appear in the function signatures within the documentation.\n\n.. code-block:: pycon\n\n    >>> help(example)\n\n    ....\n\n    FUNCTIONS\n        add(...)\n            Signature : (i: int, j: int) -> int\n\n            A function which adds two numbers\n\nA shorter notation for named arguments is also available:\n\n.. code-block:: cpp\n\n    // regular notation\n    m.def(\"add1\", &add, py::arg(\"i\"), py::arg(\"j\"));\n    // shorthand\n    using namespace pybind11::literals;\n    m.def(\"add2\", &add, \"i\"_a, \"j\"_a);\n\nThe :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.\nNote that the literal operator must first be made visible with the directive\n``using namespace pybind11::literals``. This does not bring in anything else\nfrom the ``pybind11`` namespace except for literals.\n\n.. _default_args:\n\nDefault arguments\n=================\n\nSuppose now that the function to be bound has default arguments, e.g.:\n\n.. code-block:: cpp\n\n    int add(int i = 1, int j = 2) {\n        return i + j;\n    }\n\nUnfortunately, pybind11 cannot automatically extract these parameters, since they\nare not part of the function's type information. However, they are simple to specify\nusing an extension of :class:`arg`:\n\n.. code-block:: cpp\n\n    m.def(\"add\", &add, \"A function which adds two numbers\",\n          py::arg(\"i\") = 1, py::arg(\"j\") = 2);\n\nThe default values also appear within the documentation.\n\n.. code-block:: pycon\n\n    >>> help(example)\n\n    ....\n\n    FUNCTIONS\n        add(...)\n            Signature : (i: int = 1, j: int = 2) -> int\n\n            A function which adds two numbers\n\nThe shorthand notation is also available for default arguments:\n\n.. code-block:: cpp\n\n    // regular notation\n    m.def(\"add1\", &add, py::arg(\"i\") = 1, py::arg(\"j\") = 2);\n    // shorthand\n    m.def(\"add2\", &add, \"i\"_a=1, \"j\"_a=2);\n\nExporting variables\n===================\n\nTo expose a value from C++, use the ``attr`` function to register it in a\nmodule as shown below. Built-in types and general objects (more on that later)\nare automatically converted when assigned as attributes, and can be explicitly\nconverted using the function ``py::cast``.\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        m.attr(\"the_answer\") = 42;\n        py::object world = py::cast(\"World\");\n        m.attr(\"what\") = world;\n    }\n\nThese are then accessible from Python:\n\n.. code-block:: pycon\n\n    >>> import example\n    >>> example.the_answer\n    42\n    >>> example.what\n    'World'\n\n.. _supported_types:\n\nSupported data types\n====================\n\nA large number of data types are supported out of the box and can be used\nseamlessly as functions arguments, return values or with ``py::cast`` in general.\nFor a full overview, see the :doc:`advanced/cast/index` section.\n"
  },
  {
    "path": "docs/benchmark.py",
    "content": "from __future__ import annotations\n\nimport datetime as dt\nimport os\nimport random\n\nnfns = 4  # Functions per class\nnargs = 4  # Arguments per function\n\n\ndef generate_dummy_code_pybind11(nclasses=10):\n    decl = \"\"\n    bindings = \"\"\n\n    for cl in range(nclasses):\n        decl += f\"class cl{cl:03};\\n\"\n    decl += \"\\n\"\n\n    for cl in range(nclasses):\n        decl += f\"class {cl:03} {{\\n\"\n        decl += \"public:\\n\"\n        bindings += f'    py::class_<cl{cl:03}>(m, \"cl{cl:03}\")\\n'\n        for fn in range(nfns):\n            ret = random.randint(0, nclasses - 1)\n            params = [random.randint(0, nclasses - 1) for i in range(nargs)]\n            decl += f\"    cl{ret:03} *fn_{fn:03}(\"\n            decl += \", \".join(f\"cl{p:03} *\" for p in params)\n            decl += \");\\n\"\n            bindings += f'        .def(\"fn_{fn:03}\", &cl{cl:03}::fn_{fn:03})\\n'\n        decl += \"};\\n\\n\"\n        bindings += \"        ;\\n\"\n\n    result = \"#include <pybind11/pybind11.h>\\n\\n\"\n    result += \"namespace py = pybind11;\\n\\n\"\n    result += decl + \"\\n\"\n    result += \"PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\\n\"\n    result += bindings\n    result += \"}\"\n    return result\n\n\ndef generate_dummy_code_boost(nclasses=10):\n    decl = \"\"\n    bindings = \"\"\n\n    for cl in range(nclasses):\n        decl += f\"class cl{cl:03};\\n\"\n    decl += \"\\n\"\n\n    for cl in range(nclasses):\n        decl += f\"class cl{cl:03} {{\\n\"\n        decl += \"public:\\n\"\n        bindings += f'    py::class_<cl{cl:03}>(\"cl{cl:03}\")\\n'\n        for fn in range(nfns):\n            ret = random.randint(0, nclasses - 1)\n            params = [random.randint(0, nclasses - 1) for i in range(nargs)]\n            decl += f\"    cl{ret:03} *fn_{fn:03}(\"\n            decl += \", \".join(f\"cl{p:03} *\" for p in params)\n            decl += \");\\n\"\n            bindings += f'        .def(\"fn_{fn:03}\", &cl{cl:03}::fn_{fn:03}, py::return_value_policy<py::manage_new_object>())\\n'\n        decl += \"};\\n\\n\"\n        bindings += \"        ;\\n\"\n\n    result = \"#include <boost/python.hpp>\\n\\n\"\n    result += \"namespace py = boost::python;\\n\\n\"\n    result += decl + \"\\n\"\n    result += \"BOOST_PYTHON_MODULE(example) {\\n\"\n    result += bindings\n    result += \"}\"\n    return result\n\n\nfor codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]:\n    print(\"{\")\n    for i in range(10):\n        nclasses = 2**i\n        with open(\"test.cpp\", \"w\") as f:\n            f.write(codegen(nclasses))\n        n1 = dt.datetime.now()\n        os.system(\n            \"g++ -Os -shared -rdynamic -undefined dynamic_lookup \"\n            \"-fvisibility=hidden -std=c++14 test.cpp -I include \"\n            \"-I /System/Library/Frameworks/Python.framework/Headers -o test.so\"\n        )\n        n2 = dt.datetime.now()\n        elapsed = (n2 - n1).total_seconds()\n        size = os.stat(\"test.so\").st_size\n        print(f\"   {{{nclasses * nfns}, {elapsed:.6f}, {size}}},\")\n    print(\"}\")\n"
  },
  {
    "path": "docs/benchmark.rst",
    "content": "Benchmark\n=========\n\nThe following is the result of a synthetic benchmark comparing both compilation\ntime and module size of pybind11 against Boost.Python. A detailed report about a\nBoost.Python to pybind11 conversion of a real project is available here: [#f1]_.\n\n.. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf\n\nSetup\n-----\n\nA python script (see the ``docs/benchmark.py`` file) was used to generate a set\nof files with dummy classes whose count increases for each successive benchmark\n(between 1 and 2048 classes in powers of two). Each class has four methods with\na randomly generated signature with a return value and four arguments. (There\nwas no particular reason for this setup other than the desire to generate many\nunique function signatures whose count could be controlled in a simple way.)\n\nHere is an example of the binding code for one class:\n\n.. code-block:: cpp\n\n    ...\n    class cl034 {\n    public:\n        cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *);\n        cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *);\n        cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *);\n        cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *);\n    };\n    ...\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        ...\n        py::class_<cl034>(m, \"cl034\")\n            .def(\"fn_000\", &cl034::fn_000)\n            .def(\"fn_001\", &cl034::fn_001)\n            .def(\"fn_002\", &cl034::fn_002)\n            .def(\"fn_003\", &cl034::fn_003)\n        ...\n    }\n\nThe Boost.Python version looks almost identical except that a return value\npolicy had to be specified as an argument to ``def()``. For both libraries,\ncompilation was done with\n\n.. code-block:: bash\n\n    Apple LLVM version 7.0.2 (clang-700.1.81)\n\nand the following compilation flags\n\n.. code-block:: bash\n\n    g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14\n\nCompilation time\n----------------\n\nThe following log-log plot shows how the compilation time grows for an\nincreasing number of class and function declarations. pybind11 includes many\nfewer headers, which initially leads to shorter compilation times, but the\nperformance is ultimately fairly similar (pybind11 is 19.8 seconds faster for\nthe largest largest file with 2048 classes and a total of 8192 methods -- a\nmodest **1.2x** speedup relative to Boost.Python, which required 116.35\nseconds).\n\n.. only:: not latex\n\n    .. image:: pybind11_vs_boost_python1.svg\n\n.. only:: latex\n\n    .. image:: pybind11_vs_boost_python1.png\n\nModule size\n-----------\n\nDifferences between the two libraries become much more pronounced when\nconsidering the file size of the generated Python plugin: for the largest file,\nthe binary generated by Boost.Python required 16.8 MiB, which was **2.17\ntimes** / **9.1 megabytes** larger than the output generated by pybind11. For\nvery small inputs, Boost.Python has an edge in the plot below -- however, note\nthat it stores many definitions in an external library, whose size was not\nincluded here, hence the comparison is slightly shifted in Boost.Python's\nfavor.\n\n.. only:: not latex\n\n    .. image:: pybind11_vs_boost_python2.svg\n\n.. only:: latex\n\n    .. image:: pybind11_vs_boost_python2.png\n"
  },
  {
    "path": "docs/changelog.md",
    "content": "# Changelog\n\n<style>\nul.simple > li > p {\n  padding-bottom: .2em;\n}\n</style>\n\nStarting with version 1.8.0, pybind11 releases use a [semantic\nversioning](http://semver.org) policy.\n\nChanges will be added here periodically from the \"Suggested changelog\nentry\" block in pull request descriptions.\n\n\n## Version 3.0.2 (February 16, 2026)\n\nNew Features:\n\n- Added helper functions to `py::array` that return shape and strides as `std::span` when available.\n  [#5974](https://github.com/pybind/pybind11/pull/5974)\n\nBug fixes:\n\n- Added fallback locking for Python 3.13t where `PyCriticalSection_BeginMutex` is unavailable.\n  [#5981](https://github.com/pybind/pybind11/pull/5981)\n\n- Fixed race condition in `py::make_key_iterator` with free-threaded Python.\n  [#5971](https://github.com/pybind/pybind11/pull/5971)\n\n- MSVC 19.16 and earlier were blocked from using `std::launder` due to internal compiler errors.\n  [#5968](https://github.com/pybind/pybind11/pull/5968)\n\n- Internals destructors were updated to check the owning interpreter before clearing Python objects.\n  [#5965](https://github.com/pybind/pybind11/pull/5965)\n\n- Internals shutdown handling was refined in two iterations before release: an initial finalization-time cleanup was followed by a safety adjustment to avoid late-shutdown `py::cast` segfaults.\n  [#5958](https://github.com/pybind/pybind11/pull/5958)\n  [#5972](https://github.com/pybind/pybind11/pull/5972)\n\n- Fixed ambiguous `str(handle)` construction for `object`-derived types like `kwargs` or `dict` by templatizing the constructor with SFINAE.\n  [#5949](https://github.com/pybind/pybind11/pull/5949)\n\n- Fixed concurrency consistency for `internals_pp_manager` under multiple-interpreters.\n  [#5947](https://github.com/pybind/pybind11/pull/5947)\n\n- Fixed MSVC LNK2001 in C++20 builds when /GL (whole program optimization) is enabled.\n  [#5939](https://github.com/pybind/pybind11/pull/5939)\n\n- Added per-interpreter storage for `gil_safe_call_once_and_store` to make it safe under multi-interpreters.\n  [#5933](https://github.com/pybind/pybind11/pull/5933)\n\n- A workaround for a GCC `-Warray-bounds` false positive in `argument_vector` was added.\n  [#5908](https://github.com/pybind/pybind11/pull/5908)\n\n- Corrected a mistake where support for `__index__` was added, but the type hints did not reflect acceptance of `SupportsIndex` objects. Also fixed a long-standing bug: the complex-caster did not accept `__index__` in `convert` mode.\n  [#5891](https://github.com/pybind/pybind11/pull/5891)\n\n- Fixed `*args/**kwargs` return types. Added type hinting to `py::make_tuple`.\n  [#5881](https://github.com/pybind/pybind11/pull/5881)\n\n- Fixed compiler error in `type_caster_generic` when casting a `T` implicitly convertible from `T*`.\n  [#5873](https://github.com/pybind/pybind11/pull/5873)\n\n- Updated `py::native_enum` bindings to unregister enum types on destruction, preventing a use-after-free when returning a destroyed enum instance.\n  [#5871](https://github.com/pybind/pybind11/pull/5871)\n\n- Fixed undefined behavior that occurred when importing pybind11 modules from non-main threads created by C API modules or embedded python interpreters.\n  [#5870](https://github.com/pybind/pybind11/pull/5870)\n\n- Fixed dangling pointer in `internals::registered_types_cpp_fast`.\n  [#5867](https://github.com/pybind/pybind11/pull/5867)\n\n- Added support for `std::shared_ptr<T>` when loading module-local or conduit types from other modules.\n  [#5862](https://github.com/pybind/pybind11/pull/5862)\n\n- Fixed thread-safety issues if types were concurrently registered while `get_local_type_info()` was called in free threaded Python.\n  [#5856](https://github.com/pybind/pybind11/pull/5856)\n\n- Fixed py::float_ casting and py::int_ and py::float_ type hints.\n  [#5839](https://github.com/pybind/pybind11/pull/5839)\n\n- Fixed two `smart_holder` bugs in `shared_ptr` and `unique_ptr` adoption with multiple/virtual inheritance:\n    - `shared_ptr` to-Python caster was updated to register the correct subobject pointer (fixes #5786).\n    - `unique_ptr` adoption was updated to own the proper object start while aliasing subobject pointers for registration, which fixed MSVC crashes during destruction.\n  [#5836](https://github.com/pybind/pybind11/pull/5836)\n\n- Constrained `accessor::operator=` templates to avoid obscuring special members.\n  [#5832](https://github.com/pybind/pybind11/pull/5832)\n\n- Fixed crash that can occur when finalizers acquire and release the GIL.\n  [#5828](https://github.com/pybind/pybind11/pull/5828)\n\n- Fixed compiler detection in `pybind11/detail/pybind11_namespace_macros.h` for clang-cl on Windows, to address warning suppression macros.\n  [#5816](https://github.com/pybind/pybind11/pull/5816)\n\n- Fixed compatibility with CMake policy CMP0190 by not always requiring a Python interpreter when cross-compiling.\n  [#5829](https://github.com/pybind/pybind11/pull/5829)\n\n- Added a static assertion to disallow `keep_alive` and `call_guard` on properties.\n  [#5533](https://github.com/pybind/pybind11/pull/5533)\n\nInternal:\n\n- CMake policy limit was set to 4.1.\n  [#5944](https://github.com/pybind/pybind11/pull/5944)\n\n- Improved performance of function calls between Python and C++ by switching to the \"vectorcall\" calling protocol.\n  [#5948](https://github.com/pybind/pybind11/pull/5948)\n\n- Many C-style casts were replaced with C++-style casts.\n  [#5930](https://github.com/pybind/pybind11/pull/5930)\n\n- Added `cast_sources` abstraction to `type_caster_generic`.\n  [#5866](https://github.com/pybind/pybind11/pull/5866)\n\n- Improved the performance of from-Python conversions of legacy pybind11 enum objects bound by `py::enum_`.\n  [#5860](https://github.com/pybind/pybind11/pull/5860)\n\n- Reduced size overhead by deduplicating functions' readable signatures and type information.\n  [#5857](https://github.com/pybind/pybind11/pull/5857)\n\n- Used new Python 3.14 C APIs when available.\n  [#5854](https://github.com/pybind/pybind11/pull/5854)\n\n- Improved performance of function dispatch and type casting by porting two-level type info lookup strategy from nanobind.\n  [#5842](https://github.com/pybind/pybind11/pull/5842)\n\n- Updated `.gitignore` to exclude `__pycache__/` directories.\n  [#5838](https://github.com/pybind/pybind11/pull/5838)\n\n- Changed internals to use `thread_local` instead of `thread_specific_storage` for increased performance.\n  [#5834](https://github.com/pybind/pybind11/pull/5834)\n\n- Reduced function call overhead by using thread_local for loader_life_support when possible.\n  [#5830](https://github.com/pybind/pybind11/pull/5830)\n\n- Removed heap allocation for the C++ argument array when dispatching functions with 6 or fewer arguments.\n  [#5824](https://github.com/pybind/pybind11/pull/5824)\n\n\nDocumentation:\n\n- Fixed docstring for `long double` complex types to use `numpy.clongdouble` instead of the deprecated `numpy.longcomplex` (removed in NumPy 2.0).\n  [#5952](https://github.com/pybind/pybind11/pull/5952)\n\n- The \"Supported compilers\" and \"Supported platforms\" sections in the main `README.rst` were replaced with a new \"Supported platforms & compilers\" section that points to the CI test matrix as the living source of truth.\n  [#5910](https://github.com/pybind/pybind11/pull/5910)\n\n- Fixed documentation formatting.\n  [#5903](https://github.com/pybind/pybind11/pull/5903)\n\n- Updated upgrade notes for `py::native_enum`.\n  [#5885](https://github.com/pybind/pybind11/pull/5885)\n\n- Clarified in the docs to what extent bindings are global.\n  [#5859](https://github.com/pybind/pybind11/pull/5859)\n\n\nTests:\n\n- Fixed deadlock in a free-threading test by releasing the GIL while waiting on synchronization.\n  [#5973](https://github.com/pybind/pybind11/pull/5973)\n\n- Calls to `env.deprecated_call()` were replaced with direct calls to `pytest.deprecated_call()`.\n  [#5893](https://github.com/pybind/pybind11/pull/5893)\n\n- Updated pytest configuration to use `log_level` instead of `log_cli_level`.\n  [#5890](https://github.com/pybind/pybind11/pull/5890)\n\n\nCI:\n\n- Added CI tests for windows-11-arm with clang/MSVC (currently python 3.13), windows-11-arm with clang/mingw (currently python 3.12).\n  [#5932](https://github.com/pybind/pybind11/pull/5932)\n\n- These clang-tidy rules were added: `readability-redundant-casting`, `readability-redundant-inline-specifier`, `readability-redundant-member-init`\n  [#5924](https://github.com/pybind/pybind11/pull/5924)\n\n- Replaced deprecated macos-13 runners with macos-15-intel in CI.\n  [#5916](https://github.com/pybind/pybind11/pull/5916)\n\n- Restored `runs-on: windows-latest` in CI.\n  [#5835](https://github.com/pybind/pybind11/pull/5835)\n\n## Version 3.0.1 (August 22, 2025)\n\nBug fixes:\n\n- Fixed compilation error in `type_caster_enum_type` when casting\n  pointer-to-enum types. Added pointer overload to handle dereferencing before\n  enum conversion.\n  [#5776](https://github.com/pybind/pybind11/pull/5776)\n\n- Implement binary version of `make_index_sequence` to reduce template depth\n  requirements for functions with many parameters.\n  [#5751](https://github.com/pybind/pybind11/pull/5751)\n\n- Subinterpreter-specific exception handling code was removed to resolve segfaults.\n  [#5795](https://github.com/pybind/pybind11/pull/5795)\n\n- Fixed issue that caused ``PYBIND11_MODULE`` code to run again if the module\n  was re-imported after being deleted from ``sys.modules``.\n  [#5782](https://github.com/pybind/pybind11/pull/5782)\n\n- Prevent concurrent creation of sub-interpreters as a workaround for stdlib\n  concurrency issues in Python 3.12.\n  [#5779](https://github.com/pybind/pybind11/pull/5779)\n\n- Fixed potential crash when using `cpp_function` objects with sub-interpreters.\n  [#5771](https://github.com/pybind/pybind11/pull/5771)\n\n- Fixed non-entrant check in `implicitly_convertible()`.\n  [#5777](https://github.com/pybind/pybind11/pull/5777)\n\n- Support C++20 on platforms that have older c++ runtimes.\n  [#5761](https://github.com/pybind/pybind11/pull/5761)\n\n- Fix compilation with clang on msys2.\n  [#5757](https://github.com/pybind/pybind11/pull/5757)\n\n- Avoid `nullptr` dereference warning with GCC 13.3.0 and python 3.11.13.\n  [#5756](https://github.com/pybind/pybind11/pull/5756)\n\n- Fix potential warning about number of threads being too large.\n  [#5807](https://github.com/pybind/pybind11/pull/5807)\n\n\n<!-- fix(cmake) -->\n\n- Fix gcc 11.4+ warning about serial compilation using CMake.\n  [#5791](https://github.com/pybind/pybind11/pull/5791)\n\n\nDocumentation:\n\n- Improve `buffer_info` type checking in numpy docs.\n  [#5805](https://github.com/pybind/pybind11/pull/5805)\n\n- Replace `robotpy-build` with `semiwrap` in the binding tool list.\n  [#5804](https://github.com/pybind/pybind11/pull/5804)\n\n- Show nogil in most examples.\n  [#5770](https://github.com/pybind/pybind11/pull/5770)\n\n- Fix `py::trampoline_self_life_support` visibility in docs.\n  [#5766](https://github.com/pybind/pybind11/pull/5766)\n\n\nTests:\n\n- Avoid a spurious warning about `DOWNLOAD_CATCH` being manually specified.\n  [#5803](https://github.com/pybind/pybind11/pull/5803)\n\n- Fix an IsolatedConfig test.\n  [#5768](https://github.com/pybind/pybind11/pull/5768)\n\n\nCI:\n\n- Add CI testing for Android.\n  [#5714](https://github.com/pybind/pybind11/pull/5714)\n\n\nInternal:\n\n- Rename internal variables to avoid the word `slots` (reads better).\n  [#5793](https://github.com/pybind/pybind11/pull/5793)\n\n\n## Version 3.0.0 (July 10, 2025)\n\nPybind11 3.0 includes an ABI bump, the first required bump in many years\non Unix (Windows has had required bumps more often). This release contains\nthe smart-holder branch, multi-phase init and subinterpreter support,\n`py::native_enum`, an interface to warnings, typing improvements, and more.\nCMake now defaults to FindPython mode. Please check our upgrade guide for\nmore info on upgrading!\n\nSupport for Python 3.14, 3.14t, GraalPy, and PyPy 3.11 has been added, while\nlegacy support for Python 3.7, PyPy 3.8/3.9, and CMake \\<3.15 has been removed.\nMost deprecated features have been kept for this release, but anything\nproducing a warning in 3.0 may be removed in a future 3.x version. We also now\nhave a deprecation page.\n\nNew Features:\n\n- The `smart_holder` branch has been merged, enabling\n  `py::class_<T, py::smart_holder>`, which handles two-way conversion\n  with `std::unique_ptr<T>` and `std::shared_ptr<T>` (simultaneously),\n  disowning a Python object being passed to `std::unique_ptr<T>`,\n  trampoline objects, and `std::enable_shared_from_this`.\n  [#5542](https://github.com/pybind/pybind11/pull/5542)\n\n  - Added support for `std::shared_ptr<const T>` in `py::init()` when using\n    `py::smart_holder`, complementing existing support for\n    `std::unique_ptr<const T>`.\n    [#5731](https://github.com/pybind/pybind11/pull/5731)\n\n  - Support const-only smart pointers.\n    [#5718](https://github.com/pybind/pybind11/pull/5718)\n\n  - Eliminate cross-DSO RTTI reliance from `trampoline_self_life_support` functionality, `smart_holder` deleter detection, and other\n    `smart_holder` bookkeeping. Resolves platform-specific issues on macOS related to cross-DSO `dynamic_cast` and `typeid` mismatches.\n    [#5728](https://github.com/pybind/pybind11/pull/5728) (replaces [#5700](https://github.com/pybind/pybind11/pull/5700))\n\n- Changed `PYBIND11_MODULE` macro implementation to perform multi-phase\n  module initialization (PEP 489) behind the scenes.\n  [#5574](https://github.com/pybind/pybind11/pull/5574) and avoid destruction\n  [#5688](https://github.com/pybind/pybind11/pull/5688)\n\n- Support for sub-interpreters (both isolated (with separate GILs) and\n  legacy (with a global GIL). Add the\n  `py::multiple_interpreters::per_interpreter_gil()` tag (or,\n  `py::multiple_interpreters::shared_gil()` for legacy interpreter\n  support) to `PYBIND11_MODULE` calls (as the third parameter) to\n  indicate that a module supports running with sub-interpreters.\n  [#5564](https://github.com/pybind/pybind11/pull/5564)\n\n  - Rename macro `PYBIND11_SUBINTERPRETER_SUPPORT` -> `PYBIND11_HAS_SUBINTERPRETER_SUPPORT` to meet naming convention.\n    [#5682](https://github.com/pybind/pybind11/pull/5682)\n\n  - Allow subinterpreter support to be disabled if defined to 0. This is mostly an emergency workaround, and is not exposed in CMake.\n    [#5708](https://github.com/pybind/pybind11/pull/5708) and [#5710](https://github.com/pybind/pybind11/pull/5710)\n\n  - Modify internals pointer-to-pointer implementation to not use `thread_local` (better iOS support).\n    [#5709](https://github.com/pybind/pybind11/pull/5709)\n\n  - Support implementations without subinterpreter support.\n    [#5732](https://github.com/pybind/pybind11/pull/5732)\n\n- Changed `PYBIND11_EMBEDDED_MODULE` macro implementation to perform\n  multi-phase module initialization (PEP 489) behind the scenes and to\n  support `py::mod_gil_not_used()`,\n  `py::multiple_interpreters::per_interpreter_gil()` and\n  `py::multiple_interpreters::shared_gil()`.\n  [#5665](https://github.com/pybind/pybind11/pull/5665) and consolidate code\n  [#5670](https://github.com/pybind/pybind11/pull/5670).\n\n- Added API in `pybind11/subinterpreter.h` for embedding sub-interpreters (requires Python 3.12+).\n  [#5666](https://github.com/pybind/pybind11/pull/5666)\n\n- `py::native_enum` was added, for conversions between Python's native\n  (stdlib) enum types and C++ enums.\n  [#5555](https://github.com/pybind/pybind11/pull/5555)\n\n  - Add class doc string to `py::native_enum`.\n    [#5617](https://github.com/pybind/pybind11/pull/5617).\n\n  - Fix signature for functions with a `native_enum` in the signature.\n    [#5619](https://github.com/pybind/pybind11/pull/5619)\n\n- Support `py::numpy_scalar<>` / `py::make_scalar()` for NumPy types.\n  [#5726](https://github.com/pybind/pybind11/pull/5726)\n\n- A `py::release_gil_before_calling_cpp_dtor` option (for `py::class_`)\n  was added to resolve the long-standing issue \\#1446.\n  [#5522](https://github.com/pybind/pybind11/pull/5522)\n\n- Add `dtype::normalized_num` and `dtype::num_of`.\n  [#5429](https://github.com/pybind/pybind11/pull/5429)\n\n- Add support for `array_t<handle>` and `array_t<object>`.\n  [#5427](https://github.com/pybind/pybind11/pull/5427)\n\n- Added `py::warnings` namespace with `py::warnings::warn` and\n  `py::warnings::new_warning_type` that provides the interface for\n  Python warnings.\n  [#5291](https://github.com/pybind/pybind11/pull/5291)\n\n- `stl.h` `list|set|map_caster` were made more user friendly: it is no\n  longer necessary to explicitly convert Python iterables to `tuple()`,\n  `set()`, or `map()` in many common situations.\n  [#4686](https://github.com/pybind/pybind11/pull/4686)\n\n- The `array_caster` in pybind11/stl.h was enhanced to support value\n  types that are not default-constructible.\n  [#5305](https://github.com/pybind/pybind11/pull/5305)\n\n- `pybind11/conduit/pybind11_platform_abi_id.h` was factored out, to\n  maximize reusability of `PYBIND11_PLATFORM_ABI_ID` (for other\n  Python/C++ binding systems). Separately, a note was added to explain\n  that the conduit feature only covers from-Python-to-C++ conversions.\n  [#5375](https://github.com/pybind/pybind11/pull/5375) \\|\n  [#5740](https://github.com/pybind/pybind11/pull/5740)\n\n- Added support for finding pybind11 using pkgconf distributed on pypi.\n  [#5552](https://github.com/pybind/pybind11/pull/5552)\n\n- Support `--extension-suffix` on the pybind11 command.\n  [#5360](https://github.com/pybind/pybind11/pull/5360)\n\n- Add semi-public API: `pybind11::detail::is_holder_constructed` and\n  update example for `pybind11::custom_type_setup` in documentation.\n  [#5669](https://github.com/pybind/pybind11/pull/5669)\n\n- Added `py::scoped_critical_section` to support free-threaded mode.\n  [#5684](https://github.com/pybind/pybind11/pull/5684) \\|\n  [#5706](https://github.com/pybind/pybind11/pull/5706)\n\nNew Features / fixes (typing):\n\n- Added option for different arg/return type hints to `type_caster`.\n  Updated `stl/filesystem` to use correct arg/return type hints. Updated\n  `pybind11::typing` to use correct arg/return type hints for nested\n  types. [#5450](https://github.com/pybind/pybind11/pull/5450)\n- Updated type hint for `py::capsule` to `type.CapsuleType`.\n  [#5567](https://github.com/pybind/pybind11/pull/5567)\n- Adds support for `typing.SupportsInt` and `typing.SupportsFloat`.\n  Update `Final` to be narrower type hint. Make `std::function` match\n  `Callable` type. Fix `io_name` bug in `attr_with_type_hint`.\n  [#5540](https://github.com/pybind/pybind11/pull/5540)\n- Rework of arg/return type hints to support `.noconvert()`.\n  [#5486](https://github.com/pybind/pybind11/pull/5486)\n- Add `attr_with_type` for declaring attribute types and `Final`,\n  `ClassVar` type annotations.\n  [#5460](https://github.com/pybind/pybind11/pull/5460)\n- Allow annotate methods with `py::pos_only` when only have the `self`\n  argument. Make arguments for auto-generated dunder methods\n  positional-only.\n  [#5403](https://github.com/pybind/pybind11/pull/5403)\n- Added `py::Args` and `py::KWArgs` to enable custom type hinting of\n  `*args` and `**kwargs` (see PEP 484).\n  [#5357](https://github.com/pybind/pybind11/pull/5357)\n- Switched to `numpy.typing.NDArray` and `numpy.typing.ArrayLike`.\n  [#5212](https://github.com/pybind/pybind11/pull/5212)\n- Use `numpy.object_` instead of `object`.\n  [#5571](https://github.com/pybind/pybind11/pull/5571)\n- Fix module type hint.\n  [#5469](https://github.com/pybind/pybind11/pull/5469)\n- Fix Buffer type hint.\n  [#5662](https://github.com/pybind/pybind11/pull/5662)\n- Added support for `collections.abc` in type hints and convertible\n  checks of STL casters and `py::buffer`.\n  [#5566](https://github.com/pybind/pybind11/pull/5566)\n- Fix `typing` and `collections.abc` type hint ambiguity.\n  [#5663](https://github.com/pybind/pybind11/pull/5663)\n- Add `typing_extensions` alternatives for all types that need them.\n  [#5693](https://github.com/pybind/pybind11/pull/5693)\n\nRemovals:\n\n- Remove support for pybind11 v2 internals versions (4, 5, 6). (The\n  internals version number has been bumped for pybind11 v3.)\n  [#5512](https://github.com/pybind/pybind11/pull/5512) \\|\n  [#5530](https://github.com/pybind/pybind11/pull/5530)\n- Remove `make_simple_namespace` (added in 2.8.0, deprecated in 2.8.1).\n  [#5597](https://github.com/pybind/pybind11/pull/5597)\n- Legacy-mode option `PYBIND11_NUMPY_1_ONLY` has been removed.\n  [#5595](https://github.com/pybind/pybind11/pull/5595)\n- Add a deprecation warning to `.get_type` (deprecated in pybind11 2.6\n  in 2020). [#5596](https://github.com/pybind/pybind11/pull/5596)\n\nBug fixes:\n\n- Set `__file__` on submodules.\n  [#5584](https://github.com/pybind/pybind11/pull/5584). Except on\n  embedded modules.\n  [#5650](https://github.com/pybind/pybind11/pull/5650)\n- pybind11-bound functions are now pickleable.\n  [#5580](https://github.com/pybind/pybind11/pull/5580)\n- Fix bug in `attr_with_type_hint` to allow objects to be in\n  `attr_with_type_hint`.\n  [#5576](https://github.com/pybind/pybind11/pull/5576)\n- A `-Wmaybe-uninitialized` warning suppression was added in\n  `pybind11/eigen/matrix.h`.\n  [#5516](https://github.com/pybind/pybind11/pull/5516)\n- `PYBIND11_WARNING_POP` was incorrectly defined as\n  `PYBIND11_PRAGMA(clang diagnostic push)`.\n  [#5448](https://github.com/pybind/pybind11/pull/5448)\n- `PYBIND11_PLATFORM_ABI_ID` (which is used in composing\n  `PYBIND11_INTERNALS_ID`) was modernized to reflect actual ABI\n  compatibility more accurately.\n  [#4953](https://github.com/pybind/pybind11/pull/4953) \\|\n  [#5439](https://github.com/pybind/pybind11/pull/5439)\n- Fix buffer protocol implementation.\n  [#5407](https://github.com/pybind/pybind11/pull/5407)\n- Fix iterator increment operator does not skip first item.\n  [#5400](https://github.com/pybind/pybind11/pull/5400)\n- When getting or deleting an element in a container bound by\n  `bind_map`, print the key in `KeyError` if it does not exist.\n  [#5397](https://github.com/pybind/pybind11/pull/5397)\n- `pybind11::builtin_exception` is now explicitly exported when linked\n  to libc++. [#5390](https://github.com/pybind/pybind11/pull/5390)\n- Allow subclasses of `py::args` and `py::kwargs`.\n  [#5381](https://github.com/pybind/pybind11/pull/5381)\n- Disable false-positive GCC 12 Bound Check warning.\n  [#5355](https://github.com/pybind/pybind11/pull/5355)\n- Update the dict when restoring pickles, instead of assigning a\n  replacement dict.\n  [#5658](https://github.com/pybind/pybind11/pull/5658)\n- Properly define `_DEBUG` macro to `1` instead of defining it without\n  value. [#5639](https://github.com/pybind/pybind11/pull/5639)\n- Fix a missing time cast causing a compile error for newer ICC.\n  [#5621](https://github.com/pybind/pybind11/pull/5621)\n- Change the behavior of the default constructor of `py::slice` to be\n  equivalent to `::` in Python.\n  [#5620](https://github.com/pybind/pybind11/pull/5620)\n\nBug fixes and features (CMake):\n\n- Enable FindPython mode by default, with a `COMPAT` mode that\n  sets some of the old variables to ease transition.\n  [#5553](https://github.com/pybind/pybind11/pull/5553)\n- Add an author warning that auto-calculated `PYTHON_MODULE_EXTENSION`\n  may not respect `SETUPTOOLS_EXT_SUFFIX` during cross-compilation.\n  [#5495](https://github.com/pybind/pybind11/pull/5495)\n- Don't strip with `CMAKE_BUILD_TYPE` None.\n  [#5392](https://github.com/pybind/pybind11/pull/5392)\n- Fix an issue with `NO_EXTRAS` adding `pybind11::windows_extras`\n  anyway. [#5378](https://github.com/pybind/pybind11/pull/5378)\n- Fix issue with NEW/OLD message showing up.\n  [#5656](https://github.com/pybind/pybind11/pull/5656)\n- Use CMake's warnings as errors if available (CMake 3.24+).\n  [#5612](https://github.com/pybind/pybind11/pull/5612)\n- Add support for running pybind11's tests via presets in CMake 3.25+.\n  [#5655](https://github.com/pybind/pybind11/pull/5655) and support `--fresh`.\n  [#5668](https://github.com/pybind/pybind11/pull/5668)\n- Experimental CMake support for Android.\n  [#5733](https://github.com/pybind/pybind11/pull/5733)\n- Presets now generate `compile_commands.json`.\n  [#5685](https://github.com/pybind/pybind11/pull/5685)\n\nBug fixes (free-threading):\n\n- Fix data race in free threaded CPython when accessing a shared static\n  variable. [#5494](https://github.com/pybind/pybind11/pull/5494)\n- A free-threading data race in `all_type_info()` was fixed.\n  [#5419](https://github.com/pybind/pybind11/pull/5419)\n- Added exception translator specific mutex used with\n  `try_translate_exceptions` in the free-threaded build for internal\n  locking. [#5362](https://github.com/pybind/pybind11/pull/5362)\n\nInternals:\n\n- Consolidated all `PYBIND11_HAS_...` feature macros into\n  `pybind11/detail/common.h` to streamline backward compatibility checks and\n  simplify internal refactoring. This change ensures consistent macro\n  availability regardless of header inclusion order.\n  [#5647](https://github.com/pybind/pybind11/pull/5647)\n\n- `pybind11/gil_simple.h` was factored out from `pybind11/gil.h`, so\n  that it can easily be reused.\n  [#5614](https://github.com/pybind/pybind11/pull/5614)\n\n- Use CPython macros to construct `PYBIND11_VERSION_HEX`.\n  [#5683](https://github.com/pybind/pybind11/pull/5683)\n\nDocumentation:\n\n- Improved `reference_internal` policy documentation.\n  [#5528](https://github.com/pybind/pybind11/pull/5528)\n\n- A new \"Double locking, deadlocking, GIL\" document was added.\n  [#5394](https://github.com/pybind/pybind11/pull/5394)\n\n- Add documenting for free-threading and subinterpreters.\n  [#5659](https://github.com/pybind/pybind11/pull/5659)\n\nTests:\n\n- Download the final Catch2 2.x release if Catch download is requested.\n  [#5568](https://github.com/pybind/pybind11/pull/5568)\n\n- Explicitly used `signed char` for two numpy dtype tests. As seen when\n  compiling using `clang` on Linux with the `-funsigned-char` flag.\n  [#5545](https://github.com/pybind/pybind11/pull/5545)\n\n- CI testing now includes\n  `-Wwrite-strings -Wunreachable-code -Wpointer-arith -Wredundant-decls`\n  in some jobs.\n  [#5523](https://github.com/pybind/pybind11/pull/5523)\n\n- Add nightly wheels to scientific-python's nightly wheelhouse.\n  [#5675](https://github.com/pybind/pybind11/pull/5675)\n\n- Expect free-threaded warning when loading a non-free-threaded module.\n  [#5680](https://github.com/pybind/pybind11/pull/5680)\n\n- Run pytest under Python devmode.\n  [#5715](https://github.com/pybind/pybind11/pull/5715)\n\nNew and removed platforms:\n\n- Support Python 3.14 (beta 1+).\n  [#5646](https://github.com/pybind/pybind11/pull/5646)\n\n- Added support for GraalPy Python implementation\n  (<https://github.com/oracle/graalpython>).\n  [#5380](https://github.com/pybind/pybind11/pull/5380)\n\n- Support and test iOS in CI.\n  [#5705](https://github.com/pybind/pybind11/pull/5705)\n\n- Support for PyPy 3.11 added.\n  [#5508](https://github.com/pybind/pybind11/pull/5508)\n  And test in ci.\n  [#5534](https://github.com/pybind/pybind11/pull/5534)\n\n- Support for PyPy 3.8 and 3.9 was dropped.\n  [#5578](https://github.com/pybind/pybind11/pull/5578)\n\n- Support for Python 3.7 was removed. (Official end-of-life:\n  2023-06-27).\n  [#5191](https://github.com/pybind/pybind11/pull/5191)\n\n- Support for CMake older than 3.15 removed. CMake 3.15-4.0 supported.\n  [#5304](https://github.com/pybind/pybind11/pull/5304) and fix regression [#5691](https://github.com/pybind/pybind11/pull/5691).\n\n- Use scikit-build-core for the build backend for the PyPI `pybind11`.\n  The CMake generation has been moved to the sdist-\\>wheel step.\n  `PYBIND11_GLOBAL_SDIST` has been removed.\n  [#5598](https://github.com/pybind/pybind11/pull/5598) and updated\n  docs/ci. [#5676](https://github.com/pybind/pybind11/pull/5676)\n\n- clang 20 tested and used for clang-tidy.\n  [#5692](https://github.com/pybind/pybind11/pull/5692)\n\n- Drop testing on MSVC 2019 (as it is being removed from GitHub).\n  [#5712](https://github.com/pybind/pybind11/pull/5712)\n\n- Support Windows C++20 and Linux C++23 in tests.\n  [#5707](https://github.com/pybind/pybind11/pull/5707)\n\n## Version 2.13.6 (September 13, 2024)\n\nNew Features:\n\n- A new `self._pybind11_conduit_v1_()` method is automatically added to\n  all `py::class_`-wrapped types, to enable type-safe interoperability\n  between different independent Python/C++ bindings systems, including\n  pybind11 versions with different `PYBIND11_INTERNALS_VERSION`'s.\n  Supported on pybind11 2.11.2, 2.12.1, and 2.13.6+.\n  [#5296](https://github.com/pybind/pybind11/pull/5296)\n\nBug fixes:\n\n- Using `__cpp_nontype_template_args` instead of\n  `__cpp_nontype_template_parameter_class`.\n  [#5330](https://github.com/pybind/pybind11/pull/5330)\n- Properly translate C++ exception to Python exception when creating\n  Python buffer from wrapped object.\n  [#5324](https://github.com/pybind/pybind11/pull/5324)\n\nDocumentation:\n\n- Adds an answer (FAQ) for \"What is a highly conclusive and simple way\n  to find memory leaks?\".\n  [#5340](https://github.com/pybind/pybind11/pull/5340)\n\n## Version 2.13.5 (August 22, 2024)\n\nBug fixes:\n\n- Fix includes when using Windows long paths (`\\\\?\\` prefix).\n  [#5321](https://github.com/pybind/pybind11/pull/5321)\n- Support `-Wpedantic` in C++20 mode.\n  [#5322](https://github.com/pybind/pybind11/pull/5322)\n- Fix and test `<ranges>` support for `py::tuple` and `py::list`.\n  [#5314](https://github.com/pybind/pybind11/pull/5314)\n\n## Version 2.13.4 (August 14, 2024)\n\nBug fixes:\n\n- Fix paths with spaces, including on Windows. (Replaces regression from\n  [#5302](https://github.com/pybind/pybind11/pull/5302))\n  [#4874](https://github.com/pybind/pybind11/pull/4874)\n\nDocumentation:\n\n- Remove repetitive words.\n  [#5308](https://github.com/pybind/pybind11/pull/5308)\n\n## Version 2.13.3 (August 13, 2024)\n\nBug fixes:\n\n- Quote paths from pybind11-config\n  [#5302](https://github.com/pybind/pybind11/pull/5302)\n- Fix typo in Emscripten support when in config mode (CMake)\n  [#5301](https://github.com/pybind/pybind11/pull/5301)\n\n## Version 2.13.2 (August 13, 2024)\n\nNew Features:\n\n- A `pybind11::detail::type_caster_std_function_specializations` feature\n  was added, to support specializations for `std::function`'s with\n  return types that require custom to-Python conversion behavior (to\n  primary use case is to catch and convert exceptions).\n  [#4597](https://github.com/pybind/pybind11/pull/4597)\n\nChanges:\n\n- Use `PyMutex` instead of `std::mutex` for internal locking in the\n  free-threaded build.\n  [#5219](https://github.com/pybind/pybind11/pull/5219)\n- Add a special type annotation for C++ empty tuple.\n  [#5214](https://github.com/pybind/pybind11/pull/5214)\n- When compiling for WebAssembly, add the required exception flags\n  (CMake 3.13+). [#5298](https://github.com/pybind/pybind11/pull/5298)\n\nBug fixes:\n\n- Make `gil_safe_call_once_and_store` thread-safe in free-threaded\n  CPython. [#5246](https://github.com/pybind/pybind11/pull/5246)\n- A missing `#include <algorithm>` in pybind11/typing.h was added to fix\n  build errors (in case user code does not already depend on that\n  include). [#5208](https://github.com/pybind/pybind11/pull/5208)\n- Fix regression introduced in \\#5201 for GCC\\<10.3 in C++20 mode.\n  [#5205](https://github.com/pybind/pybind11/pull/5205)\n\n<!-- -->\n\n- Remove extra = when assigning flto value in the case for Clang in\n  CMake. [#5207](https://github.com/pybind/pybind11/pull/5207)\n\nTests:\n\n- Adding WASM testing to our CI (Pyodide / Emscripten via\n  scikit-build-core).\n  [#4745](https://github.com/pybind/pybind11/pull/4745)\n- clang-tidy (in GitHub Actions) was updated from clang 15 to clang 18.\n  [#5272](https://github.com/pybind/pybind11/pull/5272)\n\n## Version 2.13.1 (June 26, 2024)\n\nNew Features:\n\n- Add support for `Typing.Callable[..., T]`.\n  [#5202](https://github.com/pybind/pybind11/pull/5202)\n\nBug fixes:\n\n- Avoid aligned allocation in free-threaded build in order to support\n  macOS versions before 10.14.\n  [#5200](https://github.com/pybind/pybind11/pull/5200)\n\n## Version 2.13.0 (June 25, 2024)\n\nNew Features:\n\n- Support free-threaded CPython (3.13t). Add `py::mod_gil_not_used()`\n  tag to indicate if a module supports running with the GIL disabled.\n  [#5148](https://github.com/pybind/pybind11/pull/5148)\n- Support for Python 3.6 was removed. (Official end-of-life:\n  2021-12-23). [#5177](https://github.com/pybind/pybind11/pull/5177)\n- `py::list` gained a `.clear()` method.\n  [#5153](https://github.com/pybind/pybind11/pull/5153)\n\n<!-- -->\n\n- Support for `Union`, `Optional`, `type[T]`, `typing.TypeGuard`,\n  `typing.TypeIs`, `typing.Never`, `typing.NoReturn` and\n  `typing.Literal` was added to `pybind11/typing.h`.\n  [#5166](https://github.com/pybind/pybind11/pull/5166)\n  [#5165](https://github.com/pybind/pybind11/pull/5165)\n  [#5194](https://github.com/pybind/pybind11/pull/5194)\n  [#5193](https://github.com/pybind/pybind11/pull/5193)\n  [#5192](https://github.com/pybind/pybind11/pull/5192)\n\n<!-- -->\n\n- In CMake, if `PYBIND11_USE_CROSSCOMPILING` is enabled, then\n  `CMAKE_CROSSCOMPILING` will be respected and will keep pybind11 from\n  accessing the interpreter during configuration. Several CMake\n  variables will be required in this case, but can be deduced from the\n  environment variable `SETUPTOOLS_EXT_SUFFIX`. The default (currently\n  `OFF`) may be changed in the future.\n  [#5083](https://github.com/pybind/pybind11/pull/5083)\n\nBug fixes:\n\n- A refcount bug (leading to heap-use-after-free) involving trampoline\n  functions with `PyObject *` return type was fixed.\n  [#5156](https://github.com/pybind/pybind11/pull/5156)\n- Return `py::ssize_t` from `.ref_count()` instead of `int`.\n  [#5139](https://github.com/pybind/pybind11/pull/5139)\n- A subtle bug involving C++ types with unusual `operator&` overrides\n  was fixed. [#5189](https://github.com/pybind/pybind11/pull/5189)\n- Support Python 3.13 with minor fix, add to CI.\n  [#5127](https://github.com/pybind/pybind11/pull/5127)\n\n<!-- -->\n\n- Fix mistake affecting old cmake and old boost.\n  [#5149](https://github.com/pybind/pybind11/pull/5149)\n\nDocumentation:\n\n- Build docs updated to feature scikit-build-core and meson-python, and\n  updated setuptools instructions.\n  [#5168](https://github.com/pybind/pybind11/pull/5168)\n\nTests:\n\n- Avoid immortal objects in tests.\n  [#5150](https://github.com/pybind/pybind11/pull/5150)\n\nCI:\n\n- Compile against Python 3.13t in CI.\n- Use `macos-13` (Intel) for CI jobs for now (will drop Python 3.7\n  soon). [#5109](https://github.com/pybind/pybind11/pull/5109)\n- Releases now have artifact attestations, visible at\n  <https://github.com/pybind/pybind11/attestations>.\n  [#5196](https://github.com/pybind/pybind11/pull/5196)\n\nOther:\n\n- Some cleanup in preparation for 3.13 support.\n  [#5137](https://github.com/pybind/pybind11/pull/5137)\n- Avoid a warning by ensuring an iterator end check is included in\n  release mode. [#5129](https://github.com/pybind/pybind11/pull/5129)\n- Bump max cmake to 3.29.\n  [#5075](https://github.com/pybind/pybind11/pull/5075)\n- Update docs and noxfile.\n  [#5071](https://github.com/pybind/pybind11/pull/5071)\n\n## Version 2.12.1 (September 13, 2024)\n\nNew Features:\n\n- A new `self._pybind11_conduit_v1_()` method is automatically added to\n  all `py::class_`-wrapped types, to enable type-safe interoperability\n  between different independent Python/C++ bindings systems, including\n  pybind11 versions with different `PYBIND11_INTERNALS_VERSION`'s.\n  Supported on pybind11 2.11.2, 2.12.1, and 2.13.6+.\n  [#5296](https://github.com/pybind/pybind11/pull/5296)\n\n## Version 2.12.0 (March 27, 2024)\n\nNew Features:\n\n- `pybind11` now supports compiling for [NumPy\n  2](https://numpy.org/devdocs/numpy_2_0_migration_guide.html). Most\n  code shouldn't change (see `upgrade-guide-2.12` for details). However,\n  if you experience issues you can define `PYBIND11_NUMPY_1_ONLY` to\n  disable the new support for now, but this will be removed in the\n  future. [#5050](https://github.com/pybind/pybind11/pull/5050)\n- `pybind11/gil_safe_call_once.h` was added (it needs to be included\n  explicitly). The primary use case is GIL-safe initialization of C++\n  `static` variables.\n  [#4877](https://github.com/pybind/pybind11/pull/4877)\n- Support move-only iterators in `py::make_iterator`,\n  `py::make_key_iterator`, `py::make_value_iterator`.\n  [#4834](https://github.com/pybind/pybind11/pull/4834)\n- Two simple `py::set_error()` functions were added and the\n  documentation was updated accordingly. In particular,\n  `py::exception<>::operator()` was deprecated (use one of the new\n  functions instead). The documentation for `py::exception<>` was\n  further updated to not suggest code that may result in undefined\n  behavior. [#4772](https://github.com/pybind/pybind11/pull/4772)\n\nBug fixes:\n\n- Removes potential for Undefined Behavior during process teardown.\n  [#4897](https://github.com/pybind/pybind11/pull/4897)\n- Improve compatibility with the nvcc compiler (especially CUDA\n  12.1/12.2). [#4893](https://github.com/pybind/pybind11/pull/4893)\n- `pybind11/numpy.h` now imports NumPy's `multiarray` and `_internal`\n  submodules with paths depending on the installed version of NumPy (for\n  compatibility with NumPy 2).\n  [#4857](https://github.com/pybind/pybind11/pull/4857)\n- Builtins collections names in docstrings are now consistently rendered\n  in lowercase (list, set, dict, tuple), in accordance with PEP 585.\n  [#4833](https://github.com/pybind/pybind11/pull/4833)\n- Added `py::typing::Iterator<T>`, `py::typing::Iterable<T>`.\n  [#4832](https://github.com/pybind/pybind11/pull/4832)\n- Render `py::function` as `Callable` in docstring.\n  [#4829](https://github.com/pybind/pybind11/pull/4829)\n- Also bump `PYBIND11_INTERNALS_VERSION` for MSVC, which unlocks two new\n  features without creating additional incompatibilities.\n  [#4819](https://github.com/pybind/pybind11/pull/4819)\n- Guard against crashes/corruptions caused by modules built with\n  different MSVC versions.\n  [#4779](https://github.com/pybind/pybind11/pull/4779)\n- A long-standing bug in the handling of Python multiple inheritance was\n  fixed. See PR \\#4762 for the rather complex details.\n  [#4762](https://github.com/pybind/pybind11/pull/4762)\n- Fix `bind_map` with `using` declarations.\n  [#4952](https://github.com/pybind/pybind11/pull/4952)\n- Qualify `py::detail::concat` usage to avoid ADL selecting one from\n  somewhere else, such as modernjson's concat.\n  [#4955](https://github.com/pybind/pybind11/pull/4955)\n- Use new PyCode API on Python 3.12+.\n  [#4916](https://github.com/pybind/pybind11/pull/4916)\n- Minor cleanup from warnings reported by Clazy.\n  [#4988](https://github.com/pybind/pybind11/pull/4988)\n- Remove typing and duplicate `class_` for\n  `KeysView`/`ValuesView`/`ItemsView`.\n  [#4985](https://github.com/pybind/pybind11/pull/4985)\n- Use `PyObject_VisitManagedDict()` and `PyObject_ClearManagedDict()` on\n  Python 3.13 and newer.\n  [#4973](https://github.com/pybind/pybind11/pull/4973)\n- Update `make_static_property_type()` to make it compatible with Python\n  3.13. [#4971](https://github.com/pybind/pybind11/pull/4971)\n\n<!-- -->\n\n- Render typed iterators for `make_iterator`, `make_key_iterator`,\n  `make_value_iterator`.\n  [#4876](https://github.com/pybind/pybind11/pull/4876)\n- Add several missing type name specializations.\n  [#5073](https://github.com/pybind/pybind11/pull/5073)\n- Change docstring render for `py::buffer`, `py::sequence` and\n  `py::handle` (to `Buffer`, `Sequence`, `Any`).\n  [#4831](https://github.com/pybind/pybind11/pull/4831)\n- Fixed `base_enum.__str__` docstring.\n  [#4827](https://github.com/pybind/pybind11/pull/4827)\n- Enforce single line docstring signatures.\n  [#4735](https://github.com/pybind/pybind11/pull/4735)\n- Special 'typed' wrappers now available in `typing.h` to annotate\n  tuple, dict, list, set, and function.\n  [#4259](https://github.com/pybind/pybind11/pull/4259)\n- Create `handle_type_name` specialization to type-hint variable length\n  tuples. [#5051](https://github.com/pybind/pybind11/pull/5051)\n\n<!-- -->\n\n- Setting `PYBIND11_FINDPYTHON` to OFF will force the old FindPythonLibs\n  mechanism to be used.\n  [#5042](https://github.com/pybind/pybind11/pull/5042)\n- Skip empty `PYBIND11_PYTHON_EXECUTABLE_LAST` for the first cmake run.\n  [#4856](https://github.com/pybind/pybind11/pull/4856)\n- Fix FindPython mode exports & avoid `pkg_resources` if\n  `importlib.metadata` available.\n  [#4941](https://github.com/pybind/pybind11/pull/4941)\n- `Python_ADDITIONAL_VERSIONS` (classic search) now includes 3.12.\n  [#4909](https://github.com/pybind/pybind11/pull/4909)\n- `pybind11.pc` is now relocatable by default as long as install\n  destinations are not absolute paths.\n  [#4830](https://github.com/pybind/pybind11/pull/4830)\n- Correctly detect CMake FindPython removal when used as a subdirectory.\n  [#4806](https://github.com/pybind/pybind11/pull/4806)\n- Don't require the libs component on CMake 3.18+ when using\n  PYBIND11_FINDPYTHON (fixes manylinux builds).\n  [#4805](https://github.com/pybind/pybind11/pull/4805)\n- `pybind11_strip` is no longer automatically applied when\n  `CMAKE_BUILD_TYPE` is unset.\n  [#4780](https://github.com/pybind/pybind11/pull/4780)\n- Support `DEBUG_POSFIX` correctly for debug builds.\n  [#4761](https://github.com/pybind/pybind11/pull/4761)\n- Hardcode lto/thin lto for Emscripten cross-compiles.\n  [#4642](https://github.com/pybind/pybind11/pull/4642)\n- Upgrade maximum supported CMake version to 3.27 to fix CMP0148\n  warnings. [#4786](https://github.com/pybind/pybind11/pull/4786)\n\nDocumentation:\n\n- Small fix to grammar in `functions.rst`.\n  [#4791](https://github.com/pybind/pybind11/pull/4791)\n- Remove upper bound in example pyproject.toml for setuptools.\n  [#4774](https://github.com/pybind/pybind11/pull/4774)\n\nCI:\n\n- CI: Update NVHPC to 23.5 and Ubuntu 20.04.\n  [#4764](https://github.com/pybind/pybind11/pull/4764)\n- Test on PyPy 3.10.\n  [#4714](https://github.com/pybind/pybind11/pull/4714)\n\nOther:\n\n- Use Ruff formatter instead of Black.\n  [#4912](https://github.com/pybind/pybind11/pull/4912)\n- An `assert()` was added to help Coverty avoid generating a false\n  positive. [#4817](https://github.com/pybind/pybind11/pull/4817)\n\n## Version 2.11.2 (September 13, 2024)\n\nNew Features:\n\n- A new `self._pybind11_conduit_v1_()` method is automatically added to\n  all `py::class_`-wrapped types, to enable type-safe interoperability\n  between different independent Python/C++ bindings systems, including\n  pybind11 versions with different `PYBIND11_INTERNALS_VERSION`'s.\n  Supported on pybind11 2.11.2, 2.12.1, and 2.13.6+.\n  [#5296](https://github.com/pybind/pybind11/pull/5296)\n\n## Version 2.11.1 (July 17, 2023)\n\nChanges:\n\n- `PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF` is now provided as an\n  option for disabling the default-on `PyGILState_Check()`'s in\n  `pybind11::handle`'s `inc_ref()` & `dec_ref()`.\n  [#4753](https://github.com/pybind/pybind11/pull/4753)\n- `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF` was disabled for PyPy in\n  general (not just PyPy Windows).\n  [#4751](https://github.com/pybind/pybind11/pull/4751)\n\n## Version 2.11.0 (July 14, 2023)\n\nNew features:\n\n- The newly added `pybind11::detail::is_move_constructible` trait can be\n  specialized for cases in which `std::is_move_constructible` does not\n  work as needed. This is very similar to the long-established\n  `pybind11::detail::is_copy_constructible`.\n  [#4631](https://github.com/pybind/pybind11/pull/4631)\n- Introduce `recursive_container_traits`.\n  [#4623](https://github.com/pybind/pybind11/pull/4623)\n- `pybind11/type_caster_pyobject_ptr.h` was added to support automatic\n  wrapping of APIs that make use of `PyObject *`. This header needs to\n  included explicitly (i.e. it is not included implicitly with\n  `pybind/pybind11.h`).\n  [#4601](https://github.com/pybind/pybind11/pull/4601)\n- `format_descriptor<>` & `npy_format_descriptor<>` `PyObject *`\n  specializations were added. The latter enables\n  `py::array_t<PyObject *>` to/from-python conversions.\n  [#4674](https://github.com/pybind/pybind11/pull/4674)\n- `buffer_info` gained an `item_type_is_equivalent_to<T>()` member\n  function. [#4674](https://github.com/pybind/pybind11/pull/4674)\n- The `capsule` API gained a user-friendly constructor\n  (`py::capsule(ptr, \"name\", dtor)`).\n  [#4720](https://github.com/pybind/pybind11/pull/4720)\n\nChanges:\n\n- `PyGILState_Check()`'s in `pybind11::handle`'s `inc_ref()` &\n  `dec_ref()` are now enabled by default again.\n  [#4246](https://github.com/pybind/pybind11/pull/4246)\n- `py::initialize_interpreter()` using `PyConfig_InitPythonConfig()`\n  instead of `PyConfig_InitIsolatedConfig()`, to obtain complete\n  `sys.path`. [#4473](https://github.com/pybind/pybind11/pull/4473)\n- Cast errors now always include Python type information, even if\n  `PYBIND11_DETAILED_ERROR_MESSAGES` is not defined. This increases\n  binary sizes slightly (~1.5%) but the error messages are much more\n  informative. [#4463](https://github.com/pybind/pybind11/pull/4463)\n- The docstring generation for the `std::array`-list caster was fixed.\n  Previously, signatures included the size of the list in a\n  non-standard, non-spec compliant way. The new format conforms to\n  PEP 593. **Tooling for processing the docstrings may need to be\n  updated accordingly.**\n  [#4679](https://github.com/pybind/pybind11/pull/4679)\n- Setter return values (which are inaccessible for all practical\n  purposes) are no longer converted to Python (only to be discarded).\n  [#4621](https://github.com/pybind/pybind11/pull/4621)\n- Allow lambda specified to function definition to be `noexcept(true)`\n  in C++17. [#4593](https://github.com/pybind/pybind11/pull/4593)\n- Get rid of recursive template instantiations for concatenating type\n  signatures on C++17 and higher.\n  [#4587](https://github.com/pybind/pybind11/pull/4587)\n- Compatibility with Python 3.12 (beta). Note that the minimum pybind11\n  ABI version for Python 3.12 is version 5. (The default ABI version for\n  Python versions up to and including 3.11 is still version 4.).\n  [#4570](https://github.com/pybind/pybind11/pull/4570)\n- With `PYBIND11_INTERNALS_VERSION 5` (default for Python 3.12+), MSVC\n  builds use `std::hash<std::type_index>` and\n  `std::equal_to<std::type_index>` instead of string-based type\n  comparisons. This resolves issues when binding types defined in the\n  unnamed namespace.\n  [#4319](https://github.com/pybind/pybind11/pull/4319)\n- Python exception `__notes__` (introduced with Python 3.11) are now\n  added to the `error_already_set::what()` output.\n  [#4678](https://github.com/pybind/pybind11/pull/4678)\n\nBuild system improvements:\n\n- CMake 3.27 support was added, CMake 3.4 support was dropped.\n  FindPython will be used if `FindPythonInterp` is not present.\n  [#4719](https://github.com/pybind/pybind11/pull/4719)\n- Update clang-tidy to 15 in CI.\n  [#4387](https://github.com/pybind/pybind11/pull/4387)\n- Moved the linting framework over to Ruff.\n  [#4483](https://github.com/pybind/pybind11/pull/4483)\n- Skip `lto` checks and target generation when\n  `CMAKE_INTERPROCEDURAL_OPTIMIZATION` is defined.\n  [#4643](https://github.com/pybind/pybind11/pull/4643)\n- No longer inject `-stdlib=libc++`, not needed for modern Pythons\n  (macOS 10.9+). [#4639](https://github.com/pybind/pybind11/pull/4639)\n- PyPy 3.10 support was added, PyPy 3.7 support was dropped.\n  [#4728](https://github.com/pybind/pybind11/pull/4728)\n- Testing with Python 3.12 beta releases was added.\n  [#4713](https://github.com/pybind/pybind11/pull/4713)\n\n## Version 2.10.4 (Mar 16, 2023)\n\nChanges:\n\n- `python3 -m pybind11` gained a `--version` option (prints the version\n  and exits). [#4526](https://github.com/pybind/pybind11/pull/4526)\n\nBug Fixes:\n\n- Fix a warning when pydebug is enabled on Python 3.11.\n  [#4461](https://github.com/pybind/pybind11/pull/4461)\n- Ensure `gil_scoped_release` RAII is non-copyable.\n  [#4490](https://github.com/pybind/pybind11/pull/4490)\n- Ensure the tests dir does not show up with new versions of setuptools.\n  [#4510](https://github.com/pybind/pybind11/pull/4510)\n- Better stacklevel for a warning in setuptools helpers.\n  [#4516](https://github.com/pybind/pybind11/pull/4516)\n\n## Version 2.10.3 (Jan 3, 2023)\n\nChanges:\n\n- Temporarily made our GIL status assertions (added in 2.10.2) disabled\n  by default (re-enable manually by defining\n  `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`, will be enabled in 2.11).\n  [#4432](https://github.com/pybind/pybind11/pull/4432)\n- Improved error messages when `inc_ref`/`dec_ref` are called with an\n  invalid GIL state.\n  [#4427](https://github.com/pybind/pybind11/pull/4427)\n  [#4436](https://github.com/pybind/pybind11/pull/4436)\n\nBug Fixes:\n\n- Some minor touchups found by static analyzers.\n  [#4440](https://github.com/pybind/pybind11/pull/4440)\n\n## Version 2.10.2 (Dec 20, 2022)\n\nChanges:\n\n- `scoped_interpreter` constructor taking `PyConfig`.\n  [#4330](https://github.com/pybind/pybind11/pull/4330)\n- `pybind11/eigen/tensor.h` adds converters to and from `Eigen::Tensor`\n  and `Eigen::TensorMap`.\n  [#4201](https://github.com/pybind/pybind11/pull/4201)\n- `PyGILState_Check()`'s were integrated to `pybind11::handle`\n  `inc_ref()` & `dec_ref()`. The added GIL checks are guarded by\n  `PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF`, which is the default only if\n  `NDEBUG` is not defined. (Made non-default in 2.10.3, will be active\n  in 2.11) [#4246](https://github.com/pybind/pybind11/pull/4246)\n- Add option for enable/disable enum members in docstring.\n  [#2768](https://github.com/pybind/pybind11/pull/2768)\n- Fixed typing of `KeysView`, `ValuesView` and `ItemsView` in\n  `bind_map`. [#4353](https://github.com/pybind/pybind11/pull/4353)\n\nBug fixes:\n\n- Bug fix affecting only Python 3.6 under very specific, uncommon\n  conditions: move `PyEval_InitThreads()` call to the correct location.\n  [#4350](https://github.com/pybind/pybind11/pull/4350)\n- Fix segfault bug when passing foreign native functions to\n  functional.h. [#4254](https://github.com/pybind/pybind11/pull/4254)\n\nBuild system improvements:\n\n- Support setting PYTHON_LIBRARIES manually for Windows ARM\n  cross-compilation (classic mode).\n  [#4406](https://github.com/pybind/pybind11/pull/4406)\n- Extend IPO/LTO detection for ICX (a.k.a IntelLLVM) compiler.\n  [#4402](https://github.com/pybind/pybind11/pull/4402)\n- Allow calling `find_package(pybind11 CONFIG)` multiple times from\n  separate directories in the same CMake project and properly link\n  Python (new mode).\n  [#4401](https://github.com/pybind/pybind11/pull/4401)\n- `multiprocessing_set_spawn` in pytest fixture for added safety.\n  [#4377](https://github.com/pybind/pybind11/pull/4377)\n- Fixed a bug in two pybind11/tools cmake scripts causing \"Unknown\n  arguments specified\" errors.\n  [#4327](https://github.com/pybind/pybind11/pull/4327)\n\n## Version 2.10.1 (Oct 31, 2022)\n\nThis is the first version to fully support embedding the newly released\nPython 3.11.\n\nChanges:\n\n- Allow `pybind11::capsule` constructor to take null destructor\n  pointers. [#4221](https://github.com/pybind/pybind11/pull/4221)\n- `embed.h` was changed so that `PYTHONPATH` is used also with Python\n  3.11 (established behavior).\n  [#4119](https://github.com/pybind/pybind11/pull/4119)\n- A `PYBIND11_SIMPLE_GIL_MANAGEMENT` option was added (cmake, C++\n  define), along with many additional tests in `test_gil_scoped.py`. The\n  option may be useful to try when debugging GIL-related issues, to\n  determine if the more complex default implementation is or is not to\n  blame. See \\#4216 for background. WARNING: Please be careful to not\n  create ODR violations when using the option: everything that is linked\n  together with mutual symbol visibility needs to be rebuilt.\n  [#4216](https://github.com/pybind/pybind11/pull/4216)\n- `PYBIND11_EXPORT_EXCEPTION` was made non-empty only under macOS. This\n  makes Linux builds safer, and enables the removal of warning\n  suppression pragmas for Windows.\n  [#4298](https://github.com/pybind/pybind11/pull/4298)\n\nBug fixes:\n\n- Fixed a bug where `UnicodeDecodeError` was not propagated from various\n  `py::str` ctors when decoding surrogate utf characters.\n  [#4294](https://github.com/pybind/pybind11/pull/4294)\n- Revert perfect forwarding for `make_iterator`. This broke at least one\n  valid use case. May revisit later.\n  [#4234](https://github.com/pybind/pybind11/pull/4234)\n- Fix support for safe casts to `void*` (regression in 2.10.0).\n  [#4275](https://github.com/pybind/pybind11/pull/4275)\n- Fix `char8_t` support (regression in 2.9).\n  [#4278](https://github.com/pybind/pybind11/pull/4278)\n- Unicode surrogate character in Python exception message leads to\n  process termination in `error_already_set::what()`.\n  [#4297](https://github.com/pybind/pybind11/pull/4297)\n- Fix MSVC 2019 v.1924 & C++14 mode error for `overload_cast`.\n  [#4188](https://github.com/pybind/pybind11/pull/4188)\n- Make augmented assignment operators non-const for the object-api.\n  Behavior was previously broken for augmented assignment operators.\n  [#4065](https://github.com/pybind/pybind11/pull/4065)\n- Add proper error checking to C++ bindings for Python list append and\n  insert. [#4208](https://github.com/pybind/pybind11/pull/4208)\n- Work-around for Nvidia's CUDA nvcc compiler in versions 11.4.0 -\n  11.8.0. [#4220](https://github.com/pybind/pybind11/pull/4220)\n- A workaround for PyPy was added in the `py::error_already_set`\n  implementation, related to PR\n  [#1895](https://github.com/pybind/pybind11/pull/1895) released with\n  v2.10.0. [#4079](https://github.com/pybind/pybind11/pull/4079)\n- Fixed compiler errors when C++23 `std::forward_like` is available.\n  [#4136](https://github.com/pybind/pybind11/pull/4136)\n- Properly raise exceptions in contains methods (like when an object in\n  unhashable). [#4209](https://github.com/pybind/pybind11/pull/4209)\n- Further improve another error in exception handling.\n  [#4232](https://github.com/pybind/pybind11/pull/4232)\n- `get_local_internals()` was made compatible with\n  `finalize_interpreter()`, fixing potential freezes during interpreter\n  finalization. [#4192](https://github.com/pybind/pybind11/pull/4192)\n\nPerformance and style:\n\n- Reserve space in set and STL map casters if possible. This will\n  prevent unnecessary rehashing / resizing by knowing the number of keys\n  ahead of time for Python to C++ casting. This improvement will greatly\n  speed up the casting of large unordered maps and sets.\n  [#4194](https://github.com/pybind/pybind11/pull/4194)\n- GIL RAII scopes are non-copyable to avoid potential bugs.\n  [#4183](https://github.com/pybind/pybind11/pull/4183)\n- Explicitly default all relevant ctors for pytypes in the\n  `PYBIND11_OBJECT` macros and enforce the clang-tidy checks\n  `modernize-use-equals-default` in macros as well.\n  [#4017](https://github.com/pybind/pybind11/pull/4017)\n- Optimize iterator advancement in C++ bindings.\n  [#4237](https://github.com/pybind/pybind11/pull/4237)\n- Use the modern `PyObject_GenericGetDict` and `PyObject_GenericSetDict`\n  for handling dynamic attribute dictionaries.\n  [#4106](https://github.com/pybind/pybind11/pull/4106)\n- Document that users should use `PYBIND11_NAMESPACE` instead of using\n  `pybind11` when opening namespaces. Using namespace declarations and\n  namespace qualification remain the same as `pybind11`. This is done to\n  ensure consistent symbol visibility.\n  [#4098](https://github.com/pybind/pybind11/pull/4098)\n- Mark `detail::forward_like` as constexpr.\n  [#4147](https://github.com/pybind/pybind11/pull/4147)\n- Optimize unpacking_collector when processing `arg_v` arguments.\n  [#4219](https://github.com/pybind/pybind11/pull/4219)\n- Optimize casting C++ object to `None`.\n  [#4269](https://github.com/pybind/pybind11/pull/4269)\n\nBuild system improvements:\n\n- CMake: revert overwrite behavior, now opt-in with\n  `PYBIND11_PYTHONLIBS_OVERRWRITE OFF`.\n  [#4195](https://github.com/pybind/pybind11/pull/4195)\n- Include a pkg-config file when installing pybind11, such as in the\n  Python package. [#4077](https://github.com/pybind/pybind11/pull/4077)\n- Avoid stripping debug symbols when `CMAKE_BUILD_TYPE` is set to\n  `DEBUG` instead of `Debug`.\n  [#4078](https://github.com/pybind/pybind11/pull/4078)\n- Followup to [#3948](https://github.com/pybind/pybind11/pull/3948),\n  fixing vcpkg again.\n  [#4123](https://github.com/pybind/pybind11/pull/4123)\n\n## Version 2.10.0 (Jul 15, 2022)\n\nRemoved support for Python 2.7, Python 3.5, and MSVC 2015. Support for\nMSVC 2017 is limited due to availability of CI runners; we highly\nrecommend MSVC 2019 or 2022 be used. Initial support added for Python\n3.11.\n\nNew features:\n\n- `py::anyset` & `py::frozenset` were added, with copying (cast) to\n  `std::set` (similar to `set`).\n  [#3901](https://github.com/pybind/pybind11/pull/3901)\n- Support bytearray casting to string.\n  [#3707](https://github.com/pybind/pybind11/pull/3707)\n- `type_caster<std::monostate>` was added. `std::monostate` is a tag\n  type that allows `std::variant` to act as an optional, or allows\n  default construction of a `std::variant` holding a non-default\n  constructible type.\n  [#3818](https://github.com/pybind/pybind11/pull/3818)\n- `pybind11::capsule::set_name` added to mutate the name of the capsule\n  instance. [#3866](https://github.com/pybind/pybind11/pull/3866)\n- NumPy: dtype constructor from type number added, accessors\n  corresponding to Python API `dtype.num`, `dtype.byteorder`,\n  `dtype.flags` and `dtype.alignment` added.\n  [#3868](https://github.com/pybind/pybind11/pull/3868)\n\nChanges:\n\n- Python 3.6 is now the minimum supported version.\n  [#3688](https://github.com/pybind/pybind11/pull/3688)\n  [#3719](https://github.com/pybind/pybind11/pull/3719)\n- The minimum version for MSVC is now 2017.\n  [#3722](https://github.com/pybind/pybind11/pull/3722)\n- Fix issues with CPython 3.11 betas and add to supported test matrix.\n  [#3923](https://github.com/pybind/pybind11/pull/3923)\n- `error_already_set` is now safer and more performant, especially for\n  exceptions with long tracebacks, by delaying computation.\n  [#1895](https://github.com/pybind/pybind11/pull/1895)\n- Improve exception handling in python `str` bindings.\n  [#3826](https://github.com/pybind/pybind11/pull/3826)\n- The bindings for capsules now have more consistent exception handling.\n  [#3825](https://github.com/pybind/pybind11/pull/3825)\n- `PYBIND11_OBJECT_CVT` and `PYBIND11_OBJECT_CVT_DEFAULT` macro can now\n  be used to define classes in namespaces other than pybind11.\n  [#3797](https://github.com/pybind/pybind11/pull/3797)\n- Error printing code now uses `PYBIND11_DETAILED_ERROR_MESSAGES`\n  instead of requiring `NDEBUG`, allowing use with release builds if\n  desired. [#3913](https://github.com/pybind/pybind11/pull/3913)\n- Implicit conversion of the literal `0` to `pybind11::handle` is now\n  disabled. [#4008](https://github.com/pybind/pybind11/pull/4008)\n\nBug fixes:\n\n- Fix exception handling when `pybind11::weakref()` fails.\n  [#3739](https://github.com/pybind/pybind11/pull/3739)\n- `module_::def_submodule` was missing proper error handling. This is\n  fixed now. [#3973](https://github.com/pybind/pybind11/pull/3973)\n- The behavior or `error_already_set` was made safer and the highly\n  opaque \"Unknown internal error occurred\" message was replaced with a\n  more helpful message.\n  [#3982](https://github.com/pybind/pybind11/pull/3982)\n- `error_already_set::what()` now handles non-normalized exceptions\n  correctly. [#3971](https://github.com/pybind/pybind11/pull/3971)\n- Support older C++ compilers where filesystem is not yet part of the\n  standard library and is instead included in\n  `std::experimental::filesystem`.\n  [#3840](https://github.com/pybind/pybind11/pull/3840)\n- Fix `-Wfree-nonheap-object` warnings produced by GCC by avoiding\n  returning pointers to static objects with\n  `return_value_policy::take_ownership`.\n  [#3946](https://github.com/pybind/pybind11/pull/3946)\n- Fix cast from pytype rvalue to another pytype.\n  [#3949](https://github.com/pybind/pybind11/pull/3949)\n- Ensure proper behavior when garbage collecting classes with dynamic\n  attributes in Python \\>=3.9.\n  [#4051](https://github.com/pybind/pybind11/pull/4051)\n- A couple long-standing `PYBIND11_NAMESPACE`\n  `__attribute__((visibility(\"hidden\")))` inconsistencies are now fixed\n  (affects only unusual environments).\n  [#4043](https://github.com/pybind/pybind11/pull/4043)\n- `pybind11::detail::get_internals()` is now resilient to in-flight\n  Python exceptions.\n  [#3981](https://github.com/pybind/pybind11/pull/3981)\n- Arrays with a dimension of size 0 are now properly converted to\n  dynamic Eigen matrices (more common in NumPy 1.23).\n  [#4038](https://github.com/pybind/pybind11/pull/4038)\n- Avoid catching unrelated errors when importing NumPy.\n  [#3974](https://github.com/pybind/pybind11/pull/3974)\n\nPerformance and style:\n\n- Added an accessor overload of `(object &&key)` to reference steal the\n  object when using python types as keys. This prevents unnecessary\n  reference count overhead for attr, dictionary, tuple, and sequence\n  look ups. Added additional regression tests. Fixed a performance bug\n  the caused accessor assignments to potentially perform unnecessary\n  copies. [#3970](https://github.com/pybind/pybind11/pull/3970)\n- Perfect forward all args of `make_iterator`.\n  [#3980](https://github.com/pybind/pybind11/pull/3980)\n- Avoid potential bug in pycapsule destructor by adding an `error_guard`\n  to one of the dtors.\n  [#3958](https://github.com/pybind/pybind11/pull/3958)\n- Optimize dictionary access in `strip_padding` for numpy.\n  [#3994](https://github.com/pybind/pybind11/pull/3994)\n- `stl_bind.h` bindings now take slice args as a const-ref.\n  [#3852](https://github.com/pybind/pybind11/pull/3852)\n- Made slice constructor more consistent, and improve performance of\n  some casters by allowing reference stealing.\n  [#3845](https://github.com/pybind/pybind11/pull/3845)\n- Change numpy dtype from_args method to use const ref.\n  [#3878](https://github.com/pybind/pybind11/pull/3878)\n- Follow rule of three to ensure `PyErr_Restore` is called only once.\n  [#3872](https://github.com/pybind/pybind11/pull/3872)\n- Added missing perfect forwarding for `make_iterator` functions.\n  [#3860](https://github.com/pybind/pybind11/pull/3860)\n- Optimize c++ to python function casting by using the rvalue caster.\n  [#3966](https://github.com/pybind/pybind11/pull/3966)\n- Optimize Eigen sparse matrix casting by removing unnecessary\n  temporary. [#4064](https://github.com/pybind/pybind11/pull/4064)\n- Avoid potential implicit copy/assignment constructors causing double\n  free in `strdup_guard`.\n  [#3905](https://github.com/pybind/pybind11/pull/3905)\n- Enable clang-tidy checks `misc-definitions-in-headers`,\n  `modernize-loop-convert`, and `modernize-use-nullptr`.\n  [#3881](https://github.com/pybind/pybind11/pull/3881)\n  [#3988](https://github.com/pybind/pybind11/pull/3988)\n\nBuild system improvements:\n\n- CMake: Fix file extension on Windows with cp36 and cp37 using\n  FindPython. [#3919](https://github.com/pybind/pybind11/pull/3919)\n- CMake: Support multiple Python targets (such as on vcpkg).\n  [#3948](https://github.com/pybind/pybind11/pull/3948)\n- CMake: Fix issue with NVCC on Windows.\n  [#3947](https://github.com/pybind/pybind11/pull/3947)\n- CMake: Drop the bitness check on cross compiles (like targeting\n  WebAssembly via Emscripten).\n  [#3959](https://github.com/pybind/pybind11/pull/3959)\n- Add MSVC builds in debug mode to CI.\n  [#3784](https://github.com/pybind/pybind11/pull/3784)\n- MSVC 2022 C++20 coverage was added to GitHub Actions, including Eigen.\n  [#3732](https://github.com/pybind/pybind11/pull/3732),\n  [#3741](https://github.com/pybind/pybind11/pull/3741)\n\nBackend and tidying up:\n\n- New theme for the documentation.\n  [#3109](https://github.com/pybind/pybind11/pull/3109)\n- Remove idioms in code comments. Use more inclusive language.\n  [#3809](https://github.com/pybind/pybind11/pull/3809)\n- `#include <iostream>` was removed from the `pybind11/stl.h` header.\n  Your project may break if it has a transitive dependency on this\n  include. The fix is to \"Include What You Use\".\n  [#3928](https://github.com/pybind/pybind11/pull/3928)\n- Avoid `setup.py <command>` usage in internal tests.\n  [#3734](https://github.com/pybind/pybind11/pull/3734)\n\n## Version 2.9.2 (Mar 29, 2022)\n\nChanges:\n\n- Enum now has an `__index__` method on Python \\<3.8 too.\n  [#3700](https://github.com/pybind/pybind11/pull/3700)\n- Local internals are now cleared after finalizing the interpreter.\n  [#3744](https://github.com/pybind/pybind11/pull/3744)\n\nBug fixes:\n\n- Better support for Python 3.11 alphas.\n  [#3694](https://github.com/pybind/pybind11/pull/3694)\n- `PYBIND11_TYPE_CASTER` now uses fully qualified symbols, so it can be\n  used outside of `pybind11::detail`.\n  [#3758](https://github.com/pybind/pybind11/pull/3758)\n- Some fixes for PyPy 3.9.\n  [#3768](https://github.com/pybind/pybind11/pull/3768)\n- Fixed a potential memleak in PyPy in `get_type_override`.\n  [#3774](https://github.com/pybind/pybind11/pull/3774)\n- Fix usage of `VISIBILITY_INLINES_HIDDEN`.\n  [#3721](https://github.com/pybind/pybind11/pull/3721)\n\nBuild system improvements:\n\n- Uses `sysconfig` module to determine installation locations on Python\n  \\>= 3.10, instead of `distutils` which has been deprecated.\n  [#3764](https://github.com/pybind/pybind11/pull/3764)\n- Support Catch 2.13.5+ (supporting GLIBC 2.34+).\n  [#3679](https://github.com/pybind/pybind11/pull/3679)\n- Fix test failures with numpy 1.22 by ignoring whitespace when\n  comparing `str()` of dtypes.\n  [#3682](https://github.com/pybind/pybind11/pull/3682)\n\nBackend and tidying up:\n\n- clang-tidy: added `readability-qualified-auto`,\n  `readability-braces-around-statements`,\n  `cppcoreguidelines-prefer-member-initializer`,\n  `clang-analyzer-optin.performance.Padding`,\n  `cppcoreguidelines-pro-type-static-cast-downcast`, and\n  `readability-inconsistent-declaration-parameter-name`.\n  [#3702](https://github.com/pybind/pybind11/pull/3702),\n  [#3699](https://github.com/pybind/pybind11/pull/3699),\n  [#3716](https://github.com/pybind/pybind11/pull/3716),\n  [#3709](https://github.com/pybind/pybind11/pull/3709)\n- clang-format was added to the pre-commit actions, and the entire code\n  base automatically reformatted (after several iterations preparing for\n  this leap). [#3713](https://github.com/pybind/pybind11/pull/3713)\n\n## Version 2.9.1 (Feb 2, 2022)\n\nChanges:\n\n- If possible, attach Python exception with `py::raise_from` to\n  `TypeError` when casting from C++ to Python. This will give additional\n  info if Python exceptions occur in the caster. Adds a test case of\n  trying to convert a set from C++ to Python when the hash function is\n  not defined in Python.\n  [#3605](https://github.com/pybind/pybind11/pull/3605)\n- Add a mapping of C++11 nested exceptions to their Python exception\n  equivalent using `py::raise_from`. This attaches the nested exceptions\n  in Python using the `__cause__` field.\n  [#3608](https://github.com/pybind/pybind11/pull/3608)\n- Propagate Python exception traceback using `raise_from` if a pybind11\n  function runs out of overloads.\n  [#3671](https://github.com/pybind/pybind11/pull/3671)\n- `py::multiple_inheritance` is now only needed when C++ bases are\n  hidden from pybind11.\n  [#3650](https://github.com/pybind/pybind11/pull/3650) and\n  [#3659](https://github.com/pybind/pybind11/pull/3659)\n\nBug fixes:\n\n- Remove a boolean cast in `numpy.h` that causes MSVC C4800 warnings\n  when compiling against Python 3.10 or newer.\n  [#3669](https://github.com/pybind/pybind11/pull/3669)\n- Render `py::bool_` and `py::float_` as `bool` and `float`\n  respectively. [#3622](https://github.com/pybind/pybind11/pull/3622)\n\nBuild system improvements:\n\n- Fix CMake extension suffix computation on Python 3.10+.\n  [#3663](https://github.com/pybind/pybind11/pull/3663)\n- Allow `CMAKE_ARGS` to override CMake args in pybind11's own\n  `setup.py`. [#3577](https://github.com/pybind/pybind11/pull/3577)\n- Remove a few deprecated c-headers.\n  [#3610](https://github.com/pybind/pybind11/pull/3610)\n- More uniform handling of test targets.\n  [#3590](https://github.com/pybind/pybind11/pull/3590)\n- Add clang-tidy readability check to catch potentially swapped function\n  args. [#3611](https://github.com/pybind/pybind11/pull/3611)\n\n## Version 2.9.0 (Dec 28, 2021)\n\nThis is the last version to support Python 2.7 and 3.5.\n\nNew Features:\n\n- Allow `py::args` to be followed by other arguments; the remaining\n  arguments are implicitly keyword-only, as if a `py::kw_only{}`\n  annotation had been used.\n  [#3402](https://github.com/pybind/pybind11/pull/3402)\n\nChanges:\n\n- Make str/bytes/memoryview more interoperable with `std::string_view`.\n  [#3521](https://github.com/pybind/pybind11/pull/3521)\n- Replace `_` with `const_name` in internals, avoid defining `pybind::_`\n  if `_` defined as macro (common gettext usage)\n  [#3423](https://github.com/pybind/pybind11/pull/3423)\n\nBug fixes:\n\n- Fix a rare warning about extra copy in an Eigen constructor.\n  [#3486](https://github.com/pybind/pybind11/pull/3486)\n- Fix caching of the C++ overrides.\n  [#3465](https://github.com/pybind/pybind11/pull/3465)\n- Add missing `std::forward` calls to some `cpp_function` overloads.\n  [#3443](https://github.com/pybind/pybind11/pull/3443)\n- Support PyPy 7.3.7 and the PyPy3.8 beta. Test python-3.11 on PRs with\n  the `python dev` label.\n  [#3419](https://github.com/pybind/pybind11/pull/3419)\n- Replace usage of deprecated `Eigen::MappedSparseMatrix` with\n  `Eigen::Map<Eigen::SparseMatrix<...>>` for Eigen 3.3+.\n  [#3499](https://github.com/pybind/pybind11/pull/3499)\n- Tweaks to support Microsoft Visual Studio 2022.\n  [#3497](https://github.com/pybind/pybind11/pull/3497)\n\nBuild system improvements:\n\n- Nicer CMake printout and IDE organisation for pybind11's own tests.\n  [#3479](https://github.com/pybind/pybind11/pull/3479)\n- CMake: report version type as part of the version string to avoid a\n  spurious space in the package status message.\n  [#3472](https://github.com/pybind/pybind11/pull/3472)\n- Flags starting with `-g` in `$CFLAGS` and `$CPPFLAGS` are no longer\n  overridden by `.Pybind11Extension`.\n  [#3436](https://github.com/pybind/pybind11/pull/3436)\n- Ensure ThreadPool is closed in `setup_helpers`.\n  [#3548](https://github.com/pybind/pybind11/pull/3548)\n- Avoid LTS on `mips64` and `ppc64le` (reported broken).\n  [#3557](https://github.com/pybind/pybind11/pull/3557)\n\n## v2.8.1 (Oct 27, 2021)\n\nChanges and additions:\n\n- The simple namespace creation shortcut added in 2.8.0 was deprecated\n  due to usage of CPython internal API, and will be removed soon. Use\n  `py::module_::import(\"types\").attr(\"SimpleNamespace\")`.\n  [#3374](https://github.com/pybinyyd/pybind11/pull/3374)\n- Add C++ Exception type to throw and catch `AttributeError`. Useful for\n  defining custom `__setattr__` and `__getattr__` methods.\n  [#3387](https://github.com/pybind/pybind11/pull/3387)\n\nFixes:\n\n- Fixed the potential for dangling references when using properties with\n  `std::optional` types.\n  [#3376](https://github.com/pybind/pybind11/pull/3376)\n- Modernize usage of `PyCodeObject` on Python 3.9+ (moving toward\n  support for Python 3.11a1)\n  [#3368](https://github.com/pybind/pybind11/pull/3368)\n- A long-standing bug in `eigen.h` was fixed (originally PR \\#3343). The\n  bug was unmasked by newly added `static_assert`'s in the Eigen 3.4.0\n  release. [#3352](https://github.com/pybind/pybind11/pull/3352)\n- Support multiple raw inclusion of CMake helper files (Conan.io does\n  this for multi-config generators).\n  [#3420](https://github.com/pybind/pybind11/pull/3420)\n- Fix harmless warning on upcoming CMake 3.22.\n  [#3368](https://github.com/pybind/pybind11/pull/3368)\n- Fix 2.8.0 regression with MSVC 2017 + C++17 mode + Python 3.\n  [#3407](https://github.com/pybind/pybind11/pull/3407)\n- Fix 2.8.0 regression that caused undefined behavior (typically\n  segfaults) in `make_key_iterator`/`make_value_iterator` if\n  dereferencing the iterator returned a temporary value instead of a\n  reference. [#3348](https://github.com/pybind/pybind11/pull/3348)\n\n## v2.8.0 (Oct 4, 2021)\n\nNew features:\n\n- Added `py::raise_from` to enable chaining exceptions.\n  [#3215](https://github.com/pybind/pybind11/pull/3215)\n- Allow exception translators to be optionally registered local to a\n  module instead of applying globally across all pybind11 modules. Use\n  `register_local_exception_translator(ExceptionTranslator&& translator)`\n  instead of\n  `register_exception_translator(ExceptionTranslator&& translator)` to\n  keep your exception remapping code local to the module.\n  [#2650](https://github.com/pybinyyd/pybind11/pull/2650)\n- Add `make_simple_namespace` function for instantiating Python\n  `SimpleNamespace` objects. **Deprecated in 2.8.1.**\n  [#2840](https://github.com/pybind/pybind11/pull/2840)\n- `pybind11::scoped_interpreter` and `initialize_interpreter` have new\n  arguments to allow `sys.argv` initialization.\n  [#2341](https://github.com/pybind/pybind11/pull/2341)\n- Allow Python builtins to be used as callbacks in CPython.\n  [#1413](https://github.com/pybind/pybind11/pull/1413)\n- Added `view` to view arrays with a different datatype.\n  [#987](https://github.com/pybind/pybind11/pull/987)\n- Implemented `reshape` on arrays.\n  [#984](https://github.com/pybind/pybind11/pull/984)\n- Enable defining custom `__new__` methods on classes by fixing bug\n  preventing overriding methods if they have non-pybind11 siblings.\n  [#3265](https://github.com/pybind/pybind11/pull/3265)\n- Add `make_value_iterator()`, and fix `make_key_iterator()` to return\n  references instead of copies.\n  [#3293](https://github.com/pybind/pybind11/pull/3293)\n- Improve the classes generated by `bind_map`:\n  [#3310](https://github.com/pybind/pybind11/pull/3310)\n  - Change `.items` from an iterator to a dictionary view.\n  - Add `.keys` and `.values` (both dictionary views).\n  - Allow `__contains__` to take any object.\n- `pybind11::custom_type_setup` was added, for customizing the\n  `PyHeapTypeObject` corresponding to a class, which may be useful for\n  enabling garbage collection support, among other things.\n  [#3287](https://github.com/pybind/pybind11/pull/3287)\n\nChanges:\n\n- Set `__file__` constant when running `eval_file` in an embedded\n  interpreter. [#3233](https://github.com/pybind/pybind11/pull/3233)\n- Python objects and (C++17) `std::optional` now accepted in `py::slice`\n  constructor. [#1101](https://github.com/pybind/pybind11/pull/1101)\n- The pybind11 proxy types `str`, `bytes`, `bytearray`, `tuple`, `list`\n  now consistently support passing `ssize_t` values for sizes and\n  indexes. Previously, only `size_t` was accepted in several interfaces.\n  [#3219](https://github.com/pybind/pybind11/pull/3219)\n- Avoid evaluating `PYBIND11_TLS_REPLACE_VALUE` arguments more than\n  once. [#3290](https://github.com/pybind/pybind11/pull/3290)\n\nFixes:\n\n- Bug fix: enum value's `__int__` returning non-int when underlying type\n  is bool or of char type.\n  [#1334](https://github.com/pybind/pybind11/pull/1334)\n- Fixes bug in setting error state in Capsule's pointer methods.\n  [#3261](https://github.com/pybind/pybind11/pull/3261)\n- A long-standing memory leak in `py::cpp_function::initialize` was\n  fixed. [#3229](https://github.com/pybind/pybind11/pull/3229)\n- Fixes thread safety for some `pybind11::type_caster` which require\n  lifetime extension, such as for `std::string_view`.\n  [#3237](https://github.com/pybind/pybind11/pull/3237)\n- Restore compatibility with gcc 4.8.4 as distributed by ubuntu-trusty,\n  linuxmint-17. [#3270](https://github.com/pybind/pybind11/pull/3270)\n\nBuild system improvements:\n\n- Fix regression in CMake Python package config: improper use of\n  absolute path. [#3144](https://github.com/pybind/pybind11/pull/3144)\n- Cached Python version information could become stale when CMake was\n  re-run with a different Python version. The build system now detects\n  this and updates this information.\n  [#3299](https://github.com/pybind/pybind11/pull/3299)\n- Specified UTF8-encoding in setup.py calls of open().\n  [#3137](https://github.com/pybind/pybind11/pull/3137)\n- Fix a harmless warning from CMake 3.21 with the classic Python\n  discovery. [#3220](https://github.com/pybind/pybind11/pull/3220)\n- Eigen repo and version can now be specified as cmake options.\n  [#3324](https://github.com/pybind/pybind11/pull/3324)\n\nBackend and tidying up:\n\n- Reduced thread-local storage required for keeping alive temporary data\n  for type conversion to one key per ABI version, rather than one key\n  per extension module. This makes the total thread-local storage\n  required by pybind11 2 keys per ABI version.\n  [#3275](https://github.com/pybind/pybind11/pull/3275)\n- Optimize NumPy array construction with additional moves.\n  [#3183](https://github.com/pybind/pybind11/pull/3183)\n- Conversion to `std::string` and `std::string_view` now avoids making\n  an extra copy of the data on Python \\>= 3.3.\n  [#3257](https://github.com/pybind/pybind11/pull/3257)\n- Remove const modifier from certain C++ methods on Python collections\n  (`list`, `set`, `dict`) such as (`clear()`, `append()`, `insert()`,\n  etc...) and annotated them with `py-non-const`.\n- Enable readability `clang-tidy-const-return` and remove useless\n  consts. [#3254](https://github.com/pybind/pybind11/pull/3254)\n  [#3194](https://github.com/pybind/pybind11/pull/3194)\n- The clang-tidy `google-explicit-constructor` option was enabled.\n  [#3250](https://github.com/pybind/pybind11/pull/3250)\n- Mark a pytype move constructor as noexcept (perf).\n  [#3236](https://github.com/pybind/pybind11/pull/3236)\n- Enable clang-tidy check to guard against inheritance slicing.\n  [#3210](https://github.com/pybind/pybind11/pull/3210)\n- Legacy warning suppression pragma were removed from eigen.h. On Unix\n  platforms, please use -isystem for Eigen include directories, to\n  suppress compiler warnings originating from Eigen headers. Note that\n  CMake does this by default. No adjustments are needed for Windows.\n  [#3198](https://github.com/pybind/pybind11/pull/3198)\n- Format pybind11 with isort consistent ordering of imports\n  [#3195](https://github.com/pybind/pybind11/pull/3195)\n- The warnings-suppression \"pragma clamp\" at the top/bottom of pybind11\n  was removed, clearing the path to refactoring and IWYU cleanup.\n  [#3186](https://github.com/pybind/pybind11/pull/3186)\n- Enable most bugprone checks in clang-tidy and fix the found potential\n  bugs and poor coding styles.\n  [#3166](https://github.com/pybind/pybind11/pull/3166)\n- Add `clang-tidy-readability` rules to make boolean casts explicit\n  improving code readability. Also enabled other misc and readability\n  clang-tidy checks.\n  [#3148](https://github.com/pybind/pybind11/pull/3148)\n- Move object in `.pop()` for list.\n  [#3116](https://github.com/pybind/pybind11/pull/3116)\n\n## v2.7.1 (Aug 3, 2021)\n\nMinor missing functionality added:\n\n- Allow Python builtins to be used as callbacks in CPython.\n  [#1413](https://github.com/pybind/pybind11/pull/1413)\n\nBug fixes:\n\n- Fix regression in CMake Python package config: improper use of\n  absolute path. [#3144](https://github.com/pybind/pybind11/pull/3144)\n- Fix Mingw64 and add to the CI testing matrix.\n  [#3132](https://github.com/pybind/pybind11/pull/3132)\n- Specified UTF8-encoding in setup.py calls of open().\n  [#3137](https://github.com/pybind/pybind11/pull/3137)\n- Add clang-tidy-readability rules to make boolean casts explicit\n  improving code readability. Also enabled other misc and readability\n  clang-tidy checks.\n  [#3148](https://github.com/pybind/pybind11/pull/3148)\n- Move object in `.pop()` for list.\n  [#3116](https://github.com/pybind/pybind11/pull/3116)\n\nBackend and tidying up:\n\n- Removed and fixed warning suppressions.\n  [#3127](https://github.com/pybind/pybind11/pull/3127)\n  [#3129](https://github.com/pybind/pybind11/pull/3129)\n  [#3135](https://github.com/pybind/pybind11/pull/3135)\n  [#3141](https://github.com/pybind/pybind11/pull/3141)\n  [#3142](https://github.com/pybind/pybind11/pull/3142)\n  [#3150](https://github.com/pybind/pybind11/pull/3150)\n  [#3152](https://github.com/pybind/pybind11/pull/3152)\n  [#3160](https://github.com/pybind/pybind11/pull/3160)\n  [#3161](https://github.com/pybind/pybind11/pull/3161)\n\n## v2.7.0 (Jul 16, 2021)\n\nNew features:\n\n- Enable `py::implicitly_convertible<py::none, ...>` for\n  `py::class_`-wrapped types.\n  [#3059](https://github.com/pybind/pybind11/pull/3059)\n- Allow function pointer extraction from overloaded functions.\n  [#2944](https://github.com/pybind/pybind11/pull/2944)\n- NumPy: added `.char_()` to type which gives the NumPy public `char`\n  result, which also distinguishes types by bit length (unlike\n  `.kind()`). [#2864](https://github.com/pybind/pybind11/pull/2864)\n- Add `pybind11::bytearray` to manipulate `bytearray` similar to\n  `bytes`. [#2799](https://github.com/pybind/pybind11/pull/2799)\n- `pybind11/stl/filesystem.h` registers a type caster that, on\n  C++17/Python 3.6+, converts `std::filesystem::path` to `pathlib.Path`\n  and any `os.PathLike` to `std::filesystem::path`.\n  [#2730](https://github.com/pybind/pybind11/pull/2730)\n- A `PYBIND11_VERSION_HEX` define was added, similar to\n  `PY_VERSION_HEX`.\n  [#3120](https://github.com/pybind/pybind11/pull/3120)\n\nChanges:\n\n- `py::str` changed to exclusively hold `PyUnicodeObject`. Previously\n  `py::str` could also hold `bytes`, which is probably surprising, was\n  never documented, and can mask bugs (e.g. accidental use of `py::str`\n  instead of `py::bytes`).\n  [#2409](https://github.com/pybind/pybind11/pull/2409)\n- Add a safety guard to ensure that the Python GIL is held when C++\n  calls back into Python via `object_api<>::operator()` (e.g.\n  `py::function` `__call__`). (This feature is available for Python 3.6+\n  only.) [#2919](https://github.com/pybind/pybind11/pull/2919)\n- Catch a missing `self` argument in calls to `__init__()`.\n  [#2914](https://github.com/pybind/pybind11/pull/2914)\n- Use `std::string_view` if available to avoid a copy when passing an\n  object to a `std::ostream`.\n  [#3042](https://github.com/pybind/pybind11/pull/3042)\n- An important warning about thread safety was added to the `iostream.h`\n  documentation; attempts to make `py::scoped_ostream_redirect` thread\n  safe have been removed, as it was only partially effective.\n  [#2995](https://github.com/pybind/pybind11/pull/2995)\n\nFixes:\n\n- Performance: avoid unnecessary strlen calls.\n  [#3058](https://github.com/pybind/pybind11/pull/3058)\n- Fix auto-generated documentation string when using `const T` in\n  `pyarray_t`. [#3020](https://github.com/pybind/pybind11/pull/3020)\n- Unify error messages thrown by\n  `simple_collector`/`unpacking_collector`.\n  [#3013](https://github.com/pybind/pybind11/pull/3013)\n- `pybind11::builtin_exception` is now explicitly exported, which means\n  the types included/defined in different modules are identical, and\n  exceptions raised in different modules can be caught correctly. The\n  documentation was updated to explain that custom exceptions that are\n  used across module boundaries need to be explicitly exported as well.\n  [#2999](https://github.com/pybind/pybind11/pull/2999)\n- Fixed exception when printing UTF-8 to a `scoped_ostream_redirect`.\n  [#2982](https://github.com/pybind/pybind11/pull/2982)\n- Pickle support enhancement: `setstate` implementation will attempt to\n  `setattr` `__dict__` only if the unpickled `dict` object is not empty,\n  to not force use of `py::dynamic_attr()` unnecessarily.\n  [#2972](https://github.com/pybind/pybind11/pull/2972)\n- Allow negative timedelta values to roundtrip.\n  [#2870](https://github.com/pybind/pybind11/pull/2870)\n- Fix unchecked errors could potentially swallow signals/other\n  exceptions. [#2863](https://github.com/pybind/pybind11/pull/2863)\n- Add null pointer check with `std::localtime`.\n  [#2846](https://github.com/pybind/pybind11/pull/2846)\n- Fix the `weakref` constructor from `py::object` to create a new\n  `weakref` on conversion.\n  [#2832](https://github.com/pybind/pybind11/pull/2832)\n- Avoid relying on exceptions in C++17 when getting a `shared_ptr`\n  holder from a `shared_from_this` class.\n  [#2819](https://github.com/pybind/pybind11/pull/2819)\n- Allow the codec's exception to be raised instead of `RuntimeError`\n  when casting from `py::str` to `std::string`.\n  [#2903](https://github.com/pybind/pybind11/pull/2903)\n\nBuild system improvements:\n\n- In `setup_helpers.py`, test for platforms that have some\n  multiprocessing features but lack semaphores, which `ParallelCompile`\n  requires. [#3043](https://github.com/pybind/pybind11/pull/3043)\n- Fix `pybind11_INCLUDE_DIR` in case `CMAKE_INSTALL_INCLUDEDIR` is\n  absolute. [#3005](https://github.com/pybind/pybind11/pull/3005)\n- Fix bug not respecting `WITH_SOABI` or `WITHOUT_SOABI` to CMake.\n  [#2938](https://github.com/pybind/pybind11/pull/2938)\n- Fix the default `Pybind11Extension` compilation flags with a Mingw64\n  python. [#2921](https://github.com/pybind/pybind11/pull/2921)\n- Clang on Windows: do not pass `/MP` (ignored flag).\n  [#2824](https://github.com/pybind/pybind11/pull/2824)\n- `pybind11.setup_helpers.intree_extensions` can be used to generate\n  `Pybind11Extension` instances from cpp files placed in the Python\n  package source tree.\n  [#2831](https://github.com/pybind/pybind11/pull/2831)\n\nBackend and tidying up:\n\n- Enable clang-tidy performance, readability, and modernization checks\n  throughout the codebase to enforce best coding practices.\n  [#3046](https://github.com/pybind/pybind11/pull/3046),\n  [#3049](https://github.com/pybind/pybind11/pull/3049),\n  [#3051](https://github.com/pybind/pybind11/pull/3051),\n  [#3052](https://github.com/pybind/pybind11/pull/3052),\n  [#3080](https://github.com/pybind/pybind11/pull/3080), and\n  [#3094](https://github.com/pybind/pybind11/pull/3094)\n- Checks for common misspellings were added to the pre-commit hooks.\n  [#3076](https://github.com/pybind/pybind11/pull/3076)\n- Changed `Werror` to stricter `Werror-all` for Intel compiler and fixed\n  minor issues. [#2948](https://github.com/pybind/pybind11/pull/2948)\n- Fixed compilation with GCC \\< 5 when the user defines\n  `_GLIBCXX_USE_CXX11_ABI`.\n  [#2956](https://github.com/pybind/pybind11/pull/2956)\n- Added nox support for easier local testing and linting of\n  contributions. [#3101](https://github.com/pybind/pybind11/pull/3101)\n  and [#3121](https://github.com/pybind/pybind11/pull/3121)\n- Avoid RTD style issue with docutils 0.17+.\n  [#3119](https://github.com/pybind/pybind11/pull/3119)\n- Support pipx run, such as `pipx run pybind11 --include` for a quick\n  compile. [#3117](https://github.com/pybind/pybind11/pull/3117)\n\n## v2.6.2 (Jan 26, 2021)\n\nMinor missing functionality added:\n\n- enum: add missing Enum.value property.\n  [#2739](https://github.com/pybind/pybind11/pull/2739)\n- Allow thread termination to be avoided during shutdown for CPython\n  3.7+ via `.disarm` for `gil_scoped_acquire`/`gil_scoped_release`.\n  [#2657](https://github.com/pybind/pybind11/pull/2657)\n\nFixed or improved behavior in a few special cases:\n\n- Fix bug where the constructor of `object` subclasses would not throw\n  on being passed a Python object of the wrong type.\n  [#2701](https://github.com/pybind/pybind11/pull/2701)\n- The `type_caster` for integers does not convert Python objects with\n  `__int__` anymore with `noconvert` or during the first round of trying\n  overloads. [#2698](https://github.com/pybind/pybind11/pull/2698)\n- When casting to a C++ integer, `__index__` is always called and not\n  considered as conversion, consistent with Python 3.8+.\n  [#2801](https://github.com/pybind/pybind11/pull/2801)\n\nBuild improvements:\n\n- Setup helpers: `extra_compile_args` and `extra_link_args`\n  automatically set by Pybind11Extension are now prepended, which allows\n  them to be overridden by user-set `extra_compile_args` and\n  `extra_link_args`.\n  [#2808](https://github.com/pybind/pybind11/pull/2808)\n- Setup helpers: Don't trigger unused parameter warning.\n  [#2735](https://github.com/pybind/pybind11/pull/2735)\n- CMake: Support running with `--warn-uninitialized` active.\n  [#2806](https://github.com/pybind/pybind11/pull/2806)\n- CMake: Avoid error if included from two submodule directories.\n  [#2804](https://github.com/pybind/pybind11/pull/2804)\n- CMake: Fix `STATIC` / `SHARED` being ignored in FindPython mode.\n  [#2796](https://github.com/pybind/pybind11/pull/2796)\n- CMake: Respect the setting for `CMAKE_CXX_VISIBILITY_PRESET` if\n  defined. [#2793](https://github.com/pybind/pybind11/pull/2793)\n- CMake: Fix issue with FindPython2/FindPython3 not working with\n  `pybind11::embed`.\n  [#2662](https://github.com/pybind/pybind11/pull/2662)\n- CMake: mixing local and installed pybind11's would prioritize the\n  installed one over the local one (regression in 2.6.0).\n  [#2716](https://github.com/pybind/pybind11/pull/2716)\n\nBug fixes:\n\n- Fixed segfault in multithreaded environments when using\n  `scoped_ostream_redirect`.\n  [#2675](https://github.com/pybind/pybind11/pull/2675)\n- Leave docstring unset when all docstring-related options are disabled,\n  rather than set an empty string.\n  [#2745](https://github.com/pybind/pybind11/pull/2745)\n- The module key in builtins that pybind11 uses to store its internals\n  changed from std::string to a python str type (more natural on Python\n  2, no change on Python 3).\n  [#2814](https://github.com/pybind/pybind11/pull/2814)\n- Fixed assertion error related to unhandled (later overwritten)\n  exception in CPython 3.8 and 3.9 debug builds.\n  [#2685](https://github.com/pybind/pybind11/pull/2685)\n- Fix `py::gil_scoped_acquire` assert with CPython 3.9 debug build.\n  [#2683](https://github.com/pybind/pybind11/pull/2683)\n- Fix issue with a test failing on pytest 6.2.\n  [#2741](https://github.com/pybind/pybind11/pull/2741)\n\nWarning fixes:\n\n- Fix warning modifying constructor parameter 'flag' that shadows a\n  field of 'set_flag' `[-Wshadow-field-in-constructor-modified]`.\n  [#2780](https://github.com/pybind/pybind11/pull/2780)\n- Suppressed some deprecation warnings about old-style\n  `__init__`/`__setstate__` in the tests.\n  [#2759](https://github.com/pybind/pybind11/pull/2759)\n\nValgrind work:\n\n- Fix invalid access when calling a pybind11 `__init__` on a\n  non-pybind11 class instance.\n  [#2755](https://github.com/pybind/pybind11/pull/2755)\n- Fixed various minor memory leaks in pybind11's test suite.\n  [#2758](https://github.com/pybind/pybind11/pull/2758)\n- Resolved memory leak in cpp_function initialization when exceptions\n  occurred. [#2756](https://github.com/pybind/pybind11/pull/2756)\n- Added a Valgrind build, checking for leaks and memory-related UB,\n  to CI. [#2746](https://github.com/pybind/pybind11/pull/2746)\n\nCompiler support:\n\n- Intel compiler was not activating C++14 support due to a broken\n  define. [#2679](https://github.com/pybind/pybind11/pull/2679)\n- Support ICC and NVIDIA HPC SDK in C++17 mode.\n  [#2729](https://github.com/pybind/pybind11/pull/2729)\n- Support Intel OneAPI compiler (ICC 20.2) and add to CI.\n  [#2573](https://github.com/pybind/pybind11/pull/2573)\n\n## v2.6.1 (Nov 11, 2020)\n\n- `py::exec`, `py::eval`, and `py::eval_file` now add the builtins\n  module as `\"__builtins__\"` to their `globals` argument, better\n  matching `exec` and `eval` in pure Python.\n  [#2616](https://github.com/pybind/pybind11/pull/2616)\n- `setup_helpers` will no longer set a minimum macOS version higher than\n  the current version.\n  [#2622](https://github.com/pybind/pybind11/pull/2622)\n- Allow deleting static properties.\n  [#2629](https://github.com/pybind/pybind11/pull/2629)\n- Seal a leak in `def_buffer`, cleaning up the `capture` object after\n  the `class_` object goes out of scope.\n  [#2634](https://github.com/pybind/pybind11/pull/2634)\n- `pybind11_INCLUDE_DIRS` was incorrect, potentially causing a\n  regression if it was expected to include `PYTHON_INCLUDE_DIRS` (please\n  use targets instead).\n  [#2636](https://github.com/pybind/pybind11/pull/2636)\n- Added parameter names to the `py::enum_` constructor and methods,\n  avoiding `arg0` in the generated docstrings.\n  [#2637](https://github.com/pybind/pybind11/pull/2637)\n- Added `needs_recompile` optional function to the `ParallelCompiler`\n  helper, to allow a recompile to be skipped based on a user-defined\n  function. [#2643](https://github.com/pybind/pybind11/pull/2643)\n\n## v2.6.0 (Oct 21, 2020)\n\nSee `upgrade-guide-2.6` for help upgrading to the new version.\n\nNew features:\n\n- Keyword-only arguments supported in Python 2 or 3 with\n  `py::kw_only()`.\n  [#2100](https://github.com/pybind/pybind11/pull/2100)\n- Positional-only arguments supported in Python 2 or 3 with\n  `py::pos_only()`.\n  [#2459](https://github.com/pybind/pybind11/pull/2459)\n- `py::is_final()` class modifier to block subclassing (CPython only).\n  [#2151](https://github.com/pybind/pybind11/pull/2151)\n- Added `py::prepend()`, allowing a function to be placed at the\n  beginning of the overload chain.\n  [#1131](https://github.com/pybind/pybind11/pull/1131)\n- Access to the type object now provided with `py::type::of<T>()` and\n  `py::type::of(h)`.\n  [#2364](https://github.com/pybind/pybind11/pull/2364)\n- Perfect forwarding support for methods.\n  [#2048](https://github.com/pybind/pybind11/pull/2048)\n- Added `py::error_already_set::discard_as_unraisable()`.\n  [#2372](https://github.com/pybind/pybind11/pull/2372)\n- `py::hash` is now public.\n  [#2217](https://github.com/pybind/pybind11/pull/2217)\n- `py::class_<union_type>` is now supported. Note that writing to one\n  data member of the union and reading another (type punning) is UB in\n  C++. Thus pybind11-bound enums should never be used for such\n  conversions. [#2320](https://github.com/pybind/pybind11/pull/2320).\n- Classes now check local scope when registering members, allowing a\n  subclass to have a member with the same name as a parent (such as an\n  enum). [#2335](https://github.com/pybind/pybind11/pull/2335)\n\nCode correctness features:\n\n- Error now thrown when `__init__` is forgotten on subclasses.\n  [#2152](https://github.com/pybind/pybind11/pull/2152)\n- Throw error if conversion to a pybind11 type if the Python object\n  isn't a valid instance of that type, such as `py::bytes(o)` when\n  `py::object o` isn't a bytes instance.\n  [#2349](https://github.com/pybind/pybind11/pull/2349)\n- Throw if conversion to `str` fails.\n  [#2477](https://github.com/pybind/pybind11/pull/2477)\n\nAPI changes:\n\n- `py::module` was renamed `py::module_` to avoid issues with C++20 when\n  used unqualified, but an alias `py::module` is provided for backward\n  compatibility. [#2489](https://github.com/pybind/pybind11/pull/2489)\n- Public constructors for `py::module_` have been deprecated; please use\n  `pybind11::module_::create_extension_module` if you were using the\n  public constructor (fairly rare after `PYBIND11_MODULE` was\n  introduced). [#2552](https://github.com/pybind/pybind11/pull/2552)\n- `PYBIND11_OVERLOAD*` macros and `get_overload` function replaced by\n  correctly-named `PYBIND11_OVERRIDE*` and `get_override`, fixing\n  inconsistencies in the presence of a closing `;` in these macros.\n  `get_type_overload` is deprecated.\n  [#2325](https://github.com/pybind/pybind11/pull/2325)\n\nPackaging / building improvements:\n\n- The Python package was reworked to be more powerful and useful.\n  [#2433](https://github.com/pybind/pybind11/pull/2433)\n  - `build-setuptools` is easier thanks to a new\n    `pybind11.setup_helpers` module, which provides utilities to use\n    setuptools with pybind11. It can be used via PEP 518,\n    `setup_requires`, or by directly importing or copying\n    `setup_helpers.py` into your project.\n  - CMake configuration files are now included in the Python package.\n    Use `pybind11.get_cmake_dir()` or `python -m pybind11 --cmakedir` to\n    get the directory with the CMake configuration files, or include the\n    site-packages location in your `CMAKE_MODULE_PATH`. Or you can use\n    the new `pybind11[global]` extra when you install `pybind11`, which\n    installs the CMake files and headers into your base environment in\n    the standard location.\n  - `pybind11-config` is another way to write `python -m pybind11` if\n    you have your PATH set up.\n  - Added external typing support to the helper module, code from\n    `import pybind11` can now be type checked.\n    [#2588](https://github.com/pybind/pybind11/pull/2588)\n- Minimum CMake required increased to 3.4.\n  [#2338](https://github.com/pybind/pybind11/pull/2338) and\n  [#2370](https://github.com/pybind/pybind11/pull/2370)\n  - Full integration with CMake's C++ standard system and compile\n    features replaces `PYBIND11_CPP_STANDARD`.\n  - Generated config file is now portable to different\n    Python/compiler/CMake versions.\n  - Virtual environments prioritized if `PYTHON_EXECUTABLE` is not set\n    (`venv`, `virtualenv`, and `conda`) (similar to the new FindPython\n    mode).\n  - Other CMake features now natively supported, like\n    `CMAKE_INTERPROCEDURAL_OPTIMIZATION`,\n    `set(CMAKE_CXX_VISIBILITY_PRESET hidden)`.\n  - `CUDA` as a language is now supported.\n  - Helper functions `pybind11_strip`, `pybind11_extension`,\n    `pybind11_find_import` added, see `cmake/index`.\n  - Optional `find-python-mode` and `nopython-mode` with CMake.\n    [#2370](https://github.com/pybind/pybind11/pull/2370)\n- Uninstall target added.\n  [#2265](https://github.com/pybind/pybind11/pull/2265) and\n  [#2346](https://github.com/pybind/pybind11/pull/2346)\n- `pybind11_add_module()` now accepts an optional `OPT_SIZE` flag that\n  switches the binding target to size-based optimization if the global\n  build type can not always be fixed to `MinSizeRel` (except in debug\n  mode, where optimizations remain disabled). `MinSizeRel` or this flag\n  reduces binary size quite substantially (~25% on some platforms).\n  [#2463](https://github.com/pybind/pybind11/pull/2463)\n\nSmaller or developer focused features and fixes:\n\n- Moved `mkdoc.py` to a new repo,\n  [pybind11-mkdoc](https://github.com/pybind/pybind11-mkdoc). There are\n  no longer submodules in the main repo.\n- `py::memoryview` segfault fix and update, with new\n  `py::memoryview::from_memory` in Python 3, and documentation.\n  [#2223](https://github.com/pybind/pybind11/pull/2223)\n- Fix for `buffer_info` on Python 2.\n  [#2503](https://github.com/pybind/pybind11/pull/2503)\n- If `__eq__` defined but not `__hash__`, `__hash__` is now set to\n  `None`. [#2291](https://github.com/pybind/pybind11/pull/2291)\n- `py::ellipsis` now also works on Python 2.\n  [#2360](https://github.com/pybind/pybind11/pull/2360)\n- Pointer to `std::tuple` & `std::pair` supported in cast.\n  [#2334](https://github.com/pybind/pybind11/pull/2334)\n- Small fixes in NumPy support. `py::array` now uses `py::ssize_t` as\n  first argument type.\n  [#2293](https://github.com/pybind/pybind11/pull/2293)\n- Added missing signature for `py::array`.\n  [#2363](https://github.com/pybind/pybind11/pull/2363)\n- `unchecked_mutable_reference` has access to operator `()` and `[]`\n  when const. [#2514](https://github.com/pybind/pybind11/pull/2514)\n- `py::vectorize` is now supported on functions that return void.\n  [#1969](https://github.com/pybind/pybind11/pull/1969)\n- `py::capsule` supports `get_pointer` and `set_pointer`.\n  [#1131](https://github.com/pybind/pybind11/pull/1131)\n- Fix crash when different instances share the same pointer of the same\n  type. [#2252](https://github.com/pybind/pybind11/pull/2252)\n- Fix for `py::len` not clearing Python's error state when it fails and\n  throws. [#2575](https://github.com/pybind/pybind11/pull/2575)\n- Bugfixes related to more extensive testing, new GitHub Actions CI.\n  [#2321](https://github.com/pybind/pybind11/pull/2321)\n- Bug in timezone issue in Eastern hemisphere midnight fixed.\n  [#2438](https://github.com/pybind/pybind11/pull/2438)\n- `std::chrono::time_point` now works when the resolution is not the\n  same as the system.\n  [#2481](https://github.com/pybind/pybind11/pull/2481)\n- Bug fixed where `py::array_t` could accept arrays that did not match\n  the requested ordering.\n  [#2484](https://github.com/pybind/pybind11/pull/2484)\n- Avoid a segfault on some compilers when types are removed in Python.\n  [#2564](https://github.com/pybind/pybind11/pull/2564)\n- `py::arg::none()` is now also respected when passing keyword\n  arguments. [#2611](https://github.com/pybind/pybind11/pull/2611)\n- PyPy fixes, PyPy 7.3.x now supported, including PyPy3. (Known issue\n  with PyPy2 and Windows\n  [#2596](https://github.com/pybind/pybind11/issues/2596)).\n  [#2146](https://github.com/pybind/pybind11/pull/2146)\n- CPython 3.9.0 workaround for undefined behavior (macOS segfault).\n  [#2576](https://github.com/pybind/pybind11/pull/2576)\n- CPython 3.9 warning fixes.\n  [#2253](https://github.com/pybind/pybind11/pull/2253)\n- Improved C++20 support, now tested in CI.\n  [#2489](https://github.com/pybind/pybind11/pull/2489)\n  [#2599](https://github.com/pybind/pybind11/pull/2599)\n- Improved but still incomplete debug Python interpreter support.\n  [#2025](https://github.com/pybind/pybind11/pull/2025)\n- NVCC (CUDA 11) now supported and tested in CI.\n  [#2461](https://github.com/pybind/pybind11/pull/2461)\n- NVIDIA PGI compilers now supported and tested in CI.\n  [#2475](https://github.com/pybind/pybind11/pull/2475)\n- At least Intel 18 now explicitly required when compiling with Intel.\n  [#2577](https://github.com/pybind/pybind11/pull/2577)\n- Extensive style checking in CI, with\n  [pre-commit](https://pre-commit.com) support. Code modernization,\n  checked by clang-tidy.\n- Expanded docs, including new main page, new installing section, and\n  CMake helpers page, along with over a dozen new sections on existing\n  pages.\n- In GitHub, new docs for contributing and new issue templates.\n\n## v2.5.0 (Mar 31, 2020)\n\n- Use C++17 fold expressions in type casters, if available. This can\n  improve performance during overload resolution when functions have\n  multiple arguments.\n  [#2043](https://github.com/pybind/pybind11/pull/2043).\n- Changed include directory resolution in `pybind11/__init__.py` and\n  installation in `setup.py`. This fixes a number of open issues where\n  pybind11 headers could not be found in certain environments.\n  [#1995](https://github.com/pybind/pybind11/pull/1995).\n- C++20 `char8_t` and `u8string` support.\n  [#2026](https://github.com/pybind/pybind11/pull/2026).\n- CMake: search for Python 3.9.\n  [bb9c91](https://github.com/pybind/pybind11/commit/bb9c91).\n- Fixes for MSYS-based build environments.\n  [#2087](https://github.com/pybind/pybind11/pull/2087),\n  [#2053](https://github.com/pybind/pybind11/pull/2053).\n- STL bindings for `std::vector<...>::clear`.\n  [#2074](https://github.com/pybind/pybind11/pull/2074).\n- Read-only flag for `py::buffer`.\n  [#1466](https://github.com/pybind/pybind11/pull/1466).\n- Exception handling during module initialization.\n  [bf2b031](https://github.com/pybind/pybind11/commit/bf2b031).\n- Support linking against a CPython debug build.\n  [#2025](https://github.com/pybind/pybind11/pull/2025).\n- Fixed issues involving the availability and use of aligned `new` and\n  `delete`. [#1988](https://github.com/pybind/pybind11/pull/1988),\n  [759221](https://github.com/pybind/pybind11/commit/759221).\n- Fixed a resource leak upon interpreter shutdown.\n  [#2020](https://github.com/pybind/pybind11/pull/2020).\n- Fixed error handling in the boolean caster.\n  [#1976](https://github.com/pybind/pybind11/pull/1976).\n\n## v2.4.3 (Oct 15, 2019)\n\n- Adapt pybind11 to a C API convention change in Python 3.8.\n  [#1950](https://github.com/pybind/pybind11/pull/1950).\n\n## v2.4.2 (Sep 21, 2019)\n\n- Replaced usage of a C++14 only construct.\n  [#1929](https://github.com/pybind/pybind11/pull/1929).\n- Made an ifdef future-proof for Python \\>= 4.\n  [f3109d](https://github.com/pybind/pybind11/commit/f3109d).\n\n## v2.4.1 (Sep 20, 2019)\n\n- Fixed a problem involving implicit conversion from enumerations to\n  integers on Python 3.8.\n  [#1780](https://github.com/pybind/pybind11/pull/1780).\n\n## v2.4.0 (Sep 19, 2019)\n\n- Try harder to keep pybind11-internal data structures separate when\n  there are potential ABI incompatibilities. Fixes crashes that occurred\n  when loading multiple pybind11 extensions that were e.g. compiled by\n  GCC (libstdc++) and Clang (libc++).\n  [#1588](https://github.com/pybind/pybind11/pull/1588) and\n  [c9f5a](https://github.com/pybind/pybind11/commit/c9f5a).\n- Added support for `__await__`, `__aiter__`, and `__anext__` protocols.\n  [#1842](https://github.com/pybind/pybind11/pull/1842).\n- `pybind11_add_module()`: don't strip symbols when compiling in\n  `RelWithDebInfo` mode.\n  [#1980](https://github.com/pybind/pybind11/pull/1980).\n- `enum_`: Reproduce Python behavior when comparing against invalid\n  values (e.g. `None`, strings, etc.). Add back support for\n  `__invert__()`.\n  [#1912](https://github.com/pybind/pybind11/pull/1912),\n  [#1907](https://github.com/pybind/pybind11/pull/1907).\n- List insertion operation for `py::list`. Added `.empty()` to all\n  collection types. Added `py::set::contains()` and\n  `py::dict::contains()`.\n  [#1887](https://github.com/pybind/pybind11/pull/1887),\n  [#1884](https://github.com/pybind/pybind11/pull/1884),\n  [#1888](https://github.com/pybind/pybind11/pull/1888).\n- `py::details::overload_cast_impl` is available in C++11 mode, can be\n  used like `overload_cast` with an additional set of parentheses.\n  [#1581](https://github.com/pybind/pybind11/pull/1581).\n- Fixed `get_include()` on Conda.\n  [#1877](https://github.com/pybind/pybind11/pull/1877).\n- `stl_bind.h`: negative indexing support.\n  [#1882](https://github.com/pybind/pybind11/pull/1882).\n- Minor CMake fix to add MinGW compatibility.\n  [#1851](https://github.com/pybind/pybind11/pull/1851).\n- GIL-related fixes.\n  [#1836](https://github.com/pybind/pybind11/pull/1836),\n  [8b90b](https://github.com/pybind/pybind11/commit/8b90b).\n- Other very minor/subtle fixes and improvements.\n  [#1329](https://github.com/pybind/pybind11/pull/1329),\n  [#1910](https://github.com/pybind/pybind11/pull/1910),\n  [#1863](https://github.com/pybind/pybind11/pull/1863),\n  [#1847](https://github.com/pybind/pybind11/pull/1847),\n  [#1890](https://github.com/pybind/pybind11/pull/1890),\n  [#1860](https://github.com/pybind/pybind11/pull/1860),\n  [#1848](https://github.com/pybind/pybind11/pull/1848),\n  [#1821](https://github.com/pybind/pybind11/pull/1821),\n  [#1837](https://github.com/pybind/pybind11/pull/1837),\n  [#1833](https://github.com/pybind/pybind11/pull/1833),\n  [#1748](https://github.com/pybind/pybind11/pull/1748),\n  [#1852](https://github.com/pybind/pybind11/pull/1852).\n\n## v2.3.0 (June 11, 2019)\n\n- Significantly reduced module binary size (10-20%) when compiled in\n  C++11 mode with GCC/Clang, or in any mode with MSVC. Function\n  signatures are now always precomputed at compile time (this was\n  previously only available in C++14 mode for non-MSVC compilers).\n  [#934](https://github.com/pybind/pybind11/pull/934).\n\n- Add basic support for tag-based static polymorphism, where classes\n  provide a method to returns the desired type of an instance.\n  [#1326](https://github.com/pybind/pybind11/pull/1326).\n\n- Python type wrappers (`py::handle`, `py::object`, etc.) now support\n  map Python's number protocol onto C++ arithmetic operators such as\n  `operator+`, `operator/=`, etc.\n  [#1511](https://github.com/pybind/pybind11/pull/1511).\n\n- A number of improvements related to enumerations:\n\n  > 1.  The `enum_` implementation was rewritten from scratch to reduce\n  >     code bloat. Rather than instantiating a full implementation for\n  >     each enumeration, most code is now contained in a generic base\n  >     class. [#1511](https://github.com/pybind/pybind11/pull/1511).\n  > 2.  The `value()` method of `py::enum_` now accepts an optional\n  >     docstring that will be shown in the documentation of the\n  >     associated enumeration.\n  >     [#1160](https://github.com/pybind/pybind11/pull/1160).\n  > 3.  check for already existing enum value and throw an error if\n  >     present. [#1453](https://github.com/pybind/pybind11/pull/1453).\n\n- Support for over-aligned type allocation via C++17's aligned `new`\n  statement. [#1582](https://github.com/pybind/pybind11/pull/1582).\n\n- Added `py::ellipsis()` method for slicing of multidimensional NumPy\n  arrays [#1502](https://github.com/pybind/pybind11/pull/1502).\n\n- Numerous Improvements to the `mkdoc.py` script for extracting\n  documentation from C++ header files.\n  [#1788](https://github.com/pybind/pybind11/pull/1788).\n\n- `pybind11_add_module()`: allow including Python as a `SYSTEM` include\n  path. [#1416](https://github.com/pybind/pybind11/pull/1416).\n\n- `pybind11/stl.h` does not convert strings to `vector<string>` anymore.\n  [#1258](https://github.com/pybind/pybind11/issues/1258).\n\n- Mark static methods as such to fix auto-generated Sphinx\n  documentation. [#1732](https://github.com/pybind/pybind11/pull/1732).\n\n- Re-throw forced unwind exceptions (e.g. during pthread termination).\n  [#1208](https://github.com/pybind/pybind11/pull/1208).\n\n- Added `__contains__` method to the bindings of maps (`std::map`,\n  `std::unordered_map`).\n  [#1767](https://github.com/pybind/pybind11/pull/1767).\n\n- Improvements to `gil_scoped_acquire`.\n  [#1211](https://github.com/pybind/pybind11/pull/1211).\n\n- Type caster support for `std::deque<T>`.\n  [#1609](https://github.com/pybind/pybind11/pull/1609).\n\n- Support for `std::unique_ptr` holders, whose deleters differ between a\n  base and derived class.\n  [#1353](https://github.com/pybind/pybind11/pull/1353).\n\n- Construction of STL array/vector-like data structures from iterators.\n  Added an `extend()` operation.\n  [#1709](https://github.com/pybind/pybind11/pull/1709),\n\n- CMake build system improvements for projects that include non-C++\n  files (e.g. plain C, CUDA) in `pybind11_add_module` et al.\n  [#1678](https://github.com/pybind/pybind11/pull/1678).\n\n- Fixed asynchronous invocation and deallocation of Python functions\n  wrapped in `std::function`.\n  [#1595](https://github.com/pybind/pybind11/pull/1595).\n\n- Fixes regarding return value policy propagation in STL type casters.\n  [#1603](https://github.com/pybind/pybind11/pull/1603).\n\n- Fixed scoped enum comparisons.\n  [#1571](https://github.com/pybind/pybind11/pull/1571).\n\n- Fixed iostream redirection for code that releases the GIL.\n  [#1368](https://github.com/pybind/pybind11/pull/1368),\n\n- A number of CI-related fixes.\n  [#1757](https://github.com/pybind/pybind11/pull/1757),\n  [#1744](https://github.com/pybind/pybind11/pull/1744),\n  [#1670](https://github.com/pybind/pybind11/pull/1670).\n\n## v2.2.4 (September 11, 2018)\n\n- Use new Python 3.7 Thread Specific Storage (TSS) implementation if\n  available. [#1454](https://github.com/pybind/pybind11/pull/1454),\n  [#1517](https://github.com/pybind/pybind11/pull/1517).\n- Fixes for newer MSVC versions and C++17 mode.\n  [#1347](https://github.com/pybind/pybind11/pull/1347),\n  [#1462](https://github.com/pybind/pybind11/pull/1462).\n- Propagate return value policies to type-specific casters when casting\n  STL containers.\n  [#1455](https://github.com/pybind/pybind11/pull/1455).\n- Allow ostream-redirection of more than 1024 characters.\n  [#1479](https://github.com/pybind/pybind11/pull/1479).\n- Set `Py_DEBUG` define when compiling against a debug Python build.\n  [#1438](https://github.com/pybind/pybind11/pull/1438).\n- Untangle integer logic in number type caster to work for custom types\n  that may only be castable to a restricted set of builtin types.\n  [#1442](https://github.com/pybind/pybind11/pull/1442).\n- CMake build system: Remember Python version in cache file.\n  [#1434](https://github.com/pybind/pybind11/pull/1434).\n- Fix for custom smart pointers: use `std::addressof` to obtain holder\n  address instead of `operator&`.\n  [#1435](https://github.com/pybind/pybind11/pull/1435).\n- Properly report exceptions thrown during module initialization.\n  [#1362](https://github.com/pybind/pybind11/pull/1362).\n- Fixed a segmentation fault when creating empty-shaped NumPy array.\n  [#1371](https://github.com/pybind/pybind11/pull/1371).\n- The version of Intel C++ compiler must be \\>= 2017, and this is now\n  checked by the header files.\n  [#1363](https://github.com/pybind/pybind11/pull/1363).\n- A few minor typo fixes and improvements to the test suite, and patches\n  that silence compiler warnings.\n- Vectors now support construction from generators, as well as\n  `extend()` from a list or generator.\n  [#1496](https://github.com/pybind/pybind11/pull/1496).\n\n## v2.2.3 (April 29, 2018)\n\n- The pybind11 header location detection was replaced by a new\n  implementation that no longer depends on `pip` internals (the recently\n  released `pip` 10 has restricted access to this API).\n  [#1190](https://github.com/pybind/pybind11/pull/1190).\n- Small adjustment to an implementation detail to work around a compiler\n  segmentation fault in Clang 3.3/3.4.\n  [#1350](https://github.com/pybind/pybind11/pull/1350).\n- The minimal supported version of the Intel compiler was \\>= 17.0 since\n  pybind11 v2.1. This check is now explicit, and a compile-time error is\n  raised if the compiler meet the requirement.\n  [#1363](https://github.com/pybind/pybind11/pull/1363).\n- Fixed an endianness-related fault in the test suite.\n  [#1287](https://github.com/pybind/pybind11/pull/1287).\n\n## v2.2.2 (February 7, 2018)\n\n- Fixed a segfault when combining embedded interpreter\n  shutdown/reinitialization with external loaded pybind11 modules.\n  [#1092](https://github.com/pybind/pybind11/pull/1092).\n- Eigen support: fixed a bug where Nx1/1xN numpy inputs couldn't be\n  passed as arguments to Eigen vectors (which for Eigen are simply\n  compile-time fixed Nx1/1xN matrices).\n  [#1106](https://github.com/pybind/pybind11/pull/1106).\n- Clarified to license by moving the licensing of contributions from\n  `LICENSE` into `CONTRIBUTING.md`: the licensing of contributions is\n  not actually part of the software license as distributed. This isn't\n  meant to be a substantial change in the licensing of the project, but\n  addresses concerns that the clause made the license non-standard.\n  [#1109](https://github.com/pybind/pybind11/issues/1109).\n- Fixed a regression introduced in 2.1 that broke binding functions with\n  lvalue character literal arguments.\n  [#1128](https://github.com/pybind/pybind11/pull/1128).\n- MSVC: fix for compilation failures under /permissive-, and added the\n  flag to the appveyor test suite.\n  [#1155](https://github.com/pybind/pybind11/pull/1155).\n- Fixed `__qualname__` generation, and in turn, fixes how class names\n  (especially nested class names) are shown in generated docstrings.\n  [#1171](https://github.com/pybind/pybind11/pull/1171).\n- Updated the FAQ with a suggested project citation reference.\n  [#1189](https://github.com/pybind/pybind11/pull/1189).\n- Added fixes for deprecation warnings when compiled under C++17 with\n  `-Wdeprecated` turned on, and add `-Wdeprecated` to the test suite\n  compilation flags.\n  [#1191](https://github.com/pybind/pybind11/pull/1191).\n- Fixed outdated PyPI URLs in `setup.py`.\n  [#1213](https://github.com/pybind/pybind11/pull/1213).\n- Fixed a refcount leak for arguments that end up in a `py::args`\n  argument for functions with both fixed positional and `py::args`\n  arguments. [#1216](https://github.com/pybind/pybind11/pull/1216).\n- Fixed a potential segfault resulting from possible premature\n  destruction of `py::args`/`py::kwargs` arguments with overloaded\n  functions. [#1223](https://github.com/pybind/pybind11/pull/1223).\n- Fixed `del map[item]` for a `stl_bind.h` bound stl map.\n  [#1229](https://github.com/pybind/pybind11/pull/1229).\n- Fixed a regression from v2.1.x where the aggregate initialization\n  could unintentionally end up at a constructor taking a templated\n  `std::initializer_list<T>` argument.\n  [#1249](https://github.com/pybind/pybind11/pull/1249).\n- Fixed an issue where calling a function with a keep_alive policy on\n  the same nurse/patient pair would cause the internal patient storage\n  to needlessly grow (unboundedly, if the nurse is long-lived).\n  [#1251](https://github.com/pybind/pybind11/issues/1251).\n- Various other minor fixes.\n\n## v2.2.1 (September 14, 2017)\n\n- Added `py::module_::reload()` member function for reloading a module.\n  [#1040](https://github.com/pybind/pybind11/pull/1040).\n- Fixed a reference leak in the number converter.\n  [#1078](https://github.com/pybind/pybind11/pull/1078).\n- Fixed compilation with Clang on host GCC \\< 5 (old libstdc++ which\n  isn't fully C++11 compliant).\n  [#1062](https://github.com/pybind/pybind11/pull/1062).\n- Fixed a regression where the automatic `std::vector<bool>` caster\n  would fail to compile. The same fix also applies to any container\n  which returns element proxies instead of references.\n  [#1053](https://github.com/pybind/pybind11/pull/1053).\n- Fixed a regression where the `py::keep_alive` policy could not be\n  applied to constructors.\n  [#1065](https://github.com/pybind/pybind11/pull/1065).\n- Fixed a nullptr dereference when loading a `py::module_local` type\n  that's only registered in an external module.\n  [#1058](https://github.com/pybind/pybind11/pull/1058).\n- Fixed implicit conversion of accessors to types derived from\n  `py::object`. [#1076](https://github.com/pybind/pybind11/pull/1076).\n- The `name` in `PYBIND11_MODULE(name, variable)` can now be a macro.\n  [#1082](https://github.com/pybind/pybind11/pull/1082).\n- Relaxed overly strict `py::pickle()` check for matching get and set\n  types. [#1064](https://github.com/pybind/pybind11/pull/1064).\n- Conversion errors now try to be more informative when it's likely that\n  a missing header is the cause (e.g. forgetting `<pybind11/stl.h>`).\n  [#1077](https://github.com/pybind/pybind11/pull/1077).\n\n## v2.2.0 (August 31, 2017)\n\n- Support for embedding the Python interpreter. See the\n  `documentation page </advanced/embedding>` for a full overview of the\n  new features. [#774](https://github.com/pybind/pybind11/pull/774),\n  [#889](https://github.com/pybind/pybind11/pull/889),\n  [#892](https://github.com/pybind/pybind11/pull/892),\n  [#920](https://github.com/pybind/pybind11/pull/920).\n\n  ```cpp\n  #include <pybind11/embed.h>\n  namespace py = pybind11;\n\n  int main() {\n      py::scoped_interpreter guard{}; // start the interpreter and keep it alive\n\n      py::print(\"Hello, World!\"); // use the Python API\n  }\n  ```\n\n- Support for inheriting from multiple C++ bases in Python.\n  [#693](https://github.com/pybind/pybind11/pull/693).\n\n  ```python\n  from cpp_module import CppBase1, CppBase2\n\n\n  class PyDerived(CppBase1, CppBase2):\n      def __init__(self):\n          CppBase1.__init__(self)  # C++ bases must be initialized explicitly\n          CppBase2.__init__(self)\n  ```\n\n- `PYBIND11_MODULE` is now the preferred way to create module entry\n  points. `PYBIND11_PLUGIN` is deprecated. See `macros` for details.\n  [#879](https://github.com/pybind/pybind11/pull/879).\n\n  ```cpp\n  // new\n  PYBIND11_MODULE(example, m) {\n      m.def(\"add\", [](int a, int b) { return a + b; });\n  }\n\n  // old\n  PYBIND11_PLUGIN(example) {\n      py::module m(\"example\");\n      m.def(\"add\", [](int a, int b) { return a + b; });\n      return m.ptr();\n  }\n  ```\n\n- pybind11's headers and build system now more strictly enforce hidden\n  symbol visibility for extension modules. This should be seamless for\n  most users, but see the `upgrade` if you use a custom build system.\n  [#995](https://github.com/pybind/pybind11/pull/995).\n\n- Support for `py::module_local` types which allow multiple modules to\n  export the same C++ types without conflicts. This is useful for opaque\n  types like `std::vector<int>`. `py::bind_vector` and `py::bind_map`\n  now default to `py::module_local` if their elements are builtins or\n  local types. See `module_local` for details.\n  [#949](https://github.com/pybind/pybind11/pull/949),\n  [#981](https://github.com/pybind/pybind11/pull/981),\n  [#995](https://github.com/pybind/pybind11/pull/995),\n  [#997](https://github.com/pybind/pybind11/pull/997).\n\n- Custom constructors can now be added very easily using lambdas or\n  factory functions which return a class instance by value, pointer or\n  holder. This supersedes the old placement-new `__init__` technique.\n  See `custom_constructors` for details.\n  [#805](https://github.com/pybind/pybind11/pull/805),\n  [#1014](https://github.com/pybind/pybind11/pull/1014).\n\n  ```cpp\n  struct Example {\n      Example(std::string);\n  };\n\n  py::class_<Example>(m, \"Example\")\n      .def(py::init<std::string>()) // existing constructor\n      .def(py::init([](int n) { // custom constructor\n          return std::make_unique<Example>(std::to_string(n));\n      }));\n  ```\n\n- Similarly to custom constructors, pickling support functions are now\n  bound using the `py::pickle()` adaptor which improves type safety. See\n  the `upgrade` and `pickling` for details.\n  [#1038](https://github.com/pybind/pybind11/pull/1038).\n\n- Builtin support for converting C++17 standard library types and\n  general conversion improvements:\n\n  1.  C++17 `std::variant` is supported right out of the box. C++11/14\n      equivalents (e.g. `boost::variant`) can also be added with a\n      simple user-defined specialization. See `cpp17_container_casters`\n      for details. [#811](https://github.com/pybind/pybind11/pull/811),\n      [#845](https://github.com/pybind/pybind11/pull/845),\n      [#989](https://github.com/pybind/pybind11/pull/989).\n  2.  Out-of-the-box support for C++17 `std::string_view`.\n      [#906](https://github.com/pybind/pybind11/pull/906).\n  3.  Improved compatibility of the builtin `optional` converter.\n      [#874](https://github.com/pybind/pybind11/pull/874).\n  4.  The `bool` converter now accepts `numpy.bool_` and types which\n      define `__bool__` (Python 3.x) or `__nonzero__` (Python 2.7).\n      [#925](https://github.com/pybind/pybind11/pull/925).\n  5.  C++-to-Python casters are now more efficient and move elements out\n      of rvalue containers whenever possible.\n      [#851](https://github.com/pybind/pybind11/pull/851),\n      [#936](https://github.com/pybind/pybind11/pull/936),\n      [#938](https://github.com/pybind/pybind11/pull/938).\n  6.  Fixed `bytes` to `std::string/char*` conversion on Python 3.\n      [#817](https://github.com/pybind/pybind11/pull/817).\n  7.  Fixed lifetime of temporary C++ objects created in Python-to-C++\n      conversions. [#924](https://github.com/pybind/pybind11/pull/924).\n\n- Scope guard call policy for RAII types, e.g.\n  `py::call_guard<py::gil_scoped_release>()`,\n  `py::call_guard<py::scoped_ostream_redirect>()`. See `call_policies`\n  for details. [#740](https://github.com/pybind/pybind11/pull/740).\n\n- Utility for redirecting C++ streams to Python (e.g. `std::cout` -\\>\n  `sys.stdout`). Scope guard `py::scoped_ostream_redirect` in C++ and a\n  context manager in Python. See `ostream_redirect`.\n  [#1009](https://github.com/pybind/pybind11/pull/1009).\n\n- Improved handling of types and exceptions across module boundaries.\n  [#915](https://github.com/pybind/pybind11/pull/915),\n  [#951](https://github.com/pybind/pybind11/pull/951),\n  [#995](https://github.com/pybind/pybind11/pull/995).\n\n- Fixed destruction order of `py::keep_alive` nurse/patient objects in\n  reference cycles.\n  [#856](https://github.com/pybind/pybind11/pull/856).\n\n- NumPy and buffer protocol related improvements:\n\n  1.  Support for negative strides in Python buffer objects/numpy\n      arrays. This required changing integers from unsigned to signed\n      for the related C++ APIs. Note: If you have compiler warnings\n      enabled, you may notice some new conversion warnings after\n      upgrading. These can be resolved with `static_cast`.\n      [#782](https://github.com/pybind/pybind11/pull/782).\n  2.  Support `std::complex` and arrays inside `PYBIND11_NUMPY_DTYPE`.\n      [#831](https://github.com/pybind/pybind11/pull/831),\n      [#832](https://github.com/pybind/pybind11/pull/832).\n  3.  Support for constructing `py::buffer_info` and `py::arrays` using\n      arbitrary containers or iterators instead of requiring a\n      `std::vector`.\n      [#788](https://github.com/pybind/pybind11/pull/788),\n      [#822](https://github.com/pybind/pybind11/pull/822),\n      [#860](https://github.com/pybind/pybind11/pull/860).\n  4.  Explicitly check numpy version and require \\>= 1.7.0.\n      [#819](https://github.com/pybind/pybind11/pull/819).\n\n- Support for allowing/prohibiting `None` for specific arguments and\n  improved `None` overload resolution order. See `none_arguments` for\n  details. [#843](https://github.com/pybind/pybind11/pull/843).\n  [#859](https://github.com/pybind/pybind11/pull/859).\n\n- Added `py::exec()` as a shortcut for `py::eval<py::eval_statements>()`\n  and support for C++11 raw string literals as input. See `eval`.\n  [#766](https://github.com/pybind/pybind11/pull/766),\n  [#827](https://github.com/pybind/pybind11/pull/827).\n\n- `py::vectorize()` ignores non-vectorizable arguments and supports\n  member functions.\n  [#762](https://github.com/pybind/pybind11/pull/762).\n\n- Support for bound methods as callbacks (`pybind11/functional.h`).\n  [#815](https://github.com/pybind/pybind11/pull/815).\n\n- Allow aliasing pybind11 methods: `cls.attr(\"foo\") = cls.attr(\"bar\")`.\n  [#802](https://github.com/pybind/pybind11/pull/802).\n\n- Don't allow mixed static/non-static overloads.\n  [#804](https://github.com/pybind/pybind11/pull/804).\n\n- Fixed overriding static properties in derived classes.\n  [#784](https://github.com/pybind/pybind11/pull/784).\n\n- Added support for write only properties.\n  [#1144](https://github.com/pybind/pybind11/pull/1144).\n\n- Improved deduction of member functions of a derived class when its\n  bases aren't registered with pybind11.\n  [#855](https://github.com/pybind/pybind11/pull/855).\n\n  ```cpp\n  struct Base {\n      int foo() { return 42; }\n  }\n\n  struct Derived : Base {}\n\n  // Now works, but previously required also binding `Base`\n  py::class_<Derived>(m, \"Derived\")\n      .def(\"foo\", &Derived::foo); // function is actually from `Base`\n  ```\n\n- The implementation of `py::init<>` now uses C++11 brace initialization\n  syntax to construct instances, which permits binding implicit\n  constructors of aggregate types.\n  [#1015](https://github.com/pybind/pybind11/pull/1015).\n\n  > ```cpp\n  > struct Aggregate {\n  >     int a;\n  >     std::string b;\n  > };\n  >\n  > py::class_<Aggregate>(m, \"Aggregate\")\n  >     .def(py::init<int, const std::string &>());\n  > ```\n\n- Fixed issues with multiple inheritance with offset base/derived\n  pointers. [#812](https://github.com/pybind/pybind11/pull/812),\n  [#866](https://github.com/pybind/pybind11/pull/866),\n  [#960](https://github.com/pybind/pybind11/pull/960).\n\n- Fixed reference leak of type objects.\n  [#1030](https://github.com/pybind/pybind11/pull/1030).\n\n- Improved support for the `/std:c++14` and `/std:c++latest` modes on\n  MSVC 2017. [#841](https://github.com/pybind/pybind11/pull/841),\n  [#999](https://github.com/pybind/pybind11/pull/999).\n\n- Fixed detection of private operator new on MSVC.\n  [#893](https://github.com/pybind/pybind11/pull/893),\n  [#918](https://github.com/pybind/pybind11/pull/918).\n\n- Intel C++ compiler compatibility fixes.\n  [#937](https://github.com/pybind/pybind11/pull/937).\n\n- Fixed implicit conversion of `py::enum_` to integer types on Python\n  2.7. [#821](https://github.com/pybind/pybind11/pull/821).\n\n- Added `py::hash` to fetch the hash value of Python objects, and\n  `.def(hash(py::self))` to provide the C++ `std::hash` as the Python\n  `__hash__` method.\n  [#1034](https://github.com/pybind/pybind11/pull/1034).\n\n- Fixed `__truediv__` on Python 2 and `__itruediv__` on Python 3.\n  [#867](https://github.com/pybind/pybind11/pull/867).\n\n- `py::capsule` objects now support the `name` attribute. This is useful\n  for interfacing with `scipy.LowLevelCallable`.\n  [#902](https://github.com/pybind/pybind11/pull/902).\n\n- Fixed `py::make_iterator`'s `__next__()` for past-the-end calls.\n  [#897](https://github.com/pybind/pybind11/pull/897).\n\n- Added `error_already_set::matches()` for checking Python exceptions.\n  [#772](https://github.com/pybind/pybind11/pull/772).\n\n- Deprecated `py::error_already_set::clear()`. It's no longer needed\n  following a simplification of the `py::error_already_set` class.\n  [#954](https://github.com/pybind/pybind11/pull/954).\n\n- Deprecated `py::handle::operator==()` in favor of `py::handle::is()`\n  [#825](https://github.com/pybind/pybind11/pull/825).\n\n- Deprecated `py::object::borrowed`/`py::object::stolen`. Use\n  `py::object::borrowed_t{}`/`py::object::stolen_t{}` instead.\n  [#771](https://github.com/pybind/pybind11/pull/771).\n\n- Changed internal data structure versioning to avoid conflicts between\n  modules compiled with different revisions of pybind11.\n  [#1012](https://github.com/pybind/pybind11/pull/1012).\n\n- Additional compile-time and run-time error checking and more\n  informative messages.\n  [#786](https://github.com/pybind/pybind11/pull/786),\n  [#794](https://github.com/pybind/pybind11/pull/794),\n  [#803](https://github.com/pybind/pybind11/pull/803).\n\n- Various minor improvements and fixes.\n  [#764](https://github.com/pybind/pybind11/pull/764),\n  [#791](https://github.com/pybind/pybind11/pull/791),\n  [#795](https://github.com/pybind/pybind11/pull/795),\n  [#840](https://github.com/pybind/pybind11/pull/840),\n  [#844](https://github.com/pybind/pybind11/pull/844),\n  [#846](https://github.com/pybind/pybind11/pull/846),\n  [#849](https://github.com/pybind/pybind11/pull/849),\n  [#858](https://github.com/pybind/pybind11/pull/858),\n  [#862](https://github.com/pybind/pybind11/pull/862),\n  [#871](https://github.com/pybind/pybind11/pull/871),\n  [#872](https://github.com/pybind/pybind11/pull/872),\n  [#881](https://github.com/pybind/pybind11/pull/881),\n  [#888](https://github.com/pybind/pybind11/pull/888),\n  [#899](https://github.com/pybind/pybind11/pull/899),\n  [#928](https://github.com/pybind/pybind11/pull/928),\n  [#931](https://github.com/pybind/pybind11/pull/931),\n  [#944](https://github.com/pybind/pybind11/pull/944),\n  [#950](https://github.com/pybind/pybind11/pull/950),\n  [#952](https://github.com/pybind/pybind11/pull/952),\n  [#962](https://github.com/pybind/pybind11/pull/962),\n  [#965](https://github.com/pybind/pybind11/pull/965),\n  [#970](https://github.com/pybind/pybind11/pull/970),\n  [#978](https://github.com/pybind/pybind11/pull/978),\n  [#979](https://github.com/pybind/pybind11/pull/979),\n  [#986](https://github.com/pybind/pybind11/pull/986),\n  [#1020](https://github.com/pybind/pybind11/pull/1020),\n  [#1027](https://github.com/pybind/pybind11/pull/1027),\n  [#1037](https://github.com/pybind/pybind11/pull/1037).\n\n- Testing improvements.\n  [#798](https://github.com/pybind/pybind11/pull/798),\n  [#882](https://github.com/pybind/pybind11/pull/882),\n  [#898](https://github.com/pybind/pybind11/pull/898),\n  [#900](https://github.com/pybind/pybind11/pull/900),\n  [#921](https://github.com/pybind/pybind11/pull/921),\n  [#923](https://github.com/pybind/pybind11/pull/923),\n  [#963](https://github.com/pybind/pybind11/pull/963).\n\n## v2.1.1 (April 7, 2017)\n\n- Fixed minimum version requirement for MSVC 2015u3\n  [#773](https://github.com/pybind/pybind11/pull/773).\n\n## v2.1.0 (March 22, 2017)\n\n- pybind11 now performs function overload resolution in two phases. The\n  first phase only considers exact type matches, while the second allows\n  for implicit conversions to take place. A special `noconvert()` syntax\n  can be used to completely disable implicit conversions for specific\n  arguments. [#643](https://github.com/pybind/pybind11/pull/643),\n  [#634](https://github.com/pybind/pybind11/pull/634),\n  [#650](https://github.com/pybind/pybind11/pull/650).\n- Fixed a regression where static properties no longer worked with\n  classes using multiple inheritance. The `py::metaclass` attribute is\n  no longer necessary (and deprecated as of this release) when binding\n  classes with static properties.\n  [#679](https://github.com/pybind/pybind11/pull/679),\n- Classes bound using `pybind11` can now use custom metaclasses.\n  [#679](https://github.com/pybind/pybind11/pull/679),\n- `py::args` and `py::kwargs` can now be mixed with other positional\n  arguments when binding functions using pybind11.\n  [#611](https://github.com/pybind/pybind11/pull/611).\n- Improved support for C++11 unicode string and character types; added\n  extensive documentation regarding pybind11's string conversion\n  behavior. [#624](https://github.com/pybind/pybind11/pull/624),\n  [#636](https://github.com/pybind/pybind11/pull/636),\n  [#715](https://github.com/pybind/pybind11/pull/715).\n- pybind11 can now avoid expensive copies when converting Eigen arrays\n  to NumPy arrays (and vice versa).\n  [#610](https://github.com/pybind/pybind11/pull/610).\n- The \"fast path\" in `py::vectorize` now works for any full-size group\n  of C or F-contiguous arrays. The non-fast path is also faster since it\n  no longer performs copies of the input arguments (except when type\n  conversions are necessary).\n  [#610](https://github.com/pybind/pybind11/pull/610).\n- Added fast, unchecked access to NumPy arrays via a proxy object.\n  [#746](https://github.com/pybind/pybind11/pull/746).\n- Transparent support for class-specific `operator new` and\n  `operator delete` implementations.\n  [#755](https://github.com/pybind/pybind11/pull/755).\n- Slimmer and more efficient STL-compatible iterator interface for\n  sequence types. [#662](https://github.com/pybind/pybind11/pull/662).\n- Improved custom holder type support.\n  [#607](https://github.com/pybind/pybind11/pull/607).\n- `nullptr` to `None` conversion fixed in various builtin type casters.\n  [#732](https://github.com/pybind/pybind11/pull/732).\n- `enum_` now exposes its members via a special `__members__` attribute.\n  [#666](https://github.com/pybind/pybind11/pull/666).\n- `std::vector` bindings created using `stl_bind.h` can now optionally\n  implement the buffer protocol.\n  [#488](https://github.com/pybind/pybind11/pull/488).\n- Automated C++ reference documentation using doxygen and breathe.\n  [#598](https://github.com/pybind/pybind11/pull/598).\n- Added minimum compiler version assertions.\n  [#727](https://github.com/pybind/pybind11/pull/727).\n- Improved compatibility with C++1z.\n  [#677](https://github.com/pybind/pybind11/pull/677).\n- Improved `py::capsule` API. Can be used to implement cleanup callbacks\n  that are involved at module destruction time.\n  [#752](https://github.com/pybind/pybind11/pull/752).\n- Various minor improvements and fixes.\n  [#595](https://github.com/pybind/pybind11/pull/595),\n  [#588](https://github.com/pybind/pybind11/pull/588),\n  [#589](https://github.com/pybind/pybind11/pull/589),\n  [#603](https://github.com/pybind/pybind11/pull/603),\n  [#619](https://github.com/pybind/pybind11/pull/619),\n  [#648](https://github.com/pybind/pybind11/pull/648),\n  [#695](https://github.com/pybind/pybind11/pull/695),\n  [#720](https://github.com/pybind/pybind11/pull/720),\n  [#723](https://github.com/pybind/pybind11/pull/723),\n  [#729](https://github.com/pybind/pybind11/pull/729),\n  [#724](https://github.com/pybind/pybind11/pull/724),\n  [#742](https://github.com/pybind/pybind11/pull/742),\n  [#753](https://github.com/pybind/pybind11/pull/753).\n\n## v2.0.1 (Jan 4, 2017)\n\n- Fix pointer to reference error in type_caster on MSVC\n  [#583](https://github.com/pybind/pybind11/pull/583).\n- Fixed a segmentation in the test suite due to a typo\n  [cd7eac](https://github.com/pybind/pybind11/commit/cd7eac).\n\n## v2.0.0 (Jan 1, 2017)\n\n- Fixed a reference counting regression affecting types with custom\n  metaclasses (introduced in v2.0.0-rc1).\n  [#571](https://github.com/pybind/pybind11/pull/571).\n- Quenched a CMake policy warning.\n  [#570](https://github.com/pybind/pybind11/pull/570).\n\n## v2.0.0-rc1 (Dec 23, 2016)\n\nThe pybind11 developers are excited to issue a release candidate of\npybind11 with a subsequent v2.0.0 release planned in early January next\nyear.\n\nAn incredible amount of effort by went into pybind11 over the last ~5\nmonths, leading to a release that is jam-packed with exciting new\nfeatures and numerous usability improvements. The following list links\nPRs or individual commits whenever applicable.\n\nHappy Christmas!\n\n- Support for binding C++ class hierarchies that make use of multiple\n  inheritance. [#410](https://github.com/pybind/pybind11/pull/410).\n\n- PyPy support: pybind11 now supports nightly builds of PyPy and will\n  interoperate with the future 5.7 release. No code changes are\n  necessary, everything \"just\" works as usual. Note that we only target\n  the Python 2.7 branch for now; support for 3.x will be added once its\n  `cpyext` extension support catches up. A few minor features remain\n  unsupported for the time being (notably dynamic attributes in custom\n  types). [#527](https://github.com/pybind/pybind11/pull/527).\n\n- Significant work on the documentation -- in particular, the monolithic\n  `advanced.rst` file was restructured into a easier to read\n  hierarchical organization.\n  [#448](https://github.com/pybind/pybind11/pull/448).\n\n- Many NumPy-related improvements:\n\n  1.  Object-oriented API to access and modify NumPy `ndarray`\n      instances, replicating much of the corresponding NumPy C API\n      functionality.\n      [#402](https://github.com/pybind/pybind11/pull/402).\n\n  2.  NumPy array `dtype` array descriptors are now first-class citizens\n      and are exposed via a new class `py::dtype`.\n\n  3.  Structured dtypes can be registered using the\n      `PYBIND11_NUMPY_DTYPE()` macro. Special `array` constructors\n      accepting dtype objects were also added.\n\n      One potential caveat involving this change: format descriptor\n      strings should now be accessed via `format_descriptor::format()`\n      (however, for compatibility purposes, the old syntax\n      `format_descriptor::value` will still work for non-structured data\n      types). [#308](https://github.com/pybind/pybind11/pull/308).\n\n  4.  Further improvements to support structured dtypes throughout the\n      system. [#472](https://github.com/pybind/pybind11/pull/472),\n      [#474](https://github.com/pybind/pybind11/pull/474),\n      [#459](https://github.com/pybind/pybind11/pull/459),\n      [#453](https://github.com/pybind/pybind11/pull/453),\n      [#452](https://github.com/pybind/pybind11/pull/452), and\n      [#505](https://github.com/pybind/pybind11/pull/505).\n\n  5.  Fast access operators.\n      [#497](https://github.com/pybind/pybind11/pull/497).\n\n  6.  Constructors for arrays whose storage is owned by another object.\n      [#440](https://github.com/pybind/pybind11/pull/440).\n\n  7.  Added constructors for `array` and `array_t` explicitly accepting\n      shape and strides; if strides are not provided, they are deduced\n      assuming C-contiguity. Also added simplified constructors for\n      1-dimensional case.\n\n  8.  Added buffer/NumPy support for `char[N]` and `std::array<char, N>`\n      types.\n\n  9.  Added `memoryview` wrapper type which is constructible from\n      `buffer_info`.\n\n- Eigen: many additional conversions and support for non-contiguous\n  arrays/slices. [#427](https://github.com/pybind/pybind11/pull/427),\n  [#315](https://github.com/pybind/pybind11/pull/315),\n  [#316](https://github.com/pybind/pybind11/pull/316),\n  [#312](https://github.com/pybind/pybind11/pull/312), and\n  [#267](https://github.com/pybind/pybind11/pull/267)\n\n- Incompatible changes in `class_<...>::class_()`:\n\n  > 1.  Declarations of types that provide access via the buffer\n  >     protocol must now include the `py::buffer_protocol()` annotation\n  >     as an argument to the `class_` constructor.\n  > 2.  Declarations of types that require a custom metaclass (i.e. all\n  >     classes which include static properties via commands such as\n  >     `def_readwrite_static()`) must now include the `py::metaclass()`\n  >     annotation as an argument to the `class_` constructor.\n  >\n  >     These two changes were necessary to make type definitions in\n  >     pybind11 future-proof, and to support PyPy via its cpyext\n  >     mechanism. [#527](https://github.com/pybind/pybind11/pull/527).\n  >\n  > 3.  This version of pybind11 uses a redesigned mechanism for\n  >     instantiating trampoline classes that are used to override\n  >     virtual methods from within Python. This led to the following\n  >     user-visible syntax change: instead of\n  >\n  >     ```cpp\n  >     py::class_<TrampolineClass>(\"MyClass\")\n  >       .alias<MyClass>()\n  >       ....\n  >     ```\n  >\n  >     write\n  >\n  >     ```cpp\n  >     py::class_<MyClass, TrampolineClass>(\"MyClass\")\n  >       ....\n  >     ```\n  >\n  >     Importantly, both the original and the trampoline class are now\n  >     specified as an arguments (in arbitrary order) to the\n  >     `py::class_` template, and the `alias<..>()` call is gone. The\n  >     new scheme has zero overhead in cases when Python doesn't\n  >     override any functions of the underlying C++ class. [rev.\n  >     86d825](https://github.com/pybind/pybind11/commit/86d825).\n\n- Added `eval` and `eval_file` functions for evaluating expressions and\n  statements from a string or file. [rev.\n  0d3fc3](https://github.com/pybind/pybind11/commit/0d3fc3).\n\n- pybind11 can now create types with a modifiable dictionary.\n  [#437](https://github.com/pybind/pybind11/pull/437) and\n  [#444](https://github.com/pybind/pybind11/pull/444).\n\n- Support for translation of arbitrary C++ exceptions to Python\n  counterparts. [#296](https://github.com/pybind/pybind11/pull/296) and\n  [#273](https://github.com/pybind/pybind11/pull/273).\n\n- Report full backtraces through mixed C++/Python code, better reporting\n  for import errors, fixed GIL management in exception processing.\n  [#537](https://github.com/pybind/pybind11/pull/537),\n  [#494](https://github.com/pybind/pybind11/pull/494), [rev.\n  e72d95](https://github.com/pybind/pybind11/commit/e72d95), and [rev.\n  099d6e](https://github.com/pybind/pybind11/commit/099d6e).\n\n- Support for bit-level operations, comparisons, and serialization of\n  C++ enumerations.\n  [#503](https://github.com/pybind/pybind11/pull/503),\n  [#508](https://github.com/pybind/pybind11/pull/508),\n  [#380](https://github.com/pybind/pybind11/pull/380),\n  [#309](https://github.com/pybind/pybind11/pull/309).\n  [#311](https://github.com/pybind/pybind11/pull/311).\n\n- The `class_` constructor now accepts its template arguments in any\n  order. [#385](https://github.com/pybind/pybind11/pull/385).\n\n- Attribute and item accessors now have a more complete interface which\n  makes it possible to chain attributes as in\n  `obj.attr(\"a\")[key].attr(\"b\").attr(\"method\")(1, 2, 3)`.\n  [#425](https://github.com/pybind/pybind11/pull/425).\n\n- Major redesign of the default and conversion constructors in\n  `pytypes.h`. [#464](https://github.com/pybind/pybind11/pull/464).\n\n- Added built-in support for `std::shared_ptr` holder type. It is no\n  longer necessary to to include a declaration of the form\n  `PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)` (though\n  continuing to do so won't cause an error).\n  [#454](https://github.com/pybind/pybind11/pull/454).\n\n- New `py::overload_cast` casting operator to select among multiple\n  possible overloads of a function. An example:\n\n  > ```cpp\n  > py::class_<Pet>(m, \"Pet\")\n  >     .def(\"set\", py::overload_cast<int>(&Pet::set), \"Set the pet's age\")\n  >     .def(\"set\", py::overload_cast<const std::string &>(&Pet::set), \"Set the pet's name\");\n  > ```\n\n  This feature only works on C++14-capable compilers.\n  [#541](https://github.com/pybind/pybind11/pull/541).\n\n- C++ types are automatically cast to Python types, e.g. when assigning\n  them as an attribute. For instance, the following is now legal:\n\n  > ```cpp\n  > py::module m = /* ... */\n  > m.attr(\"constant\") = 123;\n  > ```\n\n  (Previously, a `py::cast` call was necessary to avoid a compilation\n  error.) [#551](https://github.com/pybind/pybind11/pull/551).\n\n- Redesigned `pytest`-based test suite.\n  [#321](https://github.com/pybind/pybind11/pull/321).\n\n- Instance tracking to detect reference leaks in test suite.\n  [#324](https://github.com/pybind/pybind11/pull/324)\n\n- pybind11 can now distinguish between multiple different instances that\n  are located at the same memory address, but which have different\n  types. [#329](https://github.com/pybind/pybind11/pull/329).\n\n- Improved logic in `move` return value policy.\n  [#510](https://github.com/pybind/pybind11/pull/510),\n  [#297](https://github.com/pybind/pybind11/pull/297).\n\n- Generalized unpacking API to permit calling Python functions from C++\n  using notation such as\n  `foo(a1, a2, *args, \"ka\"_a=1, \"kb\"_a=2, **kwargs)`.\n  [#372](https://github.com/pybind/pybind11/pull/372).\n\n- `py::print()` function whose behavior matches that of the native\n  Python `print()` function.\n  [#372](https://github.com/pybind/pybind11/pull/372).\n\n- Added `py::dict` keyword\n  constructor:`auto d = dict(\"number\"_a=42, \"name\"_a=\"World\");`.\n  [#372](https://github.com/pybind/pybind11/pull/372).\n\n- Added `py::str::format()` method and `_s` literal:\n  `py::str s = \"1 + 2 = {}\"_s.format(3);`.\n  [#372](https://github.com/pybind/pybind11/pull/372).\n\n- Added `py::repr()` function which is equivalent to Python's builtin\n  `repr()`. [#333](https://github.com/pybind/pybind11/pull/333).\n\n- Improved construction and destruction logic for holder types. It is\n  now possible to reference instances with smart pointer holder types\n  without constructing the holder if desired. The\n  `PYBIND11_DECLARE_HOLDER_TYPE` macro now accepts an optional second\n  parameter to indicate whether the holder type uses intrusive reference\n  counting. [#533](https://github.com/pybind/pybind11/pull/533) and\n  [#561](https://github.com/pybind/pybind11/pull/561).\n\n- Mapping a stateless C++ function to Python and back is now \"for free\"\n  (i.e. no extra indirections or argument conversion overheads). [rev.\n  954b79](https://github.com/pybind/pybind11/commit/954b79).\n\n- Bindings for `std::valarray<T>`.\n  [#545](https://github.com/pybind/pybind11/pull/545).\n\n- Improved support for C++17 capable compilers.\n  [#562](https://github.com/pybind/pybind11/pull/562).\n\n- Bindings for `std::optional<t>`.\n  [#475](https://github.com/pybind/pybind11/pull/475),\n  [#476](https://github.com/pybind/pybind11/pull/476),\n  [#479](https://github.com/pybind/pybind11/pull/479),\n  [#499](https://github.com/pybind/pybind11/pull/499), and\n  [#501](https://github.com/pybind/pybind11/pull/501).\n\n- `stl_bind.h`: general improvements and support for `std::map` and\n  `std::unordered_map`.\n  [#490](https://github.com/pybind/pybind11/pull/490),\n  [#282](https://github.com/pybind/pybind11/pull/282),\n  [#235](https://github.com/pybind/pybind11/pull/235).\n\n- The `std::tuple`, `std::pair`, `std::list`, and `std::vector` type\n  casters now accept any Python sequence type as input. [rev.\n  107285](https://github.com/pybind/pybind11/commit/107285).\n\n- Improved CMake Python detection on multi-architecture Linux.\n  [#532](https://github.com/pybind/pybind11/pull/532).\n\n- Infrastructure to selectively disable or enable parts of the\n  automatically generated docstrings.\n  [#486](https://github.com/pybind/pybind11/pull/486).\n\n- `reference` and `reference_internal` are now the default return value\n  properties for static and non-static properties, respectively.\n  [#473](https://github.com/pybind/pybind11/pull/473). (the previous\n  defaults were `automatic`).\n  [#473](https://github.com/pybind/pybind11/pull/473).\n\n- Support for `std::unique_ptr` with non-default deleters or no deleter\n  at all (`py::nodelete`).\n  [#384](https://github.com/pybind/pybind11/pull/384).\n\n- Deprecated `handle::call()` method. The new syntax to call Python\n  functions is simply `handle()`. It can also be invoked explicitly via\n  `handle::operator<X>()`, where `X` is an optional return value policy.\n\n- Print more informative error messages when `make_tuple()` or `cast()`\n  fail. [#262](https://github.com/pybind/pybind11/pull/262).\n\n- Creation of holder types for classes deriving from\n  `std::enable_shared_from_this<>` now also works for `const` values.\n  [#260](https://github.com/pybind/pybind11/pull/260).\n\n- `make_iterator()` improvements for better compatibility with various\n  types (now uses prefix increment operator); it now also accepts\n  iterators with different begin/end types as long as they are equality\n  comparable. [#247](https://github.com/pybind/pybind11/pull/247).\n\n- `arg()` now accepts a wider range of argument types for default\n  values. [#244](https://github.com/pybind/pybind11/pull/244).\n\n- Support `keep_alive` where the nurse object may be `None`.\n  [#341](https://github.com/pybind/pybind11/pull/341).\n\n- Added constructors for `str` and `bytes` from zero-terminated char\n  pointers, and from char pointers and length. Added constructors for\n  `str` from `bytes` and for `bytes` from `str`, which will perform\n  UTF-8 decoding/encoding as required.\n\n- Many other improvements of library internals without user-visible\n  changes\n\n## 1.8.1 (July 12, 2016)\n\n- Fixed a rare but potentially very severe issue when the garbage\n  collector ran during pybind11 type creation.\n\n## 1.8.0 (June 14, 2016)\n\n- Redesigned CMake build system which exports a convenient\n  `pybind11_add_module` function to parent projects.\n- `std::vector<>` type bindings analogous to Boost.Python's\n  `indexing_suite`\n- Transparent conversion of sparse and dense Eigen matrices and vectors\n  (`eigen.h`)\n- Added an `ExtraFlags` template argument to the NumPy `array_t<>`\n  wrapper to disable an enforced cast that may lose precision, e.g. to\n  create overloads for different precisions and complex vs real-valued\n  matrices.\n- Prevent implicit conversion of floating point values to integral types\n  in function arguments\n- Fixed incorrect default return value policy for functions returning a\n  shared pointer\n- Don't allow registering a type via `class_` twice\n- Don't allow casting a `None` value into a C++ lvalue reference\n- Fixed a crash in `enum_::operator==` that was triggered by the\n  `help()` command\n- Improved detection of whether or not custom C++ types can be\n  copy/move-constructed\n- Extended `str` type to also work with `bytes` instances\n- Added a `\"name\"_a` user defined string literal that is equivalent to\n  `py::arg(\"name\")`.\n- When specifying function arguments via `py::arg`, the test that\n  verifies the number of arguments now runs at compile time.\n- Added `[[noreturn]]` attribute to `pybind11_fail()` to quench some\n  compiler warnings\n- List function arguments in exception text when the dispatch code\n  cannot find a matching overload\n- Added `PYBIND11_OVERLOAD_NAME` and `PYBIND11_OVERLOAD_PURE_NAME`\n  macros which can be used to override virtual methods whose name\n  differs in C++ and Python (e.g. `__call__` and `operator()`)\n- Various minor `iterator` and `make_iterator()` improvements\n- Transparently support `__bool__` on Python 2.x and Python 3.x\n- Fixed issue with destructor of unpickled object not being called\n- Minor CMake build system improvements on Windows\n- New `pybind11::args` and `pybind11::kwargs` types to create functions\n  which take an arbitrary number of arguments and keyword arguments\n- New syntax to call a Python function from C++ using `*args` and\n  `*kwargs`\n- The functions `def_property_*` now correctly process docstring\n  arguments (these formerly caused a segmentation fault)\n- Many `mkdoc.py` improvements (enumerations, template arguments,\n  `DOC()` macro accepts more arguments)\n- Cygwin support\n- Documentation improvements (pickling support, `keep_alive`, macro\n  usage)\n\n## 1.7 (April 30, 2016)\n\n- Added a new `move` return value policy that triggers C++11 move\n  semantics. The automatic return value policy falls back to this case\n  whenever a rvalue reference is encountered\n- Significantly more general GIL state routines that are used instead of\n  Python's troublesome `PyGILState_Ensure` and `PyGILState_Release` API\n- Redesign of opaque types that drastically simplifies their usage\n- Extended ability to pass values of type `[const] void *`\n- `keep_alive` fix: don't fail when there is no patient\n- `functional.h`: acquire the GIL before calling a Python function\n- Added Python RAII type wrappers `none` and `iterable`\n- Added `*args` and `*kwargs` pass-through parameters to\n  `pybind11.get_include()` function\n- Iterator improvements and fixes\n- Documentation on return value policies and opaque types improved\n\n## 1.6 (April 30, 2016)\n\n- Skipped due to upload to PyPI gone wrong and inability to recover\n  (<https://github.com/pypa/packaging-problems/issues/74>)\n\n## 1.5 (April 21, 2016)\n\n- For polymorphic types, use RTTI to try to return the closest type\n  registered with pybind11\n- Pickling support for serializing and unserializing C++ instances to a\n  byte stream in Python\n- Added a convenience routine `make_iterator()` which turns a range\n  indicated by a pair of C++ iterators into a iterable Python object\n- Added `len()` and a variadic `make_tuple()` function\n- Addressed a rare issue that could confuse the current virtual function\n  dispatcher and another that could lead to crashes in multi-threaded\n  applications\n- Added a `get_include()` function to the Python module that returns the\n  path of the directory containing the installed pybind11 header files\n- Documentation improvements: import issues, symbol visibility,\n  pickling, limitations\n- Added casting support for `std::reference_wrapper<>`\n\n## 1.4 (April 7, 2016)\n\n- Transparent type conversion for `std::wstring` and `wchar_t`\n- Allow passing `nullptr`-valued strings\n- Transparent passing of `void *` pointers using capsules\n- Transparent support for returning values wrapped in\n  `std::unique_ptr<>`\n- Improved docstring generation for compatibility with Sphinx\n- Nicer debug error message when default parameter construction fails\n- Support for \"opaque\" types that bypass the transparent conversion\n  layer for STL containers\n- Redesigned type casting interface to avoid ambiguities that could\n  occasionally cause compiler errors\n- Redesigned property implementation; fixes crashes due to an\n  unfortunate default return value policy\n- Anaconda package generation support\n\n## 1.3 (March 8, 2016)\n\n- Added support for the Intel C++ compiler (v15+)\n- Added support for the STL unordered set/map data structures\n- Added support for the STL linked list data structure\n- NumPy-style broadcasting support in `pybind11::vectorize`\n- pybind11 now displays more verbose error messages when\n  `arg::operator=()` fails\n- pybind11 internal data structures now live in a version-dependent\n  namespace to avoid ABI issues\n- Many, many bugfixes involving corner cases and advanced usage\n\n## 1.2 (February 7, 2016)\n\n- Optional: efficient generation of function signatures at compile time\n  using C++14\n- Switched to a simpler and more general way of dealing with function\n  default arguments. Unused keyword arguments in function calls are now\n  detected and cause errors as expected\n- New `keep_alive` call policy analogous to Boost.Python's\n  `with_custodian_and_ward`\n- New `pybind11::base<>` attribute to indicate a subclass relationship\n- Improved interface for RAII type wrappers in `pytypes.h`\n- Use RAII type wrappers consistently within pybind11 itself. This fixes\n  various potential refcount leaks when exceptions occur\n- Added new `bytes` RAII type wrapper (maps to `string` in Python 2.7)\n- Made handle and related RAII classes const correct, using them more\n  consistently everywhere now\n- Got rid of the ugly `__pybind11__` attributes on the Python\n  side---they are now stored in a C++ hash table that is not visible in\n  Python\n- Fixed refcount leaks involving NumPy arrays and bound functions\n- Vastly improved handling of shared/smart pointers\n- Removed an unnecessary copy operation in `pybind11::vectorize`\n- Fixed naming clashes when both pybind11 and NumPy headers are included\n- Added conversions for additional exception types\n- Documentation improvements (using multiple extension modules, smart\n  pointers, other minor clarifications)\n- unified infrastructure for parsing variadic arguments in `class_` and\n  cpp_function\n- Fixed license text (was: ZLIB, should have been: 3-clause BSD)\n- Python 3.2 compatibility\n- Fixed remaining issues when accessing types in another plugin module\n- Added enum comparison and casting methods\n- Improved SFINAE-based detection of whether types are\n  copy-constructible\n- Eliminated many warnings about unused variables and the use of\n  `offsetof()`\n- Support for `std::array<>` conversions\n\n## 1.1 (December 7, 2015)\n\n- Documentation improvements (GIL, wrapping functions, casting, fixed\n  many typos)\n- Generalized conversion of integer types\n- Improved support for casting function objects\n- Improved support for `std::shared_ptr<>` conversions\n- Initial support for `std::set<>` conversions\n- Fixed type resolution issue for types defined in a separate plugin\n  module\n- CMake build system improvements\n- Factored out generic functionality to non-templated code (smaller code\n  size)\n- Added a code size / compile time benchmark vs Boost.Python\n- Added an appveyor CI script\n\n## 1.0 (October 15, 2015)\n\n- Initial release\n"
  },
  {
    "path": "docs/classes.rst",
    "content": ".. _classes:\n\nObject-oriented code\n####################\n\nCreating bindings for a custom type\n===================================\n\nLet's now look at a more complex example where we'll create bindings for a\ncustom C++ data structure named ``Pet``. Its definition is given below:\n\n.. code-block:: cpp\n\n    struct Pet {\n        Pet(const std::string &name) : name(name) { }\n        void setName(const std::string &name_) { name = name_; }\n        const std::string &getName() const { return name; }\n\n        std::string name;\n    };\n\nThe binding code for ``Pet`` looks as follows:\n\n.. code-block:: cpp\n\n    #include <pybind11/pybind11.h>\n\n    namespace py = pybind11;\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Pet>(m, \"Pet\")\n            .def(py::init<const std::string &>())\n            .def(\"setName\", &Pet::setName)\n            .def(\"getName\", &Pet::getName);\n    }\n\n``py::class_`` creates bindings for a C++ *class* or *struct*-style data\nstructure. :func:`init` is a convenience function that takes the types of a\nconstructor's parameters as template arguments and wraps the corresponding\nconstructor (see the :ref:`custom_constructors` section for details).\n\n.. note::\n\n    Starting with pybind11v3, it is recommended to include `py::smart_holder`\n    in most situations for safety, especially if you plan to support conversions\n    to C++ smart pointers. See :ref:`smart_holder` for more information.\n\nAn interactive Python session demonstrating this example is shown below:\n\n.. code-block:: pycon\n\n    % python\n    >>> import example\n    >>> p = example.Pet(\"Molly\")\n    >>> print(p)\n    <example.Pet object at 0x10cd98060>\n    >>> p.getName()\n    'Molly'\n    >>> p.setName(\"Charly\")\n    >>> p.getName()\n    'Charly'\n\n.. seealso::\n\n    Static member functions can be bound in the same way using\n    :func:`class_::def_static`.\n\n.. note::\n\n    Binding C++ types in unnamed namespaces (also known as anonymous namespaces)\n    works reliably on many platforms, but not all. The `XFAIL_CONDITION` in\n    tests/test_unnamed_namespace_a.py encodes the currently known conditions.\n    For background see `#4319 <https://github.com/pybind/pybind11/pull/4319>`_.\n    If portability is a concern, it is therefore not recommended to bind C++\n    types in unnamed namespaces. It will be safest to manually pick unique\n    namespace names.\n\nKeyword and default arguments\n=============================\nIt is possible to specify keyword and default arguments using the syntax\ndiscussed in the previous chapter. Refer to the sections :ref:`keyword_args`\nand :ref:`default_args` for details.\n\nBinding lambda functions\n========================\n\nNote how ``print(p)`` produced a rather useless summary of our data structure in the example above:\n\n.. code-block:: pycon\n\n    >>> print(p)\n    <example.Pet object at 0x10cd98060>\n\nTo address this, we could bind a utility function that returns a human-readable\nsummary to the special method slot named ``__repr__``. Unfortunately, there is no\nsuitable functionality in the ``Pet`` data structure, and it would be nice if\nwe did not have to change it. This can easily be accomplished by binding a\nLambda function instead:\n\n.. code-block:: cpp\n\n        py::class_<Pet>(m, \"Pet\")\n            .def(py::init<const std::string &>())\n            .def(\"setName\", &Pet::setName)\n            .def(\"getName\", &Pet::getName)\n            .def(\"__repr__\",\n                [](const Pet &a) {\n                    return \"<example.Pet named '\" + a.name + \"'>\";\n                }\n            );\n\nBoth stateless [#f1]_ and stateful lambda closures are supported by pybind11.\nWith the above change, the same Python code now produces the following output:\n\n.. code-block:: pycon\n\n    >>> print(p)\n    <example.Pet named 'Molly'>\n\n.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.\n\n.. _properties:\n\nInstance and static fields\n==========================\n\nWe can also directly expose the ``name`` field using the\n:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`\nmethod also exists for ``const`` fields.\n\n.. code-block:: cpp\n\n        py::class_<Pet>(m, \"Pet\")\n            .def(py::init<const std::string &>())\n            .def_readwrite(\"name\", &Pet::name)\n            // ... remainder ...\n\nThis makes it possible to write\n\n.. code-block:: pycon\n\n    >>> p = example.Pet(\"Molly\")\n    >>> p.name\n    'Molly'\n    >>> p.name = \"Charly\"\n    >>> p.name\n    'Charly'\n\nNow suppose that ``Pet::name`` was a private internal variable\nthat can only be accessed via setters and getters.\n\n.. code-block:: cpp\n\n    class Pet {\n    public:\n        Pet(const std::string &name) : name(name) { }\n        void setName(const std::string &name_) { name = name_; }\n        const std::string &getName() const { return name; }\n    private:\n        std::string name;\n    };\n\nIn this case, the method :func:`class_::def_property`\n(:func:`class_::def_property_readonly` for read-only data) can be used to\nprovide a field-like interface within Python that will transparently call\nthe setter and getter functions:\n\n.. code-block:: cpp\n\n        py::class_<Pet>(m, \"Pet\")\n            .def(py::init<const std::string &>())\n            .def_property(\"name\", &Pet::getName, &Pet::setName)\n            // ... remainder ...\n\nWrite only properties can be defined by passing ``nullptr`` as the\ninput for the read function.\n\n.. seealso::\n\n    Similar functions :func:`class_::def_readwrite_static`,\n    :func:`class_::def_readonly_static` :func:`class_::def_property_static`,\n    and :func:`class_::def_property_readonly_static` are provided for binding\n    static variables and properties. Please also see the section on\n    :ref:`static_properties` in the advanced part of the documentation.\n\nDynamic attributes\n==================\n\nNative Python classes can pick up new attributes dynamically:\n\n.. code-block:: pycon\n\n    >>> class Pet:\n    ...     name = \"Molly\"\n    ...\n    >>> p = Pet()\n    >>> p.name = \"Charly\"  # overwrite existing\n    >>> p.age = 2  # dynamically add a new attribute\n\nBy default, classes exported from C++ do not support this and the only writable\nattributes are the ones explicitly defined using :func:`class_::def_readwrite`\nor :func:`class_::def_property`.\n\n.. code-block:: cpp\n\n    py::class_<Pet>(m, \"Pet\")\n        .def(py::init<>())\n        .def_readwrite(\"name\", &Pet::name);\n\nTrying to set any other attribute results in an error:\n\n.. code-block:: pycon\n\n    >>> p = example.Pet()\n    >>> p.name = \"Charly\"  # OK, attribute defined in C++\n    >>> p.age = 2  # fail\n    AttributeError: 'Pet' object has no attribute 'age'\n\nTo enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag\nmust be added to the :class:`py::class_` constructor:\n\n.. code-block:: cpp\n\n    py::class_<Pet>(m, \"Pet\", py::dynamic_attr())\n        .def(py::init<>())\n        .def_readwrite(\"name\", &Pet::name);\n\nNow everything works as expected:\n\n.. code-block:: pycon\n\n    >>> p = example.Pet()\n    >>> p.name = \"Charly\"  # OK, overwrite value in C++\n    >>> p.age = 2  # OK, dynamically add a new attribute\n    >>> p.__dict__  # just like a native Python class\n    {'age': 2}\n\nNote that there is a small runtime cost for a class with dynamic attributes.\nNot only because of the addition of a ``__dict__``, but also because of more\nexpensive garbage collection tracking which must be activated to resolve\npossible circular references. Native Python classes incur this same cost by\ndefault, so this is not anything to worry about. By default, pybind11 classes\nare more efficient than native Python classes. Enabling dynamic attributes\njust brings them on par.\n\n.. _inheritance:\n\nInheritance and automatic downcasting\n=====================================\n\nSuppose now that the example consists of two data structures with an\ninheritance relationship:\n\n.. code-block:: cpp\n\n    struct Pet {\n        Pet(const std::string &name) : name(name) { }\n        std::string name;\n    };\n\n    struct Dog : Pet {\n        Dog(const std::string &name) : Pet(name) { }\n        std::string bark() const { return \"woof!\"; }\n    };\n\nThere are two different ways of indicating a hierarchical relationship to\npybind11: the first specifies the C++ base class as an extra template\nparameter of the ``py::class_``:\n\n.. code-block:: cpp\n\n    py::class_<Pet>(m, \"Pet\")\n       .def(py::init<const std::string &>())\n       .def_readwrite(\"name\", &Pet::name);\n\n    // Method 1: template parameter:\n    py::class_<Dog, Pet /* <- specify C++ parent type */>(m, \"Dog\")\n        .def(py::init<const std::string &>())\n        .def(\"bark\", &Dog::bark);\n\nAlternatively, we can also assign a name to the previously bound ``Pet``\n``py::class_`` object and reference it when binding the ``Dog`` class:\n\n.. code-block:: cpp\n\n    py::class_<Pet> pet(m, \"Pet\");\n    pet.def(py::init<const std::string &>())\n       .def_readwrite(\"name\", &Pet::name);\n\n    // Method 2: pass parent class_ object:\n    py::class_<Dog>(m, \"Dog\", pet /* <- specify Python parent type */)\n        .def(py::init<const std::string &>())\n        .def(\"bark\", &Dog::bark);\n\nFunctionality-wise, both approaches are equivalent. Afterwards, instances will\nexpose fields and methods of both types:\n\n.. code-block:: pycon\n\n    >>> p = example.Dog(\"Molly\")\n    >>> p.name\n    'Molly'\n    >>> p.bark()\n    'woof!'\n\nThe C++ classes defined above are regular non-polymorphic types with an\ninheritance relationship. This is reflected in Python:\n\n.. code-block:: cpp\n\n    // Return a base pointer to a derived instance\n    m.def(\"pet_store\", []() { return std::unique_ptr<Pet>(new Dog(\"Molly\")); });\n\n.. code-block:: pycon\n\n    >>> p = example.pet_store()\n    >>> type(p)  # `Dog` instance behind `Pet` pointer\n    Pet          # no pointer downcasting for regular non-polymorphic types\n    >>> p.bark()\n    AttributeError: 'Pet' object has no attribute 'bark'\n\nThe function returned a ``Dog`` instance, but because it's a non-polymorphic\ntype behind a base pointer, Python only sees a ``Pet``. In C++, a type is only\nconsidered polymorphic if it has at least one virtual function and pybind11\nwill automatically recognize this:\n\n.. code-block:: cpp\n\n    struct PolymorphicPet {\n        virtual ~PolymorphicPet() = default;\n    };\n\n    struct PolymorphicDog : PolymorphicPet {\n        std::string bark() const { return \"woof!\"; }\n    };\n\n    // Same binding code\n    py::class_<PolymorphicPet>(m, \"PolymorphicPet\");\n    py::class_<PolymorphicDog, PolymorphicPet>(m, \"PolymorphicDog\")\n        .def(py::init<>())\n        .def(\"bark\", &PolymorphicDog::bark);\n\n    // Again, return a base pointer to a derived instance\n    m.def(\"pet_store2\", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });\n\n.. code-block:: pycon\n\n    >>> p = example.pet_store2()\n    >>> type(p)\n    PolymorphicDog  # automatically downcast\n    >>> p.bark()\n    'woof!'\n\nGiven a pointer to a polymorphic base, pybind11 performs automatic downcasting\nto the actual derived type. Note that this goes beyond the usual situation in\nC++: we don't just get access to the virtual functions of the base, we get the\nconcrete derived type including functions and attributes that the base type may\nnot even be aware of.\n\n.. seealso::\n\n    For more information about polymorphic behavior see :ref:`overriding_virtuals`.\n\n\nOverloaded methods\n==================\n\nSometimes there are several overloaded C++ methods with the same name taking\ndifferent kinds of input arguments:\n\n.. code-block:: cpp\n\n    struct Pet {\n        Pet(const std::string &name, int age) : name(name), age(age) { }\n\n        void set(int age_) { age = age_; }\n        void set(const std::string &name_) { name = name_; }\n\n        std::string name;\n        int age;\n    };\n\nAttempting to bind ``Pet::set`` will cause an error since the compiler does not\nknow which method the user intended to select. We can disambiguate by casting\nthem to function pointers. Binding multiple functions to the same Python name\nautomatically creates a chain of function overloads that will be tried in\nsequence.\n\n.. code-block:: cpp\n\n    py::class_<Pet>(m, \"Pet\")\n       .def(py::init<const std::string &, int>())\n       .def(\"set\", static_cast<void (Pet::*)(int)>(&Pet::set), \"Set the pet's age\")\n       .def(\"set\", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), \"Set the pet's name\");\n\nThe overload signatures are also visible in the method's docstring:\n\n.. code-block:: pycon\n\n    >>> help(example.Pet)\n\n    class Pet(__builtin__.object)\n     |  Methods defined here:\n     |\n     |  __init__(...)\n     |      Signature : (Pet, str, int) -> NoneType\n     |\n     |  set(...)\n     |      1. Signature : (Pet, int) -> NoneType\n     |\n     |      Set the pet's age\n     |\n     |      2. Signature : (Pet, str) -> NoneType\n     |\n     |      Set the pet's name\n\nIf you have a C++14 compatible compiler [#cpp14]_, you can use an alternative\nsyntax to cast the overloaded function:\n\n.. code-block:: cpp\n\n    py::class_<Pet>(m, \"Pet\")\n        .def(\"set\", py::overload_cast<int>(&Pet::set), \"Set the pet's age\")\n        .def(\"set\", py::overload_cast<const std::string &>(&Pet::set), \"Set the pet's name\");\n\nHere, ``py::overload_cast`` only requires the parameter types to be specified.\nThe return type and class are deduced. This avoids the additional noise of\n``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based\non constness, the ``py::const_`` tag should be used:\n\n.. code-block:: cpp\n\n    struct Widget {\n        int foo(int x, float y);\n        int foo(int x, float y) const;\n    };\n\n    py::class_<Widget>(m, \"Widget\")\n       .def(\"foo_mutable\", py::overload_cast<int, float>(&Widget::foo))\n       .def(\"foo_const\",   py::overload_cast<int, float>(&Widget::foo, py::const_));\n\nIf you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,\nyou can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:\n\n.. code-block:: cpp\n\n    template <typename... Args>\n    using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;\n\n    py::class_<Pet>(m, \"Pet\")\n        .def(\"set\", overload_cast_<int>()(&Pet::set), \"Set the pet's age\")\n        .def(\"set\", overload_cast_<const std::string &>()(&Pet::set), \"Set the pet's name\");\n\n.. [#cpp14] A compiler which supports the ``-std=c++14`` flag.\n\n.. note::\n\n    To define multiple overloaded constructors, simply declare one after the\n    other using the ``.def(py::init<...>())`` syntax. The existing machinery\n    for specifying keyword and default arguments also works.\n\n☝️ Pitfalls with raw pointers and shared ownership\n==================================================\n\n``py::class_``-wrapped objects automatically manage the lifetime of the\nwrapped C++ object, in collaboration with the chosen holder type (see\n:ref:`py_class_holder`). When wrapping C++ functions involving raw pointers,\ncare needs to be taken to not accidentally undermine automatic lifetime\nmanagement. For example, ownership is inadvertently transferred here:\n\n.. code-block:: cpp\n\n    class Child { };\n\n    class Parent {\n    public:\n       Parent() : child(std::make_shared<Child>()) { }\n       Child *get_child() { return child.get(); }  /* DANGER */\n    private:\n        std::shared_ptr<Child> child;\n    };\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        py::class_<Child, std::shared_ptr<Child>>(m, \"Child\");\n\n        py::class_<Parent, std::shared_ptr<Parent>>(m, \"Parent\")\n           .def(py::init<>())\n           .def(\"get_child\", &Parent::get_child);  /* PROBLEM */\n    }\n\nThe following Python code leads to undefined behavior, likely resulting in\na segmentation fault.\n\n.. code-block:: python\n\n   from example import Parent\n\n   print(Parent().get_child())\n\nPart of the ``/* PROBLEM */`` here is that pybind11 falls back to using\n``return_value_policy::take_ownership`` as the default (see\n:ref:`return_value_policies`). The fact that the ``Child`` instance is\nalready managed by ``std::shared_ptr<Child>`` is lost. Therefore pybind11\nwill create a second independent ``std::shared_ptr<Child>`` that also\nclaims ownership of the pointer, eventually leading to heap-use-after-free\nor double-free errors.\n\nThere are various ways to resolve this issue, either by changing\nthe ``Child`` or ``Parent`` C++ implementations (e.g. using\n``std::enable_shared_from_this<Child>`` as a base class for\n``Child``, or adding a member function to ``Parent`` that returns\n``std::shared_ptr<Child>``), or if that is not feasible, by using\n``return_value_policy::reference_internal``. What is the best approach\ndepends on the exact situation.\n\nA highly effective way to stay in the clear — even in pure C++, but\nespecially when binding C++ code to Python — is to consistently prefer\n``std::shared_ptr`` or ``std::unique_ptr`` over passing raw pointers.\n\n.. _native_enum:\n\nEnumerations and internal types\n===============================\n\nLet's now suppose that the example class contains internal types like enumerations, e.g.:\n\n.. code-block:: cpp\n\n    struct Pet {\n        enum Kind {\n            Dog = 0,\n            Cat\n        };\n\n        struct Attributes {\n            float age = 0;\n        };\n\n        Pet(const std::string &name, Kind type) : name(name), type(type) { }\n\n        std::string name;\n        Kind type;\n        Attributes attr;\n    };\n\nThe binding code for this example looks as follows:\n\n.. code-block:: cpp\n\n    #include <pybind11/native_enum.h> // Not already included with pybind11.h\n\n    py::class_<Pet> pet(m, \"Pet\");\n\n    pet.def(py::init<const std::string &, Pet::Kind>())\n        .def_readwrite(\"name\", &Pet::name)\n        .def_readwrite(\"type\", &Pet::type)\n        .def_readwrite(\"attr\", &Pet::attr);\n\n    py::native_enum<Pet::Kind>(pet, \"Kind\", \"enum.Enum\")\n        .value(\"Dog\", Pet::Kind::Dog)\n        .value(\"Cat\", Pet::Kind::Cat)\n        .export_values()\n        .finalize();\n\n    py::class_<Pet::Attributes>(pet, \"Attributes\")\n        .def(py::init<>())\n        .def_readwrite(\"age\", &Pet::Attributes::age);\n\n\nTo ensure that the nested types ``Kind`` and ``Attributes`` are created\nwithin the scope of ``Pet``, the ``pet`` ``py::class_`` instance must be\nsupplied to the ``py::native_enum`` and ``py::class_`` constructors. The\n``.export_values()`` function is available for exporting the enum entries\ninto the parent scope, if desired.\n\n``py::native_enum`` was introduced with pybind11v3. It binds C++ enum types\nto native Python enum types, typically types in Python's\n`stdlib enum <https://docs.python.org/3/library/enum.html>`_ module,\nwhich are `PEP 435 compatible <https://peps.python.org/pep-0435/>`_.\nThis is the recommended way to bind C++ enums.\nThe older ``py::enum_`` is not PEP 435 compatible\n(see `issue #2332 <https://github.com/pybind/pybind11/issues/2332>`_)\nbut remains supported indefinitely for backward compatibility.\nNew bindings should prefer ``py::native_enum``.\n\n.. note::\n\n    The deprecated ``py::enum_`` is :ref:`documented here <deprecated_enum>`.\n\nThe ``.finalize()`` call above is needed because Python's native enums\ncannot be built incrementally — all name/value pairs need to be passed at\nonce. To achieve this, ``py::native_enum`` acts as a buffer to collect the\nname/value pairs. The ``.finalize()`` call uses the accumulated name/value\npairs to build the arguments for constructing a native Python enum type.\n\nThe ``py::native_enum`` constructor takes a third argument,\n``native_type_name``, which specifies the fully qualified name of the Python\nbase class to use — e.g., ``\"enum.Enum\"`` or ``\"enum.IntEnum\"``. A fourth\noptional argument, ``class_doc``, provides the docstring for the generated\nclass.\n\nFor example:\n\n.. code-block:: cpp\n\n    py::native_enum<Pet::Kind>(pet, \"Kind\", \"enum.IntEnum\", \"Constant specifying the kind of pet\")\n\nYou may use any fully qualified Python name for ``native_type_name``.\nThe only requirement is that the named type is similar to\n`enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>`_\nin these ways:\n\n* Has a `constructor similar to that of enum.Enum\n  <https://docs.python.org/3/howto/enum.html#functional-api>`_::\n\n    Colors = enum.Enum(\"Colors\", ((\"Red\", 0), (\"Green\", 1)))\n\n* A `C++ underlying <https://en.cppreference.com/w/cpp/types/underlying_type>`_\n  enum value can be passed to the constructor for the Python enum value::\n\n    red = Colors(0)\n\n* The enum values have a ``.value`` property yielding a value that\n  can be cast to the C++ underlying type::\n\n    underlying = red.value\n\nAs of Python 3.13, the compatible `types in the stdlib enum module\n<https://docs.python.org/3/library/enum.html#module-contents>`_ are:\n``Enum``, ``IntEnum``, ``Flag``, ``IntFlag``.\n\n.. note::\n\n    In rare cases, a C++ enum may be bound to Python via a\n    :ref:`custom type caster <custom_type_caster>`. In such cases, a\n    template specialization like this may be required:\n\n    .. code-block:: cpp\n\n        #if defined(PYBIND11_HAS_NATIVE_ENUM)\n        namespace pybind11::detail {\n        template <typename FancyEnum>\n        struct type_caster_enum_type_enabled<\n            FancyEnum,\n            enable_if_t<is_fancy_enum<FancyEnum>::value>> : std::false_type {};\n        }\n        #endif\n\n    This specialization is needed only if the custom type caster is templated.\n\n    The ``PYBIND11_HAS_NATIVE_ENUM`` guard is needed only if backward\n    compatibility with pybind11v2 is required.\n"
  },
  {
    "path": "docs/cmake/index.rst",
    "content": "CMake helpers\n-------------\n\nPybind11 can be used with ``add_subdirectory(extern/pybind11)``, or from an\ninstall with ``find_package(pybind11 CONFIG)``. The interface provided in\neither case is functionally identical.\n\n.. cmake-module:: ../../tools/pybind11Config.cmake.in\n"
  },
  {
    "path": "docs/compiling.rst",
    "content": ".. _compiling:\n\nBuild systems\n#############\n\nFor an overview of Python packaging including compiled packaging with a pybind11\nexample, along with a cookiecutter that includes several pybind11 options, see\nthe `Scientific Python Development Guide`_.\n\n.. _Scientific Python Development Guide: https://learn.scientific-python.org/development/guides/packaging-compiled/\n\n.. scikit-build-core:\n\nModules with CMake\n==================\n\nA Python extension module can be created with just a few lines of code:\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example LANGUAGES CXX)\n\n    set(PYBIND11_FINDPYTHON ON)\n    find_package(pybind11 CONFIG REQUIRED)\n\n    pybind11_add_module(example example.cpp)\n    install(TARGETS example DESTINATION .)\n\n(You use the ``add_subdirectory`` instead, see the example in :ref:`cmake`.) In\nthis example, the code is located in a file named :file:`example.cpp`.  Either\nmethod will import the pybind11 project which provides the\n``pybind11_add_module`` function. It will take care of all the details needed\nto build a Python extension module on any platform.\n\nTo build with pip, build, cibuildwheel, uv, or other Python tools, you can\nadd a ``pyproject.toml`` file like this:\n\n.. code-block:: toml\n\n    [build-system]\n    requires = [\"scikit-build-core\", \"pybind11\"]\n    build-backend = \"scikit_build_core.build\"\n\n    [project]\n    name = \"example\"\n    version = \"0.1.0\"\n\nYou don't need setuptools files like ``MANIFEST.in``, ``setup.py``, or\n``setup.cfg``, as this is not setuptools. See `scikit-build-core`_ for details.\nFor projects you plan to upload to PyPI, be sure to fill out the ``[project]``\ntable with other important metadata as well (see `Writing pyproject.toml`_).\n\nA working sample project can be found in the [scikit_build_example]_\nrepository. An older and harder-to-maintain method is in [cmake_example]_. More\ndetails about our cmake support can be found below in :ref:`cmake`.\n\n.. _scikit-build-core: https://scikit-build-core.readthedocs.io\n\n.. [scikit_build_example] https://github.com/pybind/scikit_build_example\n\n.. [cmake_example] https://github.com/pybind/cmake_example\n\n.. _modules-meson-python:\n\nModules with meson-python\n=========================\n\nYou can also build a package with `Meson`_ using `meson-python`_, if you prefer\nthat. Your ``meson.build`` file would look something like this:\n\n.. _meson-example:\n\n.. code-block:: meson\n\n   project(\n       'example',\n       'cpp',\n       version: '0.1.0',\n       default_options: [\n           'cpp_std=c++11',\n       ],\n   )\n\n   py = import('python').find_installation(pure: false)\n   pybind11_dep = dependency('pybind11')\n\n   py.extension_module('example',\n       'example.cpp',\n       install: true,\n       dependencies : [pybind11_dep],\n   )\n\n\nAnd you would need a ``pyproject.toml`` file like this:\n\n.. code-block:: toml\n\n   [build-system]\n   requires = [\"meson-python\", \"pybind11\"]\n   build-backend = \"mesonpy\"\n\nMeson-python *requires* your project to be in git (or mercurial) as it uses it\nfor the SDist creation. For projects you plan to upload to PyPI, be sure to fill out the\n``[project]`` table as well (see `Writing pyproject.toml`_).\n\n\n.. _Writing pyproject.toml: https://packaging.python.org/en/latest/guides/writing-pyproject-toml\n\n.. _meson: https://mesonbuild.com\n\n.. _meson-python: https://meson-python.readthedocs.io/en/latest\n\n.. _build-setuptools:\n\nModules with setuptools\n=======================\n\nFor projects on PyPI, a historically popular option is setuptools. Sylvain\nCorlay has kindly provided an example project which shows how to set up\neverything, including automatic generation of documentation using Sphinx.\nPlease refer to the [python_example]_ repository.\n\n.. [python_example] https://github.com/pybind/python_example\n\nA helper file is provided with pybind11 that can simplify usage with setuptools.\n\nTo use pybind11 inside your ``setup.py``, you have to have some system to\nensure that ``pybind11`` is installed when you build your package. There are\nfour possible ways to do this, and pybind11 supports all four: You can ask all\nusers to install pybind11 beforehand (bad), you can use\n:ref:`setup_helpers-pep518` (good), ``setup_requires=`` (discouraged), or you\ncan :ref:`setup_helpers-copy-manually` (works but you have to manually sync\nyour copy to get updates). Third party packagers like conda-forge generally\nstrongly prefer the ``pyproject.toml`` method, as it gives them control over\nthe ``pybind11`` version, and they may apply patches, etc.\n\nAn example of a ``setup.py`` using pybind11's helpers:\n\n.. code-block:: python\n\n    from glob import glob\n    from setuptools import setup\n    from pybind11.setup_helpers import Pybind11Extension\n\n    ext_modules = [\n        Pybind11Extension(\n            \"python_example\",\n            sorted(glob(\"src/*.cpp\")),  # Sort source files for reproducibility\n        ),\n    ]\n\n    setup(..., ext_modules=ext_modules)\n\nIf you want to do an automatic search for the highest supported C++ standard,\nthat is supported via a ``build_ext`` command override; it will only affect\n``Pybind11Extensions``:\n\n.. code-block:: python\n\n    from glob import glob\n    from setuptools import setup\n    from pybind11.setup_helpers import Pybind11Extension, build_ext\n\n    ext_modules = [\n        Pybind11Extension(\n            \"python_example\",\n            sorted(glob(\"src/*.cpp\")),\n        ),\n    ]\n\n    setup(..., cmdclass={\"build_ext\": build_ext}, ext_modules=ext_modules)\n\nIf you have single-file extension modules that are directly stored in the\nPython source tree (``foo.cpp`` in the same directory as where a ``foo.py``\nwould be located), you can also generate ``Pybind11Extensions`` using\n``setup_helpers.intree_extensions``: ``intree_extensions([\"path/to/foo.cpp\",\n...])`` returns a list of ``Pybind11Extensions`` which can be passed to\n``ext_modules``, possibly after further customizing their attributes\n(``libraries``, ``include_dirs``, etc.).  By doing so, a ``foo.*.so`` extension\nmodule will be generated and made available upon installation.\n\n``intree_extension`` will automatically detect if you are using a ``src``-style\nlayout (as long as no namespace packages are involved), but you can also\nexplicitly pass ``package_dir`` to it (as in ``setuptools.setup``).\n\nSince pybind11 does not require NumPy when building, a light-weight replacement\nfor NumPy's parallel compilation distutils tool is included. Use it like this:\n\n.. code-block:: python\n\n    from pybind11.setup_helpers import ParallelCompile\n\n    # Optional multithreaded build\n    ParallelCompile(\"NPY_NUM_BUILD_JOBS\").install()\n\n    setup(...)\n\nThe argument is the name of an environment variable to control the number of\nthreads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set\nsomething different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice\na user might expect. You can also pass ``default=N`` to set the default number\nof threads (0 will take the number of threads available) and ``max=N``, the\nmaximum number of threads; if you have a large extension you may want set this\nto a memory dependent number.\n\nIf you are developing rapidly and have a lot of C++ files, you may want to\navoid rebuilding files that have not changed. For simple cases were you are\nusing ``pip install -e .`` and do not have local headers, you can skip the\nrebuild if an object file is newer than its source (headers are not checked!)\nwith the following:\n\n.. code-block:: python\n\n    from pybind11.setup_helpers import ParallelCompile, naive_recompile\n\n    ParallelCompile(\"NPY_NUM_BUILD_JOBS\", needs_recompile=naive_recompile).install()\n\n\nIf you have a more complex build, you can implement a smarter function and pass\nit to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX=\"cache g++\"\npip install -e .`` would be the way to use it with GCC, for example. Unlike the\nsimple solution, this even works even when not compiling in editable mode, but\nit does require Ccache to be installed.\n\nKeep in mind that Pip will not even attempt to rebuild if it thinks it has\nalready built a copy of your code, which it deduces from the version number.\nOne way to avoid this is to use [setuptools_scm]_, which will generate a\nversion number that includes the number of commits since your last tag and a\nhash for a dirty directory. Another way to force a rebuild is purge your cache\nor use Pip's ``--no-cache-dir`` option.\n\nYou also need a ``MANIFEST.in`` file to include all relevant files so that you\ncan make an SDist. If you use `pypa-build`_, that will build an SDist then a\nwheel from that SDist by default, so you can look inside those files (wheels\nare just zip files with a ``.whl`` extension) to make sure you aren't missing\nfiles.  `check-manifest`_ (setuptools specific) or `check-sdist`_ (general) are\nCLI tools that can compare the SDist contents with your source control.\n\n.. [Ccache] https://ccache.dev\n\n.. [setuptools_scm] https://github.com/pypa/setuptools_scm\n\n.. _setup_helpers-pep518:\n\nBuild requirements\n------------------\n\nWith a ``pyproject.toml`` file, you can ensure that ``pybind11`` is available\nduring the compilation of your project.  When this file exists, Pip will make a\nnew virtual environment, download just the packages listed here in\n``requires=``, and build a wheel (binary Python package). It will then throw\naway the environment, and install your wheel.\n\nYour ``pyproject.toml`` file will likely look something like this:\n\n.. code-block:: toml\n\n    [build-system]\n    requires = [\"setuptools\", \"pybind11\"]\n    build-backend = \"setuptools.build_meta\"\n\n.. _PEP 517: https://www.python.org/dev/peps/pep-0517/\n.. _cibuildwheel: https://cibuildwheel.pypa.io\n.. _pypa-build: https://build.pypa.io/en/latest/\n.. _check-manifest: https://pypi.io/project/check-manifest\n.. _check-sdist: https://pypi.io/project/check-sdist\n\n.. _setup_helpers-copy-manually:\n\nCopy manually\n-------------\n\nYou can also copy ``setup_helpers.py`` directly to your project; it was\ndesigned to be usable standalone, like the old example ``setup.py``. You can\nset ``include_pybind11=False`` to skip including the pybind11 package headers,\nso you can use it with git submodules and a specific git version. If you use\nthis, you will need to import from a local file in ``setup.py`` and ensure the\nhelper file is part of your MANIFEST.\n\n\nClosely related, if you include pybind11 as a subproject, you can run the\n``setup_helpers.py`` inplace. If loaded correctly, this should even pick up\nthe correct include for pybind11, though you can turn it off as shown above if\nyou want to input it manually.\n\nSuggested usage if you have pybind11 as a submodule in ``extern/pybind11``:\n\n.. code-block:: python\n\n    DIR = os.path.abspath(os.path.dirname(__file__))\n\n    sys.path.append(os.path.join(DIR, \"extern\", \"pybind11\"))\n    from pybind11.setup_helpers import Pybind11Extension  # noqa: E402\n\n    del sys.path[-1]\n\n\n.. versionchanged:: 2.6\n\n    Added ``setup_helpers`` file.\n\nBuilding with cppimport\n========================\n\n[cppimport]_ is a small Python import hook that determines whether there is a C++\nsource file whose name matches the requested module. If there is, the file is\ncompiled as a Python extension using pybind11 and placed in the same folder as\nthe C++ source file. Python is then able to find the module and load it.\n\n.. [cppimport] https://github.com/tbenthompson/cppimport\n\n\n\n.. _cmake:\n\nBuilding with CMake\n===================\n\nFor C++ codebases that have an existing CMake-based build system, a Python\nextension module can be created with just a few lines of code, as seen above in\nthe module section. Pybind11 currently defaults to the old mechanism, though be\naware that CMake 3.27 removed the old mechanism, so pybind11 will automatically\nswitch if the old mechanism is not available. Please opt into the new mechanism\nif at all possible. Our default may change in future versions. This is the\nminimum required:\n\n\n\n.. versionchanged:: 2.6\n   CMake 3.4+ is required.\n\n.. versionchanged:: 2.11\n   CMake 3.5+ is required.\n\n.. versionchanged:: 2.14\n   CMake 3.15+ is required.\n\n\nFurther information can be found at :doc:`cmake/index`.\n\npybind11_add_module\n-------------------\n\nTo ease the creation of Python extension modules, pybind11 provides a CMake\nfunction with the following signature:\n\n.. code-block:: cmake\n\n    pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]\n                        [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])\n\nThis function behaves very much like CMake's builtin ``add_library`` (in fact,\nit's a wrapper function around that command). It will add a library target\ncalled ``<name>`` to be built from the listed source files. In addition, it\nwill take care of all the Python-specific compiler and linker flags as well\nas the OS- and Python-version-specific file extension. The produced target\n``<name>`` can be further manipulated with regular CMake commands.\n\n``MODULE`` or ``SHARED`` may be given to specify the type of library. If no\ntype is given, ``MODULE`` is used by default which ensures the creation of a\nPython-exclusive module. Specifying ``SHARED`` will create a more traditional\ndynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``\nremoves this target from the default build (see CMake docs for details).\n\nSince pybind11 is a template library, ``pybind11_add_module`` adds compiler\nflags to ensure high quality code generation without bloat arising from long\nsymbol names and duplication of code in different translation units. It\nsets default visibility to *hidden*, which is required for some pybind11\nfeatures and functionality when attempting to load multiple pybind11 modules\ncompiled under different pybind11 versions.  It also adds additional flags\nenabling LTO (Link Time Optimization) and strip unneeded symbols. See the\n:ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These\nlatter optimizations are never applied in ``Debug`` mode.  If ``NO_EXTRAS`` is\ngiven, they will always be disabled, even in ``Release`` mode. However, this\nwill result in code bloat and is generally not recommended.\n\nAs stated above, LTO is enabled by default. Some newer compilers also support\ndifferent flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause\nthe function to prefer this flavor if available. The function falls back to\nregular LTO if ``-flto=thin`` is not available. If\n``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then\nthat will be respected instead of the built-in flag search.\n\n.. note::\n\n   If you want to set the property form on targets or the\n   ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`` versions of this, you should\n   still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a\n   no-op) to disable pybind11's ipo flags.\n\nThe ``OPT_SIZE`` flag enables size-based optimization equivalent to the\nstandard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,\nwhich avoid optimizations that can substantially increase the size of the\nresulting binary. This flag is particularly useful in projects that are split\ninto performance-critical parts and associated bindings. In this case, we can\ncompile the project in release mode (and hence, optimize performance globally),\nand specify ``OPT_SIZE`` for the binding target, where size might be the main\nconcern as performance is often less critical here. A ~25% size reduction has\nbeen observed in practice. This flag only changes the optimization behavior at\na per-target level and takes precedence over the global CMake build type\n(``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where\noptimizations remain disabled.\n\n.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html\n\nConfiguration variables\n-----------------------\n\nBy default, pybind11 will compile modules with the compiler default or the\nminimum standard required by pybind11, whichever is higher.  You can set the\nstandard explicitly with\n`CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:\n\n.. code-block:: cmake\n\n    set(CMAKE_CXX_STANDARD 14 CACHE STRING \"C++ version selection\")  # or 11, 14, 17, 20\n    set(CMAKE_CXX_STANDARD_REQUIRED ON)  # optional, ensure standard is supported\n    set(CMAKE_CXX_EXTENSIONS OFF)  # optional, keep compiler extensions off\n\nThe variables can also be set when calling CMake from the command line using\nthe ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``\non a target or use ``target_compile_features`` on your targets - anything that\nCMake supports.\n\nClassic Python support: The target Python version can be selected by setting\n``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified\nwith ``PYTHON_EXECUTABLE``.  For example:\n\n.. code-block:: bash\n\n    cmake -DPYBIND11_PYTHON_VERSION=3.8 ..\n\n    # Another method:\n    cmake -DPYTHON_EXECUTABLE=/path/to/python ..\n\n    # This often is a good way to get the current Python, works in environments:\n    cmake -DPYTHON_EXECUTABLE=$(python3 -c \"import sys; print(sys.executable)\") ..\n\n\nfind_package vs. add_subdirectory\n---------------------------------\n\nFor CMake-based projects that don't include the pybind11 repository internally,\nan external installation can be detected through ``find_package(pybind11)``.\nSee the `Config file`_ docstring for details of relevant CMake variables.\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example LANGUAGES CXX)\n\n    find_package(pybind11 REQUIRED)\n    pybind11_add_module(example example.cpp)\n\nNote that ``find_package(pybind11)`` will only work correctly if pybind11\nhas been correctly installed on the system, e. g. after downloading or cloning\nthe pybind11 repository  :\n\n.. code-block:: bash\n\n    # Classic CMake\n    cd pybind11\n    mkdir build\n    cd build\n    cmake ..\n    make install\n\n    # CMake 3.15+\n    cd pybind11\n    cmake -S . -B build\n    cmake --build build -j 2  # Build on 2 cores\n    cmake --install build\n\nOnce detected, the aforementioned ``pybind11_add_module`` can be employed as\nbefore. The function usage and configuration variables are identical no matter\nif pybind11 is added as a subdirectory or found as an installed package. You\ncan refer to the same [cmake_example]_ repository for a full sample project\n-- just swap out ``add_subdirectory`` for ``find_package``.\n\n.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in\n\n\n.. _find-python-mode:\n\nFindPython mode\n---------------\n\nModern CMake (3.18.2+ ideal) added a new module called FindPython that had a\nhighly improved search algorithm and modern targets and tools. If you use\nFindPython, pybind11 will detect this and use the existing targets instead:\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example LANGUAGES CXX)\n\n    find_package(Python 3.8 COMPONENTS Interpreter Development REQUIRED)\n    find_package(pybind11 CONFIG REQUIRED)\n    # or add_subdirectory(pybind11)\n\n    pybind11_add_module(example example.cpp)\n\nYou can also use the targets (as listed below) with FindPython. If you define\n``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you\n(mostly useful when building pybind11's own tests, or as a way to change search\nalgorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.\n\n.. warning::\n\n    If you use FindPython to multi-target Python versions, use the individual\n    targets listed below, and avoid targets that directly include Python parts.\n\nThere are `many ways to hint or force a discovery of a specific Python\ninstallation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),\nsetting ``Python_ROOT_DIR`` may be the most common one (though with\nvirtualenv/venv support, and Conda support, this tends to find the correct\nPython version more often than the old system did).\n\n.. warning::\n\n    When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``\n    on Unix) are not available, as is the case on a manylinux image, the\n    ``Development`` component will not be resolved by ``FindPython``. When not\n    using the embedding functionality, CMake 3.18+ allows you to specify\n    ``Development.Module`` instead of ``Development`` to resolve this issue.\n\n.. versionadded:: 2.6\n\nAdvanced: interface library targets\n-----------------------------------\n\nPybind11 supports modern CMake usage patterns with a set of interface targets,\navailable in all modes. The targets provided are:\n\n   ``pybind11::headers``\n     Just the pybind11 headers and minimum compile requirements\n\n   ``pybind11::pybind11``\n     Python headers + ``pybind11::headers``\n\n   ``pybind11::python_link_helper``\n     Just the \"linking\" part of pybind11:module\n\n   ``pybind11::module``\n     Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython) or ``pybind11::python_link_helper``\n\n   ``pybind11::embed``\n     Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs\n\n   ``pybind11::lto`` / ``pybind11::thin_lto``\n     An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.\n\n   ``pybind11::windows_extras``\n     ``/bigobj`` and ``/mp`` for MSVC.\n\n   ``pybind11::opt_size``\n     ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.\n\nTwo helper functions are also provided:\n\n    ``pybind11_strip(target)``\n      Strips a target (uses ``CMAKE_STRIP`` after the target is built)\n\n    ``pybind11_extension(target)``\n      Sets the correct extension (with SOABI) for a target.\n\nYou can use these targets to build complex applications. For example, the\n``add_python_module`` function is identical to:\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example LANGUAGES CXX)\n\n    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)\n\n    add_library(example MODULE main.cpp)\n\n    target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)\n\n    pybind11_extension(example)\n    if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo)\n        # Strip unnecessary sections of the binary on Linux/macOS\n        pybind11_strip(example)\n    endif()\n\n    set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET \"hidden\"\n                                             CUDA_VISIBILITY_PRESET \"hidden\")\n\nInstead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.\n\n.. warning::\n\n    Since pybind11 is a metatemplate library, it is crucial that certain\n    compiler flags are provided to ensure high quality code generation. In\n    contrast to the ``pybind11_add_module()`` command, the CMake interface\n    provides a *composable* set of targets to ensure that you retain flexibility.\n    It can be especially important to provide or set these properties; the\n    :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.\n\n.. versionadded:: 2.6\n\n.. _nopython-mode:\n\nAdvanced: NOPYTHON mode\n-----------------------\n\nIf you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely\ndisable Python integration (this also happens if you run ``FindPython2`` and\n``FindPython3`` without running ``FindPython``). This gives you complete\nfreedom to integrate into an existing system (like `Scikit-Build's\n<https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).\n``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the\ntargets will be missing any Python specific behavior.\n\n.. versionadded:: 2.6\n\nEmbedding the Python interpreter\n--------------------------------\n\nIn addition to extension modules, pybind11 also supports embedding Python into\na C++ executable or library. In CMake, simply link with the ``pybind11::embed``\ntarget. It provides everything needed to get the interpreter running. The Python\nheaders and libraries are attached to the target. Unlike ``pybind11::module``,\nthere is no need to manually set any additional properties here. For more\ninformation about usage in C++, see :doc:`/advanced/embedding`.\n\n.. code-block:: cmake\n\n    cmake_minimum_required(VERSION 3.15...4.2)\n    project(example LANGUAGES CXX)\n\n    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)\n\n    add_executable(example main.cpp)\n    target_link_libraries(example PRIVATE pybind11::embed)\n\n.. _building_manually:\n\nBuilding manually\n=================\n\npybind11 is a header-only library, hence it is not necessary to link against\nany special libraries and there are no intermediate (magic) translation steps.\n\nOn Linux, you can compile an example such as the one given in\n:ref:`simple_example` using the following command:\n\n.. code-block:: bash\n\n    $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)\n\nThe ``python3 -m pybind11 --includes`` command fetches the include paths for\nboth pybind11 and Python headers. This assumes that pybind11 has been installed\nusing ``pip`` or ``conda``. If it hasn't, you can also manually specify\n``-I <path-to-pybind11>/include`` together with the Python includes path\n``python3-config --includes``.\n\nOn macOS: the build command is almost the same but it also requires passing\nthe ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when\nbuilding the module:\n\n.. code-block:: bash\n\n    $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)\n\nIn general, it is advisable to include several additional build parameters\nthat can considerably reduce the size of the created binary. Refer to section\n:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based\nbuild system that works on all platforms including Windows.\n\n.. note::\n\n    On Linux and macOS, it's better to (intentionally) not link against\n    ``libpython``. The symbols will be resolved when the extension library\n    is loaded into a Python binary. This is preferable because you might\n    have several different installations of a given Python version (e.g. the\n    system-provided Python, and one that ships with a piece of commercial\n    software). In this way, the plugin will work with both versions, instead\n    of possibly importing a second Python library into a process that already\n    contains one (which will lead to a segfault).\n\n\nBuilding with Bazel\n===================\n\nYou can build with the Bazel build system using the `pybind11_bazel\n<https://github.com/pybind/pybind11_bazel>`_ repository.\n\nBuilding with Meson\n===================\n\nYou can use Meson, which has support for ``pybind11`` as a dependency (internally\nrelying on our ``pkg-config`` support). See the :ref:`module example above <meson-example>`.\n\n\nGenerating binding code automatically\n=====================================\n\nThe ``Binder`` project is a tool for automatic generation of pybind11 binding\ncode by introspecting existing C++ codebases using LLVM/Clang. See the\n[binder]_ documentation for details.\n\n.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html\n\n[AutoWIG]_ is a Python library that wraps automatically compiled libraries into\nhigh-level languages. It parses C++ code using LLVM/Clang technologies and\ngenerates the wrappers using the Mako templating engine. The approach is automatic,\nextensible, and applies to very complex C++ libraries, composed of thousands of\nclasses or incorporating modern meta-programming constructs.\n\n.. [AutoWIG] https://github.com/StatisKit/AutoWIG\n\n[semiwrap]_ is a build tool that makes it simpler to wrap C/C++ libraries with\npybind11 by automating large portions of the wrapping process and handling some\nof the more complex aspects of creating pybind11 based wrappers (especially with\ntrampolines to allow inheriting from C++ classes from Python). It includes a\nhatchling plugin that autogenerates meson.build files that can be built using\nmeson, and those build files parse your wrapped headers and generate/compile\npybind11 based wrappers into python extension modules.\n\n.. [semiwrap] https://semiwrap.readthedocs.io\n\n[litgen]_ is an automatic python bindings generator with a focus on generating\ndocumented and discoverable bindings: bindings will nicely reproduce the documentation\nfound in headers. It is based on srcML (srcml.org), a highly scalable, multi-language\nparsing tool with a developer centric approach. The API that you want to expose to python\nmust be C++14 compatible (but your implementation can use more modern constructs).\n\n.. [litgen] https://pthom.github.io/litgen\n"
  },
  {
    "path": "docs/conf.py",
    "content": "#!/usr/bin/env python3\n#\n# pybind11 documentation build configuration file, created by\n# sphinx-quickstart on Sun Oct 11 19:23:48 2015.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\nfrom __future__ import annotations\n\nimport os\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nDIR = Path(__file__).parent.resolve()\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n# sys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    \"breathe\",\n    \"myst_parser\",\n    \"sphinx_copybutton\",\n    \"sphinxcontrib.rsvgconverter\",\n    \"sphinxcontrib.moderncmakedomain\",\n]\n\nbreathe_projects = {\"pybind11\": \".build/doxygenxml/\"}\nbreathe_default_project = \"pybind11\"\nbreathe_domain_by_extension = {\"h\": \"cpp\"}\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\".templates\"]\n\n# The suffix(es) of source filenames.\nsource_suffix = [\".rst\", \".md\"]\n\n# The encoding of source files.\n# source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# General information about the project.\nproject = \"pybind11\"\ncopyright = \"2017, Wenzel Jakob\"\nauthor = \"Wenzel Jakob\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n\n# Read the listed version\nversion_file = DIR.parent / \"pybind11/_version.py\"\nwith version_file.open(encoding=\"utf-8\") as f:\n    code = compile(f.read(), version_file, \"exec\")\nloc = {\"__file__\": str(version_file)}\nexec(code, loc)\n\n# The full version, including alpha/beta/rc tags.\nversion = loc[\"__version__\"]\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = \"en\"\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n# today = ''\n# Else, today_fmt is used as the format for a strftime call.\n# today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = [\".build\", \"release.rst\"]\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\ndefault_role = \"any\"\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n# add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n# add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n# show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\n# pygments_style = 'monokai'\n\n# A list of ignored prefixes for module index sorting.\n# modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n# keep_warnings = False\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n\nhtml_theme = \"furo\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n# html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n# html_theme_path = []\n\n# The name for this set of Sphinx documents.  If None, it defaults to\n# \"<project> v<version> documentation\".\n# html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n# html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n# html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n# html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\nhtml_css_files = [\n    \"css/custom.css\",\n]\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n# html_extra_path = []\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n# html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n# html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n# html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n# html_additional_pages = {}\n\n# If false, no module index is generated.\n# html_domain_indices = True\n\n# If false, no index is generated.\n# html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n# html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n# html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n# html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n# html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n# html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n# html_file_suffix = None\n\n# Language to be used for generating the HTML full-text search index.\n# Sphinx supports the following languages:\n#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'\n#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'\n# html_search_language = 'en'\n\n# A dictionary with options for the search language support, empty by default.\n# Now only 'ja' uses this config value\n# html_search_options = {'type': 'default'}\n\n# The name of a javascript file (relative to the configuration directory) that\n# implements a search results scorer. If empty, the default will be used.\n# html_search_scorer = 'scorer.js'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"pybind11doc\"\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_engine = \"pdflatex\"\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    # 'papersize': 'letterpaper',\n    #\n    # The font size ('10pt', '11pt' or '12pt').\n    # 'pointsize': '10pt',\n    #\n    # Additional stuff for the LaTeX preamble.\n    # remove blank pages (between the title page and the TOC, etc.)\n    \"classoptions\": \",openany,oneside\",\n    \"preamble\": r\"\"\"\n\\usepackage{fontawesome}\n\\usepackage{textgreek}\n\\DeclareUnicodeCharacter{00A0}{}\n\\DeclareUnicodeCharacter{2194}{\\faArrowsH}\n\\DeclareUnicodeCharacter{1F382}{\\faBirthdayCake}\n\\DeclareUnicodeCharacter{1F355}{\\faAdjust}\n\\DeclareUnicodeCharacter{0301}{'}\n\\DeclareUnicodeCharacter{03C0}{\\textpi}\n\n\"\"\",\n    # Latex figure (float) alignment\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, \"pybind11.tex\", \"pybind11 Documentation\", \"Wenzel Jakob\", \"manual\"),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n# latex_logo = 'pybind11-logo.png'\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n# latex_use_parts = False\n\n# If true, show page references after internal links.\n# latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n# latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n# latex_appendices = []\n\n# If false, no module index is generated.\n# latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [(master_doc, \"pybind11\", \"pybind11 Documentation\", [author], 1)]\n\n# If true, show URL addresses after external links.\n# man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (\n        master_doc,\n        \"pybind11\",\n        \"pybind11 Documentation\",\n        author,\n        \"pybind11\",\n        \"One line description of project.\",\n        \"Miscellaneous\",\n    ),\n]\n\n# Documents to append as an appendix to all manuals.\n# texinfo_appendices = []\n\n# If false, no module index is generated.\n# texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n# texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n# texinfo_no_detailmenu = False\n\nprimary_domain = \"cpp\"\nhighlight_language = \"cpp\"\n\n\ndef generate_doxygen_xml(app):\n    build_dir = os.path.join(app.confdir, \".build\")\n    if not os.path.exists(build_dir):\n        os.mkdir(build_dir)\n\n    try:\n        subprocess.call([\"doxygen\", \"--version\"])\n        retcode = subprocess.call([\"doxygen\"], cwd=app.confdir)\n        if retcode < 0:\n            sys.stderr.write(f\"doxygen error code: {-retcode}\\n\")\n    except OSError as e:\n        sys.stderr.write(f\"doxygen execution failed: {e}\\n\")\n\n\ndef prepare(app):\n    with open(DIR.parent / \"README.rst\") as f:\n        contents = f.read()\n\n    if app.builder.name == \"latex\":\n        # Remove badges and stuff from start\n        contents = contents[contents.find(r\".. start\") :]\n\n        # Filter out section titles for index.rst for LaTeX\n        contents = re.sub(r\"^(.*)\\n[-~]{3,}$\", r\"**\\1**\", contents, flags=re.MULTILINE)\n\n    with open(DIR / \"readme.rst\", \"w\") as f:\n        f.write(contents)\n\n\ndef clean_up(app, exception):  # noqa: ARG001\n    (DIR / \"readme.rst\").unlink()\n\n\ndef setup(app):\n    # Add hook for building doxygen xml when needed\n    app.connect(\"builder-inited\", generate_doxygen_xml)\n\n    # Copy the readme in\n    app.connect(\"builder-inited\", prepare)\n\n    # Clean up the generated readme\n    app.connect(\"build-finished\", clean_up)\n"
  },
  {
    "path": "docs/faq.rst",
    "content": "Frequently asked questions\n##########################\n\n\"ImportError: dynamic module does not define init function\"\n===========================================================\n\n1. Make sure that the name specified in PYBIND11_MODULE is identical to the\nfilename of the extension library (without suffixes such as ``.so``).\n\n2. If the above did not fix the issue, you are likely using an incompatible\nversion of Python that does not match what you compiled with.\n\n\"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``\"\n========================================================================\n\nSee the first answer.\n\n\"SystemError: dynamic module not initialized properly\"\n======================================================\n\nSee the first answer.\n\nThe Python interpreter immediately crashes when importing my module\n===================================================================\n\nSee the first answer.\n\n.. _faq_reference_arguments:\n\nLimitations involving reference arguments\n=========================================\n\nIn C++, it's fairly common to pass arguments using mutable references or\nmutable pointers, which allows both read and write access to the value\nsupplied by the caller. This is sometimes done for efficiency reasons, or to\nrealize functions that have multiple return values. Here are two very basic\nexamples:\n\n.. code-block:: cpp\n\n    void increment(int &i) { i++; }\n    void increment_ptr(int *i) { (*i)++; }\n\nIn Python, all arguments are passed by reference, so there is no general\nissue in binding such code from Python.\n\nHowever, certain basic Python types (like ``str``, ``int``, ``bool``,\n``float``, etc.) are **immutable**. This means that the following attempt\nto port the function to Python doesn't have the same effect on the value\nprovided by the caller -- in fact, it does nothing at all.\n\n.. code-block:: python\n\n    def increment(i):\n        i += 1  # nope..\n\npybind11 is also affected by such language-level conventions, which means that\nbinding ``increment`` or ``increment_ptr`` will also create Python functions\nthat don't modify their arguments.\n\nAlthough inconvenient, one workaround is to encapsulate the immutable types in\na custom type that does allow modifications.\n\nAn other alternative involves binding a small wrapper lambda function that\nreturns a tuple with all output arguments (see the remainder of the\ndocumentation for examples on binding lambda functions). An example:\n\n.. code-block:: cpp\n\n    int foo(int &i) { i++; return 123; }\n\nand the binding code\n\n.. code-block:: cpp\n\n   m.def(\"foo\", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });\n\n\nHow can I reduce the build time?\n================================\n\nIt's good practice to split binding code over multiple files, as in the\nfollowing example:\n\n:file:`example.cpp`:\n\n.. code-block:: cpp\n\n    void init_ex1(py::module_ &);\n    void init_ex2(py::module_ &);\n    /* ... */\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        init_ex1(m);\n        init_ex2(m);\n        /* ... */\n    }\n\n:file:`ex1.cpp`:\n\n.. code-block:: cpp\n\n    void init_ex1(py::module_ &m) {\n        m.def(\"add\", [](int a, int b) { return a + b; });\n    }\n\n:file:`ex2.cpp`:\n\n.. code-block:: cpp\n\n    void init_ex2(py::module_ &m) {\n        m.def(\"sub\", [](int a, int b) { return a - b; });\n    }\n\n:command:`python`:\n\n.. code-block:: pycon\n\n    >>> import example\n    >>> example.add(1, 2)\n    3\n    >>> example.sub(1, 1)\n    0\n\nAs shown above, the various ``init_ex`` functions should be contained in\nseparate files that can be compiled independently from one another, and then\nlinked together into the same final shared object.  Following this approach\nwill:\n\n1. reduce memory requirements per compilation unit.\n\n2. enable parallel builds (if desired).\n\n3. allow for faster incremental builds. For instance, when a single class\n   definition is changed, only a subset of the binding code will generally need\n   to be recompiled.\n\n\"recursive template instantiation exceeded maximum depth of 256\"\n================================================================\n\nIf you receive an error about excessive recursive template evaluation, try\nspecifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The\nculprit is generally the generation of function signatures at compile time\nusing C++14 template metaprogramming.\n\n.. _`faq:hidden_visibility`:\n\n\"'SomeClass' declared with greater visibility than the type of its field 'SomeClass::member' [-Wattributes]\"\n============================================================================================================\n\nThis error typically indicates that you are compiling without the required\n``-fvisibility`` flag.  pybind11 code internally forces hidden visibility on\nall internal code, but if non-hidden (and thus *exported*) code attempts to\ninclude a pybind type (for example, ``py::object`` or ``py::list``) you can run\ninto this warning.\n\nTo avoid it, make sure you are specifying ``-fvisibility=hidden`` when\ncompiling pybind code.\n\nAs to why ``-fvisibility=hidden`` is necessary, because pybind modules could\nhave been compiled under different versions of pybind itself, it is also\nimportant that the symbols defined in one module do not clash with the\npotentially-incompatible symbols defined in another.  While Python extension\nmodules are usually loaded with localized symbols (under POSIX systems\ntypically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default\ncan be changed, but even if it isn't it is not always enough to guarantee\ncomplete independence of the symbols involved when not using\n``-fvisibility=hidden``.\n\nAdditionally, ``-fvisibility=hidden`` can deliver considerably binary size\nsavings. (See the following section for more details.)\n\n\n.. _`faq:symhidden`:\n\nHow can I create smaller binaries?\n==================================\n\nTo do its job, pybind11 extensively relies on a programming technique known as\n*template metaprogramming*, which is a way of performing computation at compile\ntime using type information. Template metaprogramming usually instantiates code\ninvolving significant numbers of deeply nested types that are either completely\nremoved or reduced to just a few instructions during the compiler's optimization\nphase. However, due to the nested nature of these types, the resulting symbol\nnames in the compiled extension library can be extremely long. For instance,\nthe included test suite contains the following symbol:\n\n.. only:: html\n\n    .. code-block:: none\n\n        _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_\n\n.. only:: not html\n\n    .. code-block:: cpp\n\n        __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_\n\nwhich is the mangled form of the following function type:\n\n.. code-block:: cpp\n\n    pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])\n\nThe memory needed to store just the mangled name of this function (196 bytes)\nis larger than the actual piece of code (111 bytes) it represents! On the other\nhand, it's silly to even give this function a name -- after all, it's just a\ntiny cog in a bigger piece of machinery that is not exposed to the outside\nworld. So we'll generally only want to export symbols for those functions which\nare actually called from the outside.\n\nThis can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC\nand Clang, which sets the default symbol visibility to *hidden*, which has a\ntremendous impact on the final binary size of the resulting extension library.\n(On Visual Studio, symbols are already hidden by default, so nothing needs to\nbe done there.)\n\nIn addition to decreasing binary size, ``-fvisibility=hidden`` also avoids\npotential serious issues when loading multiple modules and is required for\nproper pybind operation.  See the previous FAQ entry for more details.\n\nHow can I properly handle Ctrl-C in long-running functions?\n===========================================================\n\nCtrl-C is received by the Python interpreter, and holds it until the GIL\nis released, so a long-running function won't be interrupted.\n\nTo interrupt from inside your function, you can use the ``PyErr_CheckSignals()``\nfunction, that will tell if a signal has been raised on the Python side.  This\nfunction merely checks a flag, so its impact is negligible. When a signal has\nbeen received, you must either explicitly interrupt execution by throwing\n``py::error_already_set`` (which will propagate the existing\n``KeyboardInterrupt``), or clear the error (which you usually will not want):\n\n.. code-block:: cpp\n\n    PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n        m.def(\"long running_func\", []()\n        {\n            for (;;) {\n                if (PyErr_CheckSignals() != 0)\n                    throw py::error_already_set();\n                // Long running iteration\n            }\n        });\n    }\n\nWhat is a highly conclusive and simple way to find memory leaks (e.g. in pybind11 bindings)?\n============================================================================================\n\nUse ``while True`` & ``top`` (Linux, macOS).\n\nFor example, locally change tests/test_type_caster_pyobject_ptr.py like this:\n\n.. code-block:: diff\n\n     def test_return_list_pyobject_ptr_reference():\n    +  while True:\n         vec_obj = m.return_list_pyobject_ptr_reference(ValueHolder)\n         assert [e.value for e in vec_obj] == [93, 186]\n         # Commenting out the next `assert` will leak the Python references.\n         # An easy way to see evidence of the leaks:\n         # Insert `while True:` as the first line of this function and monitor the\n         # process RES (Resident Memory Size) with the Unix top command.\n    -    assert m.dec_ref_each_pyobject_ptr(vec_obj) == 2\n    +    # assert m.dec_ref_each_pyobject_ptr(vec_obj) == 2\n\nThen run the test as you would normally do, which will go into the infinite loop.\n\n**In another shell, but on the same machine** run:\n\n.. code-block:: bash\n\n    top\n\nThis will show:\n\n.. code-block::\n\n        PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND\n    1266095 rwgk      20   0 5207496 611372  45696 R 100.0   0.3   0:08.01 test_type_caste\n\nLook for the number under ``RES`` there. You'll see it going up very quickly.\n\n**Don't forget to Ctrl-C the test command** before your machine becomes\nunresponsive due to swapping.\n\nThis method only takes a couple minutes of effort and is very conclusive.\nWhat you want to see is that the ``RES`` number is stable after a couple\nseconds.\n\nCMake doesn't detect the right Python version\n=============================================\n\nThe CMake-based build system will try to automatically detect the installed\nversion of Python and link against that. When this fails, or when there are\nmultiple versions of Python and it finds the wrong one, delete\n``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your\nCMake configure line. (Replace ``$(which python)`` with a path to python if\nyour prefer.)\n\nYou can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the\nnew CMake FindPython support instead of pybind11's custom search. Newer CMake,\nlike, 3.18.2+, is recommended. You can set this in your ``CMakeLists.txt``\nbefore adding or finding pybind11, as well.\n\nInconsistent detection of Python version in CMake and pybind11\n==============================================================\n\nThe functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``\nprovided by CMake for Python version detection are modified by pybind11 due to\nunreliability and limitations that make them unsuitable for pybind11's needs.\nInstead pybind11 provides its own, more reliable Python detection CMake code.\nConflicts can arise, however, when using pybind11 in a project that *also* uses\nthe CMake Python detection in a system with several Python versions installed.\n\nThis difference may cause inconsistencies and errors if *both* mechanisms are\nused in the same project.\n\nThere are three possible solutions:\n\n1. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``\n   from CMake and rely on pybind11 in detecting Python version. If this is not\n   possible, the CMake machinery should be called *before* including pybind11.\n2. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python\n   COMPONENTS Interpreter Development)`` on modern CMake ( 3.18.2+ best).\n   Pybind11 in these cases uses the new CMake FindPython instead of the old,\n   deprecated search tools, and these modules are much better at finding the\n   correct Python. If FindPythonLibs/Interp are not available (CMake 3.27+),\n   then this will be ignored and FindPython will be used.\n3. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python.\n   However, you will have to use the target-based system, and do more setup\n   yourself, because it does not know about or include things that depend on\n   Python, like ``pybind11_add_module``. This might be ideal for integrating\n   into an existing system, like scikit-build's Python helpers.\n\nHow to cite this project?\n=========================\n\nWe suggest the following BibTeX template to cite pybind11 in scientific\ndiscourse:\n\n.. code-block:: bash\n\n    @misc{pybind11,\n       author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},\n       year = {2017},\n       note = {https://github.com/pybind/pybind11},\n       title = {pybind11 -- Seamless operability between C++11 and Python}\n    }\n"
  },
  {
    "path": "docs/index.rst",
    "content": ".. only:: latex\n\n   Intro\n   =====\n\n.. include:: readme.rst\n\n.. only:: not latex\n\n    Contents:\n\n.. toctree::\n   :maxdepth: 1\n\n   changelog\n   upgrade\n\n.. toctree::\n   :caption: The Basics\n   :maxdepth: 2\n\n   installing\n   basics\n   classes\n   compiling\n\n.. toctree::\n   :caption: Advanced Topics\n   :maxdepth: 2\n\n   advanced/functions\n   advanced/classes\n   advanced/exceptions\n   advanced/smart_ptrs\n   advanced/cast/index\n   advanced/pycpp/index\n   advanced/embedding\n   advanced/misc\n   advanced/deprecated\n\n.. toctree::\n   :caption: Extra Information\n   :maxdepth: 1\n\n   faq\n   benchmark\n   limitations\n   reference\n   cmake/index\n"
  },
  {
    "path": "docs/installing.rst",
    "content": ".. _installing:\n\nInstalling the library\n######################\n\nThere are several ways to get the pybind11 source, which lives at\n`pybind/pybind11 on GitHub <https://github.com/pybind/pybind11>`_. The pybind11\ndevelopers recommend one of the first three ways listed here, submodule, PyPI,\nor conda-forge, for obtaining pybind11.\n\n.. _include_as_a_submodule:\n\nInclude as a submodule\n======================\n\nWhen you are working on a project in Git, you can use the pybind11 repository\nas a submodule. From your git repository, use:\n\n.. code-block:: bash\n\n    git submodule add -b stable ../../pybind/pybind11 extern/pybind11\n    git submodule update --init\n\nThis assumes you are placing your dependencies in ``extern/``, and that you are\nusing GitHub; if you are not using GitHub, use the full https or ssh URL\ninstead of the relative URL ``../../pybind/pybind11`` above. Some other servers\nalso require the ``.git`` extension (GitHub does not).\n\nFrom here, you can now include ``extern/pybind11/include``, or you can use\nthe various integration tools (see :ref:`compiling`) pybind11 provides directly\nfrom the local folder.\n\nInclude with PyPI\n=================\n\nYou can download the sources and CMake files as a Python package from PyPI\nusing Pip. Just use:\n\n.. code-block:: bash\n\n    pip install pybind11\n\nThis will provide pybind11 in a standard Python package format. If you want\npybind11 available directly in your environment root, you can use:\n\n.. code-block:: bash\n\n    pip install \"pybind11[global]\"\n\nThis is not recommended if you are installing with your system Python, as it\nwill add files to ``/usr/local/include/pybind11`` and\n``/usr/local/share/cmake/pybind11``, so unless that is what you want, it is\nrecommended only for use in virtual environments or your ``pyproject.toml``\nfile (see :ref:`compiling`).\n\nInclude with conda-forge\n========================\n\nYou can use pybind11 with conda packaging via `conda-forge\n<https://github.com/conda-forge/pybind11-feedstock>`_:\n\n.. code-block:: bash\n\n    conda install -c conda-forge pybind11\n\n\nInclude with vcpkg\n==================\nYou can download and install pybind11 using the Microsoft `vcpkg\n<https://github.com/Microsoft/vcpkg/>`_ dependency manager:\n\n.. code-block:: bash\n\n    git clone https://github.com/Microsoft/vcpkg.git\n    cd vcpkg\n    ./bootstrap-vcpkg.sh\n    ./vcpkg integrate install\n    vcpkg install pybind11\n\nThe pybind11 port in vcpkg is kept up to date by Microsoft team members and\ncommunity contributors. If the version is out of date, please `create an issue\nor pull request <https://github.com/Microsoft/vcpkg/>`_ on the vcpkg\nrepository.\n\nGlobal install with brew\n========================\n\nThe brew package manager (Homebrew on macOS, or Linuxbrew on Linux) has a\n`pybind11 package\n<https://github.com/Homebrew/homebrew-core/blob/master/Formula/p/pybind11.rb>`_.\nTo install:\n\n.. code-block:: bash\n\n    brew install pybind11\n\n.. We should list Conan, and possibly a few other C++ package managers (hunter,\n.. perhaps). Conan has a very clean CMake integration that would be good to show.\n\nOther options\n=============\n\nOther locations you can find pybind11 are `listed here\n<https://repology.org/project/python:pybind11/versions>`_; these are maintained\nby various packagers and the community.\n"
  },
  {
    "path": "docs/limitations.rst",
    "content": "Limitations\n###########\n\nDesign choices\n^^^^^^^^^^^^^^\n\npybind11 strives to be a general solution to binding generation, but it also has\ncertain limitations:\n\n- pybind11 casts away ``const``-ness in function arguments and return values.\n  This is in line with the Python language, which has no concept of ``const``\n  values. This means that some additional care is needed to avoid bugs that\n  would be caught by the type checker in a traditional C++ program.\n\n- The NumPy interface ``pybind11::array`` greatly simplifies accessing\n  numerical data from C++ (and vice versa), but it's not a full-blown array\n  class like ``Eigen::Array`` or ``boost.multi_array``. ``Eigen`` objects are\n  directly supported, however, with ``pybind11/eigen.h``.\n\nLarge but useful features could be implemented in pybind11 but would lead to a\nsignificant increase in complexity. Pybind11 strives to be simple and compact.\nUsers who require large new features are encouraged to write an extension to\npybind11; see `pybind11_json <https://github.com/pybind/pybind11_json>`_ for an\nexample.\n\n\nKnown bugs\n^^^^^^^^^^\n\nThese are issues that hopefully will one day be fixed, but currently are\nunsolved. If you know how to help with one of these issues, contributions\nare welcome!\n\n- Intel 20.2 is currently having an issue with the test suite.\n  `#2573 <https://github.com/pybind/pybind11/pull/2573>`_\n\n- Debug mode Python does not support 1-5 tests in the test suite currently.\n  `#2422 <https://github.com/pybind/pybind11/pull/2422>`_\n\n- PyPy3 7.3.1 and 7.3.2 have issues with several tests on 32-bit Windows.\n\nKnown limitations\n^^^^^^^^^^^^^^^^^\n\nThese are issues that are probably solvable, but have not been fixed yet. A\nclean, well written patch would likely be accepted to solve them.\n\n- Type casters are not kept alive recursively.\n  `#2527 <https://github.com/pybind/pybind11/issues/2527>`_\n  One consequence is that containers of ``char *`` are currently not supported.\n  `#2245 <https://github.com/pybind/pybind11/issues/2245>`_\n\nPython 3.9.0 warning\n^^^^^^^^^^^^^^^^^^^^\n\nCombining older versions of pybind11 (< 2.6.0) with Python on exactly 3.9.0\nwill trigger undefined behavior that typically manifests as crashes during\ninterpreter shutdown (but could also destroy your data. **You have been\nwarned**).\n\nThis issue was `fixed in Python <https://github.com/python/cpython/pull/22670>`_.\nAs a mitigation for this bug, pybind11 2.6.0 or newer includes a workaround\nspecifically when Python 3.9.0 is detected at runtime, leaking about 50 bytes\nof memory when a callback function is garbage collected.  For reference, the\npybind11 test suite has about 2,000 such callbacks, but only 49 are garbage\ncollected before the end-of-process. Wheels (even if built with Python 3.9.0)\nwill correctly avoid the leak when run in Python 3.9.1, and this does not\naffect other 3.X versions.\n"
  },
  {
    "path": "docs/reference.rst",
    "content": ".. _reference:\n\n.. warning::\n\n    Please be advised that the reference documentation discussing pybind11\n    internals is currently incomplete. Please refer to the previous sections\n    and the pybind11 header files for the nitty gritty details.\n\nReference\n#########\n\n.. _macros:\n\nMacros\n======\n\n.. doxygendefine:: PYBIND11_MODULE\n\n.. _core_types:\n\nConvenience classes for arbitrary Python types\n==============================================\n\nCommon member functions\n-----------------------\n\n.. doxygenclass:: object_api\n    :members:\n\nWithout reference counting\n--------------------------\n\n.. doxygenclass:: handle\n    :members:\n\nWith reference counting\n-----------------------\n\n.. doxygenclass:: object\n    :members:\n\n.. doxygenfunction:: reinterpret_borrow\n\n.. doxygenfunction:: reinterpret_steal\n\nConvenience classes for specific Python types\n=============================================\n\n.. doxygenclass:: module_\n    :members:\n\n.. doxygengroup:: pytypes\n    :members:\n\nConvenience functions converting to Python types\n================================================\n\n.. doxygenfunction:: make_tuple(Args&&...)\n\n.. doxygenfunction:: make_iterator(Iterator, Sentinel, Extra &&...)\n.. doxygenfunction:: make_iterator(Type &, Extra&&...)\n\n.. doxygenfunction:: make_key_iterator(Iterator, Sentinel, Extra &&...)\n.. doxygenfunction:: make_key_iterator(Type &, Extra&&...)\n\n.. doxygenfunction:: make_value_iterator(Iterator, Sentinel, Extra &&...)\n.. doxygenfunction:: make_value_iterator(Type &, Extra&&...)\n\n.. _extras:\n\nPassing extra arguments to ``def`` or ``py::class_``\n====================================================\n\n.. doxygengroup:: annotations\n    :members:\n\nEmbedding the interpreter\n=========================\n\n.. doxygendefine:: PYBIND11_EMBEDDED_MODULE\n\n.. doxygenfunction:: initialize_interpreter\n\n.. doxygenfunction:: finalize_interpreter\n\n.. doxygenclass:: scoped_interpreter\n\nRedirecting C++ streams\n=======================\n\n.. doxygenclass:: scoped_ostream_redirect\n\n.. doxygenclass:: scoped_estream_redirect\n\n.. doxygenfunction:: add_ostream_redirect\n\nPython built-in functions\n=========================\n\n.. doxygengroup:: python_builtins\n    :members:\n\nInheritance\n===========\n\nSee :doc:`/classes` and :doc:`/advanced/classes` for more detail.\n\n.. doxygendefine:: PYBIND11_OVERRIDE\n\n.. doxygendefine:: PYBIND11_OVERRIDE_PURE\n\n.. doxygendefine:: PYBIND11_OVERRIDE_NAME\n\n.. doxygendefine:: PYBIND11_OVERRIDE_PURE_NAME\n\n.. doxygenfunction:: get_override\n\nExceptions\n==========\n\n.. doxygenclass:: error_already_set\n    :members:\n\n.. doxygenclass:: builtin_exception\n    :members:\n\nLiterals\n========\n\n.. doxygennamespace:: literals\n"
  },
  {
    "path": "docs/release.rst",
    "content": "On version numbers\n^^^^^^^^^^^^^^^^^^\n\nThe version number must be a valid `PEP 440\n<https://www.python.org/dev/peps/pep-0440>`_ version number.\n\nFor example:\n\n.. code-block:: C++\n\n    #define PYBIND11_VERSION_MAJOR X\n    #define PYBIND11_VERSION_MINOR Y\n    #define PYBIND11_VERSION_MICRO Z\n    #define PYBIND11_VERSION_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA\n    #define PYBIND11_VERSION_RELEASE_SERIAL 0\n    #define PYBIND11_VERSION_PATCH Za0\n\nFor beta, ``PYBIND11_VERSION_PATCH`` should be ``Zb1``. RC's can be ``Zrc1``.\nFor a final release, this must be a simple integer.\n\n\nTo release a new version of pybind11:\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIf you don't have nox, you should either use ``pipx run nox`` instead, or use\n``uv tool install nox``, ``pipx install nox``, or ``brew install nox`` (Unix).\n\n- Update the version number\n\n  - Update ``PYBIND11_VERSION_MAJOR`` etc. in\n    ``include/pybind11/detail/common.h``. MICRO should be a simple integer.\n\n  - Run ``nox -s tests_packaging`` to ensure this was done correctly.\n\n- Ensure that all the information in ``pyproject.toml`` is up-to-date, like\n    supported Python versions.\n\n- Add release date in ``docs/changelog.md`` and integrate the output of\n  ``nox -s make_changelog``.\n\n  - Note that the ``nox -s make_changelog`` command inspects\n    `needs changelog <https://github.com/pybind/pybind11/pulls?q=is%3Apr+is%3Aclosed+label%3A%22needs+changelog%22>`_.\n\n  - Manually clear the ``needs changelog`` labels using the GitHub web\n    interface (very easy: start by clicking the link above).\n\n- ``git add`` and ``git commit``, ``git push``. **Ensure CI passes**. (If it\n    fails due to a known flake issue, either ignore or restart CI.)\n\n- Add a release branch if this is a new MINOR version, or update the existing\n  release branch if it is a patch version\n\n  - NOTE: This documentation assumes your ``upstream`` is ``https://github.com/pybind/pybind11.git``\n\n  - New branch: ``git checkout -b vX.Y``, ``git push -u upstream vX.Y``\n\n  - Update branch: ``git checkout vX.Y``, ``git merge <release branch>``, ``git push``\n\n- Update tags (optional; if you skip this, the GitHub release makes a\n  non-annotated tag for you)\n\n  - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``\n\n  - ``git grep PYBIND11_VERSION include/pybind11/detail/common.h``\n\n    - Last-minute consistency check: same as tag?\n\n  - Push the new tag: ``git push upstream vX.Y.Z``\n\n- Update stable\n\n  - ``git checkout stable``\n\n  - ``git merge -X theirs vX.Y.Z``\n\n  - ``git diff vX.Y.Z``\n\n  - Carefully review and reconcile any diffs. There should be none.\n\n  - ``git push``\n\n- Make a GitHub release (this shows up in the UI, sends new release\n  notifications to users watching releases, and also uploads PyPI packages).\n  (Note: if you do not use an existing tag, this creates a new lightweight tag\n  for you, so you could skip the above step.)\n\n  - GUI method: Under `releases <https://github.com/pybind/pybind11/releases>`_\n    click \"Draft a new release\" on the far right, fill in the tag name\n    (if you didn't tag above, it will be made here), fill in a release name\n    like \"Version X.Y.Z\", and copy-and-paste the markdown-formatted (!) changelog\n    into the description. You can remove line breaks and optionally strip links\n    to PRs and issues, e.g. to a bare ``#1234`` without the hyperlink markup.\n    Check \"pre-release\" if this is an alpha/beta/RC.\n\n  - CLI method: with ``gh`` installed, run ``gh release create vX.Y.Z -t \"Version X.Y.Z\"``\n    If this is a pre-release, add ``-p``.\n\n- Get back to work\n\n  - Make sure you are on master, not somewhere else: ``git checkout master``\n\n  - Update version macros in ``include/pybind11/detail/common.h`` (set PATCH to\n    ``0a0`` and increment MINOR).\n\n  - Update ``pybind11/_version.py`` to match.\n\n  - Run ``nox -s tests_packaging`` to ensure this was done correctly.\n\n  - If the release was a new MINOR version, add a new ``IN DEVELOPMENT``\n    section in ``docs/changelog.md``.\n\n  - ``git add``, ``git commit``, ``git push``\n\nIf a version branch is updated, remember to set PATCH to ``1a0``.\n\nConda-forge should automatically make a PR in a few hours, and automatically\nmerge it if there are no issues. Homebrew should be automatic, too.\n\n\nManual packaging\n^^^^^^^^^^^^^^^^\n\nIf you need to manually upload releases, you can download the releases from\nthe job artifacts and upload them with twine. You can also make the files\nlocally (not recommended in general, as your local directory is more likely\nto be \"dirty\" and SDists love picking up random unrelated/hidden files);\nthis is the procedure:\n\n.. code-block:: bash\n\n    nox -s build\n    nox -s build_global\n    twine upload dist/*\n\nThis makes SDists and wheels, and the final line uploads them.\n"
  },
  {
    "path": "docs/requirements.in",
    "content": "breathe\nfuro\nmyst_parser\nsphinx\nsphinx-copybutton\nsphinxcontrib-moderncmakedomain\nsphinxcontrib-svg2pdfconverter\n"
  },
  {
    "path": "docs/requirements.txt",
    "content": "# This file was autogenerated by uv via the following command:\n#    uv pip compile docs/requirements.in -o docs/requirements.txt\nalabaster==0.7.16\n    # via sphinx\nbabel==2.14.0\n    # via sphinx\nbeautifulsoup4==4.12.3\n    # via furo\nbreathe==4.35.0\n    # via -r requirements.in\ncertifi==2024.7.4\n    # via requests\ncharset-normalizer==3.3.2\n    # via requests\ndocutils==0.20.1\n    # via\n    #   breathe\n    #   myst-parser\n    #   sphinx\nfuro==2024.1.29\n    # via -r requirements.in\nidna==3.7\n    # via requests\nimagesize==1.4.1\n    # via sphinx\njinja2==3.1.6\n    # via\n    #   myst-parser\n    #   sphinx\nmarkdown-it-py==3.0.0\n    # via\n    #   mdit-py-plugins\n    #   myst-parser\nmarkupsafe==2.1.5\n    # via jinja2\nmdit-py-plugins==0.4.2\n    # via myst-parser\nmdurl==0.1.2\n    # via markdown-it-py\nmyst-parser==3.0.1\n    # via -r requirements.in\npackaging==24.0\n    # via sphinx\npygments==2.17.2\n    # via\n    #   furo\n    #   sphinx\npyyaml==6.0.2\n    # via myst-parser\nrequests==2.32.4\n    # via sphinx\nsnowballstemmer==2.2.0\n    # via sphinx\nsoupsieve==2.5\n    # via beautifulsoup4\nsphinx==7.2.6\n    # via\n    #   -r requirements.in\n    #   breathe\n    #   furo\n    #   myst-parser\n    #   sphinx-basic-ng\n    #   sphinx-copybutton\n    #   sphinxcontrib-moderncmakedomain\n    #   sphinxcontrib-svg2pdfconverter\nsphinx-basic-ng==1.0.0b2\n    # via furo\nsphinx-copybutton==0.5.2\n    # via -r requirements.in\nsphinxcontrib-applehelp==1.0.8\n    # via sphinx\nsphinxcontrib-devhelp==1.0.6\n    # via sphinx\nsphinxcontrib-htmlhelp==2.0.5\n    # via sphinx\nsphinxcontrib-jsmath==1.0.1\n    # via sphinx\nsphinxcontrib-moderncmakedomain==3.27.0\n    # via -r requirements.in\nsphinxcontrib-qthelp==1.0.7\n    # via sphinx\nsphinxcontrib-serializinghtml==1.1.10\n    # via sphinx\nsphinxcontrib-svg2pdfconverter==1.2.2\n    # via -r requirements.in\nurllib3==2.6.3\n    # via requests\n"
  },
  {
    "path": "docs/upgrade.rst",
    "content": "Upgrade guide\n#############\n\nThis is a companion guide to the :doc:`changelog`. While the changelog briefly\nlists all of the new features, improvements and bug fixes, this upgrade guide\nfocuses only the subset which directly impacts your experience when upgrading\nto a new version. But it goes into more detail. This includes things like\ndeprecated APIs and their replacements, build system changes, general code\nmodernization and other useful information.\n\n.. _upgrade-guide-3.0:\n\nv3.0\n====\n\npybind11 v3.0 introduces major new features, but the vast majority of\nexisting extensions are expected to build and run without modification. Minor\nadjustments may be needed in rare cases, and any such changes can be easily\nwrapped in preprocessor conditionals to maintain compatibility with the\n2.x series.\n\nHowever, due to new features and modernizations, extensions built with\npybind11 v3.0 are not ABI-compatible with those built using v2.13. To ensure\ncross-extension-module compatibility, it is recommended to rebuild all\npybind11-based extensions with v3.0.\n\nCMake support now defaults to the modern FindPython module. If you haven't\nupdated yet, we provide some backward compatibility for ``PYTHON_*`` variables,\nbut you should switch to using ``Python_*`` variables instead. Note that\nsetting ``PYTHON_*`` variables no longer affects the build.\n\nA major new feature in this release is the integration of\n``py::smart_holder``, which improves support for ``std::unique_ptr``\nand ``std::shared_ptr``, resolving several long-standing issues. See\n:ref:`smart_holder` for details. Closely related is the addition\nof ``py::trampoline_self_life_support``, documented under\n:ref:`overriding_virtuals`.\n\nThis release includes a major modernization of cross-extension-module\nABI compatibility handling. The new implementation reflects actual ABI\ncompatibility much more accurately than in previous versions. The details\nare subtle and complex; see\n`#4953 <https://github.com/pybind/pybind11/pull/4953>`_ and\n`#5439 <https://github.com/pybind/pybind11/pull/5439>`_.\n\nAlso new in v3.0 is ``py::native_enum``, a modern API for exposing\nC++ enumerations as native Python types — typically standard-library\n``enum.Enum`` or related subclasses. This provides improved integration with\nPython's enum system, compared to the older (now deprecated) ``py::enum_``.\nSee `#5555 <https://github.com/pybind/pybind11/pull/5555>`_ for details.\nNote that ``#include <pybind11/native_enum.h>`` is not included automatically\nand must be added explicitly.\n\nFunctions exposed with pybind11 are now pickleable. This removes a\nlong-standing obstacle when using pybind11-bound functions with Python features\nthat rely on pickling, such as multiprocessing and caching tools.\nSee `#5580 <https://github.com/pybind/pybind11/pull/5580>`_ for details.\n\nAnything producing a deprecation warning in the 2.x series may be removed in a\nfuture minor release of 3.x. Most of these are still present in 3.0 in order to ease\ntransition. The new :ref:`deprecated` page details deprecations.\n\nMigration Recommendations\n-------------------------\n\nWe recommend migrating to pybind11 v3.0 promptly, while keeping initial\nchanges to a minimum. Most projects can upgrade simply by updating the\npybind11 version, without altering existing binding code.\n\nAfter a short stabilization period — enough to surface any subtle issues —\nyou may incrementally adopt new features where appropriate:\n\n* Use ``py::smart_holder`` and ``py::trampoline_self_life_support`` as needed,\n  or to improve code health. Note that ``py::classh`` is available as a\n  shortcut — for example, ``py::classh<Pet>`` is shorthand for\n  ``py::class_<Pet, py::smart_holder>``. This is designed to enable easy\n  experimentation with ``py::smart_holder`` without introducing distracting\n  whitespace changes. In many cases, a global replacement of ``py::class_``\n  with ``py::classh`` can be an effective first step. Build failures will\n  quickly identify places where ``std::shared_ptr<...>`` holders need to be\n  removed. Runtime failures (assuming good unit test coverage) will highlight\n  base-and-derived class situations that require coordinated changes.\n\n  Note that ``py::bind_vector`` and ``py::bind_map`` (in pybind11/stl_bind.h)\n  have a ``holder_type`` template parameter that defaults to\n  ``std::unique_ptr``. If ``py::smart_holder`` functionality is desired or\n  required, use e.g. ``py::bind_vector<VecType, py::smart_holder>``.\n\n* Gradually migrate from ``py::enum_`` to ``py::native_enum`` to improve\n  integration with Python's standard enum types.\n\nThere is no urgency to refactor existing, working bindings — adopt new\nfeatures as the need arises or as part of ongoing maintenance efforts.\n\nIf you are using CMake, update to FindPython variables (mostly changing\nvariables from ``PYTHON_*`` -> ``Python_*``). You should see if you can use\n``set(PYBIND11_FINDPYTHON ON)``, which has been supported for years and will\navoid setting the compatibility mode variables (and will avoid a warning).\n\nPotential stumbling blocks when migrating to v3.0\n-------------------------------------------------\n\nThe following issues are very unlikely to arise, and easy to work around:\n\n* In rare cases, a C++ enum may be bound to Python via a\n  :ref:`custom type caster <custom_type_caster>`. In such cases, a\n  template specialization like this may be required:\n\n  .. code-block:: cpp\n\n      #if defined(PYBIND11_HAS_NATIVE_ENUM)\n      namespace pybind11::detail {\n      template <typename FancyEnum>\n      struct type_caster_enum_type_enabled<\n          FancyEnum,\n          enable_if_t<is_fancy_enum<FancyEnum>::value>> : std::false_type {};\n      }\n      #endif\n\n  This specialization is needed only if the custom type caster is templated.\n\n  The ``PYBIND11_HAS_NATIVE_ENUM`` guard is needed only\n  if backward compatibility with pybind11v2 is required.\n\n* Similarly, template specializations like the following may be required\n  if there are custom\n\n  * ``pybind11::detail::copyable_holder_caster`` or\n\n  * ``pybind11::detail::move_only_holder_caster``\n\n  implementations that are used for ``std::shared_ptr`` or ``std::unique_ptr``\n  conversions:\n\n  .. code-block:: cpp\n\n      #if defined(PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT)\n      namespace pybind11::detail {\n      template <typename ExampleType>\n      struct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<\n          ExampleType,\n          enable_if_t<is_example_type<ExampleType>::value>> : std::false_type {};\n      }\n      #endif\n\n  .. code-block:: cpp\n\n      #if defined(PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT)\n      namespace pybind11::detail {\n      template <typename ExampleType>\n      struct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<\n          ExampleType,\n          enable_if_t<is_example_type<ExampleType>::value>> : std::false_type {};\n      }\n      #endif\n\n  The ``PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT`` guard is needed only\n  if backward compatibility with pybind11v2 is required.\n\n  (Note that ``copyable_holder_caster`` and ``move_only_holder_caster`` are not\n  documented, although they existed since 2017.)\n\n\n.. _upgrade-guide-2.12:\n\nv2.12\n=====\n\nNumPy support has been upgraded to support the 2.x series too. The two relevant\nchanges are that:\n\n* ``dtype.flags()`` is now a ``uint64`` and ``dtype.alignment()`` an\n  ``ssize_t`` (and NumPy may return an larger than integer value for\n  ``itemsize()`` in NumPy 2.x).\n\n* The long deprecated NumPy function ``PyArray_GetArrayParamsFromObject``\n  function is not available anymore.\n\nDue to NumPy changes, you may experience difficulties updating to NumPy 2.\nPlease see the `NumPy 2 migration guide <https://numpy.org/devdocs/numpy_2_0_migration_guide.html>`_\nfor details.\nFor example, a more direct change could be that the default integer ``\"int_\"``\n(and ``\"uint\"``) is now ``ssize_t`` and not ``long`` (affects 64bit windows).\n\nIf you want to only support NumPy 1.x for now and are having problems due to\nthe two internal changes listed above, you can define\n``PYBIND11_NUMPY_1_ONLY`` to disable the new support for now. Make sure you\ndefine this on all pybind11 compile units, since it could be a source of ODR\nviolations if used inconsistently. This option will be removed in the future,\nso adapting your code is highly recommended.\n\n\n.. _upgrade-guide-2.11:\n\nv2.11\n=====\n\n* The minimum version of CMake is now 3.5. A future version will likely move to\n  requiring something like CMake 3.15. Note that CMake 3.27 is removing the\n  long-deprecated support for ``FindPythonInterp`` if you set 3.27 as the\n  minimum or maximum supported version. To prepare for that future, CMake 3.15+\n  using ``FindPython`` or setting ``PYBIND11_FINDPYTHON`` is highly recommended,\n  otherwise pybind11 will automatically switch to using ``FindPython`` if\n  ``FindPythonInterp`` is not available.\n\n\n.. _upgrade-guide-2.9:\n\nv2.9\n====\n\n* Any usage of the recently added ``py::make_simple_namespace`` should be\n  converted to using ``py::module_::import(\"types\").attr(\"SimpleNamespace\")``\n  instead.\n\n* The use of ``_`` in custom type casters can now be replaced with the more\n  readable ``const_name`` instead. The old ``_`` shortcut has been retained\n  unless it is being used as a macro (like for gettext).\n\n\n.. _upgrade-guide-2.7:\n\nv2.7\n====\n\n*Before* v2.7, ``py::str`` can hold ``PyUnicodeObject`` or ``PyBytesObject``,\nand ``py::isinstance<str>()`` is ``true`` for both ``py::str`` and\n``py::bytes``. Starting with v2.7, ``py::str`` exclusively holds\n``PyUnicodeObject`` (`#2409 <https://github.com/pybind/pybind11/pull/2409>`_),\nand ``py::isinstance<str>()`` is ``true`` only for ``py::str``. To help in\nthe transition of user code, the ``PYBIND11_STR_LEGACY_PERMISSIVE`` macro\nis provided as an escape hatch to go back to the legacy behavior. This macro\nwill be removed in future releases. Two types of required fixes are expected\nto be common:\n\n* Accidental use of ``py::str`` instead of ``py::bytes``, masked by the legacy\n  behavior. These are probably very easy to fix, by changing from\n  ``py::str`` to ``py::bytes``.\n\n* Reliance on py::isinstance<str>(obj) being ``true`` for\n  ``py::bytes``. This is likely to be easy to fix in most cases by adding\n  ``|| py::isinstance<bytes>(obj)``, but a fix may be more involved, e.g. if\n  ``py::isinstance<T>`` appears in a template. Such situations will require\n  careful review and custom fixes.\n\n\n.. _upgrade-guide-2.6:\n\nv2.6\n====\n\nUsage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should\nbe replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the\nold macros may be deprecated and removed.\n\n``py::module`` has been renamed ``py::module_``, but a backward compatible\ntypedef has been included. This change was to avoid a language change in C++20\nthat requires unqualified ``module`` not be placed at the start of a logical\nline. Qualified usage is unaffected and the typedef will remain unless the\nC++ language rules change again.\n\nThe public constructors of ``py::module_`` have been deprecated. Use\n``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead.\n\nAn error is now thrown when ``__init__`` is forgotten on subclasses. This was\nincorrect before, but was not checked. Add a call to ``__init__`` if it is\nmissing.\n\nA ``py::type_error`` is now thrown when casting to a subclass (like\n``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid\nconversion instead.\n\nThe undocumented ``h.get_type()`` method has been deprecated and replaced by\n``py::type::of(h)``.\n\nEnums now have a ``__str__`` method pre-defined; if you want to override it,\nthe simplest fix is to add the new ``py::prepend()`` tag when defining\n``\"__str__\"``.\n\nIf ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to\n``None``, as in normal CPython. You should add ``__hash__`` if you intended the\nclass to be hashable, possibly using the new ``py::hash`` shortcut.\n\nThe constructors for ``py::array`` now always take signed integers for size,\nfor consistency. This may lead to compiler warnings on some systems. Cast to\n``py::ssize_t`` instead of ``std::size_t``.\n\nThe ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a\nstandalone package, `pybind11-mkdoc`_. If you were using those tools, please\nuse them via a pip install from the new location.\n\nThe ``pybind11`` package on PyPI no longer fills the wheel \"headers\" slot - if\nyou were using the headers from this slot, they are available by requesting the\n``global`` extra, that is, ``pip install \"pybind11[global]\"``. (Most users will\nbe unaffected, as the ``pybind11/include`` location is reported by ``python -m\npybind11 --includes`` and ``pybind11.get_include()`` is still correct and has\nnot changed since 2.5).\n\n.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc\n\nCMake support:\n--------------\n\nThe minimum required version of CMake is now 3.4.  Several details of the CMake\nsupport have been deprecated; warnings will be shown if you need to change\nsomething. The changes are:\n\n* ``PYBIND11_CPP_STANDARD=<platform-flag>`` is deprecated, please use\n  ``CMAKE_CXX_STANDARD=<number>`` instead, or any other valid CMake CXX or CUDA\n  standard selection method, like ``target_compile_features``.\n\n* If you do not request a standard, pybind11 targets will compile with the\n  compiler default, but not less than C++11, instead of forcing C++14 always.\n  If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING \"\")``\n  instead.\n\n* Direct ``pybind11::module`` usage should always be accompanied by at least\n  ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to\n  manually force this compiler flag (but not correctly on all compilers or with\n  CUDA).\n\n* ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing;\n  linking now behaves like other imported libraries consistently in both\n  config and submodule mode, and behaves like a ``SYSTEM`` library by\n  default.\n\n* If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``,\n  ``virtualenv``, and ``conda``) are prioritized over the standard search\n  (similar to the new FindPython mode).\n\nIn addition, the following changes may be of interest:\n\n* ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by\n  ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or\n  ``pybind11::thin_lto``.\n\n* Using ``find_package(Python COMPONENTS Interpreter Development)`` before\n  pybind11 will cause pybind11 to use the new Python mechanisms instead of its\n  own custom search, based on a patched version of classic ``FindPythonInterp``\n  / ``FindPythonLibs``. In the future, this may become the default. A recent\n  (3.15+ or 3.18.2+) version of CMake is recommended.\n\n\n\nv2.5\n====\n\nThe Python package now includes the headers as data in the package itself, as\nwell as in the \"headers\" wheel slot. ``pybind11 --includes`` and\n``pybind11.get_include()`` report the new location, which is always correct\nregardless of how pybind11 was installed, making the old ``user=`` argument\nmeaningless. If you are not using the function to get the location already, you\nare encouraged to switch to the package location.\n\n\nv2.2\n====\n\nDeprecation of the ``PYBIND11_PLUGIN`` macro\n--------------------------------------------\n\n``PYBIND11_MODULE`` is now the preferred way to create module entry points.\nThe old macro emits a compile-time deprecation warning.\n\n.. code-block:: cpp\n\n    // old\n    PYBIND11_PLUGIN(example) {\n        py::module m(\"example\", \"documentation string\");\n\n        m.def(\"add\", [](int a, int b) { return a + b; });\n\n        return m.ptr();\n    }\n\n    // new\n    PYBIND11_MODULE(example, m) {\n        m.doc() = \"documentation string\"; // optional\n\n        m.def(\"add\", [](int a, int b) { return a + b; });\n    }\n\n\nNew API for defining custom constructors and pickling functions\n---------------------------------------------------------------\n\nThe old placement-new custom constructors have been deprecated. The new approach\nuses ``py::init()`` and factory functions to greatly improve type safety.\n\nPlacement-new can be called accidentally with an incompatible type (without any\ncompiler errors or warnings), or it can initialize the same object multiple times\nif not careful with the Python-side ``__init__`` calls. The new-style custom\nconstructors prevent such mistakes. See :ref:`custom_constructors` for details.\n\n.. code-block:: cpp\n\n    // old -- deprecated (runtime warning shown only in debug mode)\n    py::class<Foo>(m, \"Foo\")\n        .def(\"__init__\", [](Foo &self, ...) {\n            new (&self) Foo(...); // uses placement-new\n        });\n\n    // new\n    py::class<Foo>(m, \"Foo\")\n        .def(py::init([](...) { // Note: no `self` argument\n            return new Foo(...); // return by raw pointer\n            // or: return std::make_unique<Foo>(...); // return by holder\n            // or: return Foo(...); // return by value (move constructor)\n        }));\n\nMirroring the custom constructor changes, ``py::pickle()`` is now the preferred\nway to get and set object state. See :ref:`pickling` for details.\n\n.. code-block:: cpp\n\n    // old -- deprecated (runtime warning shown only in debug mode)\n    py::class<Foo>(m, \"Foo\")\n        ...\n        .def(\"__getstate__\", [](const Foo &self) {\n            return py::make_tuple(self.value1(), self.value2(), ...);\n        })\n        .def(\"__setstate__\", [](Foo &self, py::tuple t) {\n            new (&self) Foo(t[0].cast<std::string>(), ...);\n        });\n\n    // new\n    py::class<Foo>(m, \"Foo\")\n        ...\n        .def(py::pickle(\n            [](const Foo &self) { // __getstate__\n                return py::make_tuple(self.value1(), self.value2(), ...); // unchanged\n            },\n            [](py::tuple t) { // __setstate__, note: no `self` argument\n                return new Foo(t[0].cast<std::string>(), ...);\n                // or: return std::make_unique<Foo>(...); // return by holder\n                // or: return Foo(...); // return by value (move constructor)\n            }\n        ));\n\nFor both the constructors and pickling, warnings are shown at module\ninitialization time (on import, not when the functions are called).\nThey're only visible when compiled in debug mode. Sample warning:\n\n.. code-block:: none\n\n    pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__'\n    which has been deprecated. See the upgrade guide in pybind11's docs.\n\n\nStricter enforcement of hidden symbol visibility for pybind11 modules\n---------------------------------------------------------------------\n\npybind11 now tries to actively enforce hidden symbol visibility for modules.\nIf you're using either one of pybind11's :doc:`CMake or Python build systems\n<compiling>` (the two example repositories) and you haven't been exporting any\nsymbols, there's nothing to be concerned about. All the changes have been done\ntransparently in the background. If you were building manually or relied on\nspecific default visibility, read on.\n\nSetting default symbol visibility to *hidden* has always been recommended for\npybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol\nvisibility (in conjunction with the ``strip`` utility) yields much smaller\nmodule binaries. `CPython's extension docs`_ also recommend hiding symbols\nby default, with the goal of avoiding symbol name clashes between modules.\nStarting with v2.2, pybind11 enforces this more strictly: (1) by declaring\nall symbols inside the ``pybind11`` namespace as hidden and (2) by including\nthe ``-fvisibility=hidden`` flag on Linux and macOS (only for extension\nmodules, not for embedding the interpreter).\n\n.. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module\n\nThe namespace-scope hidden visibility is done automatically in pybind11's\nheaders and it's generally transparent to users. It ensures that:\n\n* Modules compiled with different pybind11 versions don't clash with each other.\n\n* Some new features, like ``py::module_local`` bindings, can work as intended.\n\nThe ``-fvisibility=hidden`` flag applies the same visibility to user bindings\noutside of the ``pybind11`` namespace. It's now set automatic by pybind11's\nCMake and Python build systems, but this needs to be done manually by users\nof other build systems. Adding this flag:\n\n* Minimizes the chances of symbol conflicts between modules. E.g. if two\n  unrelated modules were statically linked to different (ABI-incompatible)\n  versions of the same third-party library, a symbol clash would be likely\n  (and would end with unpredictable results).\n\n* Produces smaller binaries on Linux and macOS, as pointed out previously.\n\nWithin pybind11's CMake build system, ``pybind11_add_module`` has always been\nsetting the ``-fvisibility=hidden`` flag in release mode. From now on, it's\nbeing applied unconditionally, even in debug mode and it can no longer be opted\nout of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also\nadds this flag to its interface. The ``pybind11::embed`` target is unchanged.\n\nThe most significant change here is for the ``pybind11::module`` target. If you\nwere previously relying on default visibility, i.e. if your Python module was\ndoubling as a shared library with dependents, you'll need to either export\nsymbols manually (recommended for cross-platform libraries) or factor out the\nshared library (and have the Python module link to it like the other\ndependents). As a temporary workaround, you can also restore default visibility\nusing the CMake code below, but this is not recommended in the long run:\n\n.. code-block:: cmake\n\n    target_link_libraries(mymodule PRIVATE pybind11::module)\n\n    add_library(restore_default_visibility INTERFACE)\n    target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)\n    target_link_libraries(mymodule PRIVATE restore_default_visibility)\n\n\nLocal STL container bindings\n----------------------------\n\nPrevious pybind11 versions could only bind types globally -- all pybind11\nmodules, even unrelated ones, would have access to the same exported types.\nHowever, this would also result in a conflict if two modules exported the\nsame C++ type, which is especially problematic for very common types, e.g.\n``std::vector<int>``. :ref:`module_local` were added to resolve this (see\nthat section for a complete usage guide).\n\n``py::class_`` still defaults to global bindings (because these types are\nusually unique across modules), however in order to avoid clashes of opaque\ntypes, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers\nas ``py::module_local`` if their elements are: builtins (``int``, ``float``,\netc.), not bound using ``py::class_``, or bound as ``py::module_local``. For\nexample, this change allows multiple modules to bind ``std::vector<int>``\nwithout causing conflicts. See :ref:`stl_bind` for more details.\n\nWhen upgrading to this version, if you have multiple modules which depend on\na single global binding of an STL container, note that all modules can still\naccept foreign  ``py::module_local`` types in the direction of Python-to-C++.\nThe locality only affects the C++-to-Python direction. If this is needed in\nmultiple modules, you'll need to either:\n\n* Add a copy of the same STL binding to all of the modules which need it.\n\n* Restore the global status of that single binding by marking it\n  ``py::module_local(false)``.\n\nThe latter is an easy workaround, but in the long run it would be best to\nlocalize all common type bindings in order to avoid conflicts with\nthird-party modules.\n\n\nNegative strides for Python buffer objects and numpy arrays\n-----------------------------------------------------------\n\nSupport for negative strides required changing the integer type from unsigned\nto signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you\nhave compiler warnings enabled, you may notice some new conversion warnings\nafter upgrading. These can be resolved using ``static_cast``.\n\n\nDeprecation of some ``py::object`` APIs\n---------------------------------------\n\nTo compare ``py::object`` instances by pointer, you should now use\n``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.\nPreviously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but\nthat could be confusing and is now deprecated (so that it can eventually\nbe replaced with proper rich object comparison in a future release).\n\nFor classes which inherit from ``py::object``, ``borrowed`` and ``stolen``\nwere previously available as protected constructor tags. Now the types\nshould be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``\n(`#771 <https://github.com/pybind/pybind11/pull/771>`_).\n\n\nStricter compile-time error checking\n------------------------------------\n\nSome error checks have been moved from run time to compile time. Notably,\nautomatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is\nnot directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>``\nor ``std::shared_ptr<std::vector<T>>`` are not automatically convertible).\nAttempting to bind a function with such arguments now results in a compile-time\nerror instead of waiting to fail at run time.\n\n``py::init<...>()`` constructor definitions are also stricter and now prevent\nbindings which could cause unexpected behavior:\n\n.. code-block:: cpp\n\n    struct Example {\n        Example(int &);\n    };\n\n    py::class_<Example>(m, \"Example\")\n        .def(py::init<int &>()); // OK, exact match\n        // .def(py::init<int>()); // compile-time error, mismatch\n\nA non-``const`` lvalue reference is not allowed to bind to an rvalue. However,\nnote that a constructor taking ``const T &`` can still be registered using\n``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue.\n\nv2.1\n====\n\nMinimum compiler versions are enforced at compile time\n------------------------------------------------------\n\nThe minimums also apply to v2.0 but the check is now explicit and a compile-time\nerror is raised if the compiler does not meet the requirements:\n\n* GCC >= 4.8\n* clang >= 3.3 (appleclang >= 5.0)\n* MSVC >= 2015u3\n* Intel C++ >= 15.0\n\n\nThe ``py::metaclass`` attribute is not required for static properties\n---------------------------------------------------------------------\n\nBinding classes with static properties is now possible by default. The\nzero-parameter version of ``py::metaclass()`` is deprecated. However, a new\none-parameter ``py::metaclass(python_type)`` version was added for rare\ncases when a custom metaclass is needed to override pybind11's default.\n\n.. code-block:: cpp\n\n    // old -- emits a deprecation warning\n    py::class_<Foo>(m, \"Foo\", py::metaclass())\n        .def_property_readonly_static(\"foo\", ...);\n\n    // new -- static properties work without the attribute\n    py::class_<Foo>(m, \"Foo\")\n        .def_property_readonly_static(\"foo\", ...);\n\n    // new -- advanced feature, override pybind11's default metaclass\n    py::class_<Bar>(m, \"Bar\", py::metaclass(custom_python_type))\n        ...\n\n\nv2.0\n====\n\nBreaking changes in ``py::class_``\n----------------------------------\n\nThese changes were necessary to make type definitions in pybind11\nfuture-proof, to support PyPy via its ``cpyext`` mechanism (`#527\n<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency\n(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).\n\n1. Declarations of types that provide access via the buffer protocol must\n   now include the ``py::buffer_protocol()`` annotation as an argument to\n   the ``py::class_`` constructor.\n\n   .. code-block:: cpp\n\n       py::class_<Matrix>(\"Matrix\", py::buffer_protocol())\n           .def(py::init<...>())\n           .def_buffer(...);\n\n2. Classes which include static properties (e.g. ``def_readwrite_static()``)\n   must now include the ``py::metaclass()`` attribute. Note: this requirement\n   has since been removed in v2.1. If you're upgrading from 1.x, it's\n   recommended to skip directly to v2.1 or newer.\n\n3. This version of pybind11 uses a redesigned mechanism for instantiating\n   trampoline classes that are used to override virtual methods from within\n   Python. This led to the following user-visible syntax change:\n\n   .. code-block:: cpp\n\n       // old v1.x syntax\n       py::class_<TrampolineClass>(\"MyClass\")\n           .alias<MyClass>()\n           ...\n\n       // new v2.x syntax\n       py::class_<MyClass, TrampolineClass>(\"MyClass\")\n           ...\n\n   Importantly, both the original and the trampoline class are now specified\n   as arguments to the ``py::class_`` template, and the ``alias<..>()`` call\n   is gone. The new scheme has zero overhead in cases when Python doesn't\n   override any functions of the underlying C++ class.\n   `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.\n\n   The class type must be the first template argument given to ``py::class_``\n   while the trampoline can be mixed in arbitrary order with other arguments\n   (see the following section).\n\n\nDeprecation of the ``py::base<T>()`` attribute\n----------------------------------------------\n\n``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template\nargument to ``py::class_``. This new syntax also supports multiple inheritance.\nNote that, while the type being exported must be the first argument in the\n``py::class_<Class, ...>`` template, the order of the following types (bases,\nholder and/or trampoline) is not important.\n\n.. code-block:: cpp\n\n    // old v1.x\n    py::class_<Derived>(\"Derived\", py::base<Base>());\n\n    // new v2.x\n    py::class_<Derived, Base>(\"Derived\");\n\n    // new -- multiple inheritance\n    py::class_<Derived, Base1, Base2>(\"Derived\");\n\n    // new -- apart from `Derived` the argument order can be arbitrary\n    py::class_<Derived, Base1, Holder, Base2, Trampoline>(\"Derived\");\n\n\nOut-of-the-box support for ``std::shared_ptr``\n----------------------------------------------\n\nThe relevant type caster is now built in, so it's no longer necessary to\ninclude a declaration of the form:\n\n.. code-block:: cpp\n\n    PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)\n\nContinuing to do so won't cause an error or even a deprecation warning,\nbut it's completely redundant.\n\n\nDeprecation of a few ``py::object`` APIs\n----------------------------------------\n\nAll of the old-style calls emit deprecation warnings.\n\n+---------------------------------------+---------------------------------------------+\n|  Old syntax                           |  New syntax                                 |\n+=======================================+=============================================+\n| ``obj.call(args...)``                 | ``obj(args...)``                            |\n+---------------------------------------+---------------------------------------------+\n| ``obj.str()``                         | ``py::str(obj)``                            |\n+---------------------------------------+---------------------------------------------+\n| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)``           |\n+---------------------------------------+---------------------------------------------+\n| ``py::object(ptr, true)``             | ``py::reinterpret_borrow<py::object>(ptr)`` |\n+---------------------------------------+---------------------------------------------+\n| ``py::object(ptr, false)``            | ``py::reinterpret_steal<py::object>(ptr)``  |\n+---------------------------------------+---------------------------------------------+\n| ``if (obj.attr(\"foo\"))``              | ``if (py::hasattr(obj, \"foo\"))``            |\n+---------------------------------------+---------------------------------------------+\n| ``if (obj[\"bar\"])``                   | ``if (obj.contains(\"bar\"))``                |\n+---------------------------------------+---------------------------------------------+\n"
  },
  {
    "path": "include/pybind11/attr.h",
    "content": "/*\n    pybind11/attr.h: Infrastructure for processing custom\n    type and function attributes\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"cast.h\"\n#include \"trampoline_self_life_support.h\"\n\n#include <functional>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\n/// \\addtogroup annotations\n/// @{\n\n/// Annotation for methods\nstruct is_method {\n    handle class_;\n    explicit is_method(const handle &c) : class_(c) {}\n};\n\n/// Annotation for setters\nstruct is_setter {};\n\n/// Annotation for operators\nstruct is_operator {};\n\n/// Annotation for classes that cannot be subclassed\nstruct is_final {};\n\n/// Annotation for parent scope\nstruct scope {\n    handle value;\n    explicit scope(const handle &s) : value(s) {}\n};\n\n/// Annotation for documentation\nstruct doc {\n    const char *value;\n    explicit doc(const char *value) : value(value) {}\n};\n\n/// Annotation for function names\nstruct name {\n    const char *value;\n    explicit name(const char *value) : value(value) {}\n};\n\n/// Annotation indicating that a function is an overload associated with a given \"sibling\"\nstruct sibling {\n    handle value;\n    explicit sibling(const handle &value) : value(value.ptr()) {}\n};\n\n/// Annotation indicating that a class derives from another given type\ntemplate <typename T>\nstruct base {\n\n    PYBIND11_DEPRECATED(\n        \"base<T>() was deprecated in favor of specifying 'T' as a template argument to class_\")\n    base() = default;\n};\n\n/// Keep patient alive while nurse lives\ntemplate <size_t Nurse, size_t Patient>\nstruct keep_alive {};\n\n/// Annotation indicating that a class is involved in a multiple inheritance relationship\nstruct multiple_inheritance {};\n\n/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class\nstruct dynamic_attr {};\n\n/// Annotation which enables the buffer protocol for a type\nstruct buffer_protocol {};\n\n/// Annotation which enables releasing the GIL before calling the C++ destructor of wrapped\n/// instances (pybind/pybind11#1446).\nstruct release_gil_before_calling_cpp_dtor {};\n\n/// Annotation which requests that a special metaclass is created for a type\nstruct metaclass {\n    handle value;\n\n    PYBIND11_DEPRECATED(\"py::metaclass() is no longer required. It's turned on by default now.\")\n    metaclass() = default;\n\n    /// Override pybind11's default metaclass\n    explicit metaclass(handle value) : value(value) {}\n};\n\n/// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that\n/// may be used to customize the Python type.\n///\n/// The callback is invoked immediately before `PyType_Ready`.\n///\n/// Note: This is an advanced interface, and uses of it may require changes to\n/// work with later versions of pybind11.  You may wish to consult the\n/// implementation of `make_new_python_type` in `detail/classes.h` to understand\n/// the context in which the callback will be run.\nstruct custom_type_setup {\n    using callback = std::function<void(PyHeapTypeObject *heap_type)>;\n\n    explicit custom_type_setup(callback value) : value(std::move(value)) {}\n\n    callback value;\n};\n\n/// Annotation that marks a class as local to the module:\nstruct module_local {\n    const bool value;\n    constexpr explicit module_local(bool v = true) : value(v) {}\n};\n\n/// Annotation to mark enums as an arithmetic type\nstruct arithmetic {};\n\n/// Mark a function for addition at the beginning of the existing overload chain instead of the end\nstruct prepend {};\n\n/** \\rst\n    A call policy which places one or more guard variables (``Ts...``) around the function call.\n\n    For example, this definition:\n\n    .. code-block:: cpp\n\n        m.def(\"foo\", foo, py::call_guard<T>());\n\n    is equivalent to the following pseudocode:\n\n    .. code-block:: cpp\n\n        m.def(\"foo\", [](args...) {\n            T scope_guard;\n            return foo(args...); // forwarded arguments\n        });\n \\endrst */\ntemplate <typename... Ts>\nstruct call_guard;\n\ntemplate <>\nstruct call_guard<> {\n    using type = detail::void_type;\n};\n\ntemplate <typename T>\nstruct call_guard<T> {\n    static_assert(std::is_default_constructible<T>::value,\n                  \"The guard type must be default constructible\");\n\n    using type = T;\n};\n\ntemplate <typename T, typename... Ts>\nstruct call_guard<T, Ts...> {\n    struct type {\n        T guard{}; // Compose multiple guard types with left-to-right default-constructor order\n        typename call_guard<Ts...>::type next{};\n    };\n};\n\n/// @} annotations\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n/* Forward declarations */\nenum op_id : int;\nenum op_type : int;\nstruct undefined_t;\ntemplate <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>\nstruct op_;\nvoid keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);\n\n/// Internal data structure which holds metadata about a keyword argument\nstruct argument_record {\n    const char *name;  ///< Argument name\n    const char *descr; ///< Human-readable version of the argument value\n    handle value;      ///< Associated Python object\n    bool convert : 1;  ///< True if the argument is allowed to convert when loading\n    bool none : 1;     ///< True if None is allowed when loading\n\n    argument_record(const char *name, const char *descr, handle value, bool convert, bool none)\n        : name(name), descr(descr), value(value), convert(convert), none(none) {}\n};\n\n/// Internal data structure which holds metadata about a bound function (signature, overloads,\n/// etc.)\n#define PYBIND11_DETAIL_FUNCTION_RECORD_ABI_ID \"v1\" // PLEASE UPDATE if the struct is changed.\nstruct function_record {\n    function_record()\n        : is_constructor(false), is_new_style_constructor(false), is_stateless(false),\n          is_operator(false), is_method(false), is_setter(false), has_args(false),\n          has_kwargs(false), prepend(false) {}\n\n    /// Function name\n    char *name = nullptr; /* why no C++ strings? They generate heavier code.. */\n\n    // User-specified documentation string\n    char *doc = nullptr;\n\n    /// Human-readable version of the function signature\n    char *signature = nullptr;\n\n    /// List of registered keyword arguments\n    std::vector<argument_record> args;\n\n    /// Pointer to lambda function which converts arguments and performs the actual call\n    handle (*impl)(function_call &) = nullptr;\n\n    /// Storage for the wrapped function pointer and captured data, if any\n    void *data[3] = {};\n\n    /// Pointer to custom destructor for 'data' (if needed)\n    void (*free_data)(function_record *ptr) = nullptr;\n\n    /// Return value policy associated with this function\n    return_value_policy policy = return_value_policy::automatic;\n\n    /// True if name == '__init__'\n    bool is_constructor : 1;\n\n    /// True if this is a new-style `__init__` defined in `detail/init.h`\n    bool is_new_style_constructor : 1;\n\n    /// True if this is a stateless function pointer\n    bool is_stateless : 1;\n\n    /// True if this is an operator (__add__), etc.\n    bool is_operator : 1;\n\n    /// True if this is a method\n    bool is_method : 1;\n\n    /// True if this is a setter\n    bool is_setter : 1;\n\n    /// True if the function has a '*args' argument\n    bool has_args : 1;\n\n    /// True if the function has a '**kwargs' argument\n    bool has_kwargs : 1;\n\n    /// True if this function is to be inserted at the beginning of the overload resolution chain\n    bool prepend : 1;\n\n    /// Number of arguments (including py::args and/or py::kwargs, if present)\n    std::uint16_t nargs;\n\n    /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs\n    /// argument or by a py::kw_only annotation.\n    std::uint16_t nargs_pos = 0;\n\n    /// Number of leading arguments (counted in `nargs`) that are positional-only\n    std::uint16_t nargs_pos_only = 0;\n\n    /// Python method object\n    PyMethodDef *def = nullptr;\n\n    /// Python handle to the parent scope (a class or a module)\n    handle scope;\n\n    /// Python handle to the sibling function representing an overload chain\n    handle sibling;\n\n    /// Pointer to next overload\n    function_record *next = nullptr;\n};\n// The main purpose of this macro is to make it easy to pin-point the critically related code\n// sections.\n#define PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(...)              \\\n    static_assert(                                                                                \\\n        __VA_ARGS__,                                                                              \\\n        \"Violation of precondition for pybind11/functional.h performance optimizations!\")\n\n/// Special data structure which (temporarily) holds metadata about a bound class\nstruct type_record {\n    PYBIND11_NOINLINE type_record()\n        : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),\n          module_local(false), is_final(false), release_gil_before_calling_cpp_dtor(false) {}\n\n    /// Handle to the parent scope\n    handle scope;\n\n    /// Name of the class\n    const char *name = nullptr;\n\n    // Pointer to RTTI type_info data structure\n    const std::type_info *type = nullptr;\n\n    /// How large is the underlying C++ type?\n    size_t type_size = 0;\n\n    /// What is the alignment of the underlying C++ type?\n    size_t type_align = 0;\n\n    /// How large is the type's holder?\n    size_t holder_size = 0;\n\n    /// The global operator new can be overridden with a class-specific variant\n    void *(*operator_new)(size_t) = nullptr;\n\n    /// Function pointer to class_<..>::init_instance\n    void (*init_instance)(instance *, const void *) = nullptr;\n\n    /// Function pointer to class_<..>::dealloc\n    void (*dealloc)(detail::value_and_holder &) = nullptr;\n\n    /// Function pointer for casting alias class (aka trampoline) pointer to\n    /// trampoline_self_life_support pointer. Sidesteps cross-DSO RTTI issues\n    /// on platforms like macOS (see PR #5728 for details).\n    get_trampoline_self_life_support_fn get_trampoline_self_life_support\n        = [](void *) -> trampoline_self_life_support * { return nullptr; };\n\n    /// List of base classes of the newly created type\n    list bases;\n\n    /// Optional docstring\n    const char *doc = nullptr;\n\n    /// Custom metaclass (optional)\n    handle metaclass;\n\n    /// Custom type setup.\n    custom_type_setup::callback custom_type_setup_callback;\n\n    /// Multiple inheritance marker\n    bool multiple_inheritance : 1;\n\n    /// Does the class manage a __dict__?\n    bool dynamic_attr : 1;\n\n    /// Does the class implement the buffer protocol?\n    bool buffer_protocol : 1;\n\n    /// Is the class definition local to the module shared object?\n    bool module_local : 1;\n\n    /// Is the class inheritable from python classes?\n    bool is_final : 1;\n\n    /// Solves pybind/pybind11#1446\n    bool release_gil_before_calling_cpp_dtor : 1;\n\n    holder_enum_t holder_enum_v = holder_enum_t::undefined;\n\n    PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {\n        auto *base_info = detail::get_type_info(base, false);\n        if (!base_info) {\n            std::string tname(base.name());\n            detail::clean_type_id(tname);\n            pybind11_fail(\"generic_type: type \\\"\" + std::string(name)\n                          + \"\\\" referenced unknown base type \\\"\" + tname + \"\\\"\");\n        }\n\n        // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.\n        bool this_has_unique_ptr_holder = (holder_enum_v == holder_enum_t::std_unique_ptr);\n        bool base_has_unique_ptr_holder\n            = (base_info->holder_enum_v == holder_enum_t::std_unique_ptr);\n        if (this_has_unique_ptr_holder != base_has_unique_ptr_holder) {\n            std::string tname(base.name());\n            detail::clean_type_id(tname);\n            pybind11_fail(\"generic_type: type \\\"\" + std::string(name) + \"\\\" \"\n                          + (this_has_unique_ptr_holder ? \"does not have\" : \"has\")\n                          + \" a non-default holder type while its base \\\"\" + tname + \"\\\" \"\n                          + (base_has_unique_ptr_holder ? \"does not\" : \"does\"));\n        }\n\n        bases.append(reinterpret_cast<PyObject *>(base_info->type));\n\n#ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET\n        dynamic_attr |= base_info->type->tp_dictoffset != 0;\n#else\n        dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;\n#endif\n\n        if (caster) {\n            base_info->implicit_casts.emplace_back(type, caster);\n        }\n    }\n};\n\ninline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {\n    args.reserve(f.nargs);\n    args_convert.reserve(f.nargs);\n}\n\n/// Tag for a new-style `__init__` defined in `detail/init.h`\nstruct is_new_style_constructor {};\n\n/**\n * Partial template specializations to process custom attributes provided to\n * cpp_function_ and class_. These are either used to initialize the respective\n * fields in the type_record and function_record data structures or executed at\n * runtime to deal with custom call policies (e.g. keep_alive).\n */\ntemplate <typename T, typename SFINAE = void>\nstruct process_attribute;\n\ntemplate <typename T>\nstruct process_attribute_default {\n    /// Default implementation: do nothing\n    static void init(const T &, function_record *) {}\n    static void init(const T &, type_record *) {}\n    static void precall(function_call &) {}\n    static void postcall(function_call &, handle) {}\n};\n\n/// Process an attribute specifying the function's name\ntemplate <>\nstruct process_attribute<name> : process_attribute_default<name> {\n    static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }\n};\n\n/// Process an attribute specifying the function's docstring\ntemplate <>\nstruct process_attribute<doc> : process_attribute_default<doc> {\n    static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }\n};\n\n/// Process an attribute specifying the function's docstring (provided as a C-style string)\ntemplate <>\nstruct process_attribute<const char *> : process_attribute_default<const char *> {\n    static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }\n    static void init(const char *d, type_record *r) { r->doc = d; }\n};\ntemplate <>\nstruct process_attribute<char *> : process_attribute<const char *> {};\n\n/// Process an attribute indicating the function's return value policy\ntemplate <>\nstruct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {\n    static void init(const return_value_policy &p, function_record *r) { r->policy = p; }\n};\n\n/// Process an attribute which indicates that this is an overloaded function associated with a\n/// given sibling\ntemplate <>\nstruct process_attribute<sibling> : process_attribute_default<sibling> {\n    static void init(const sibling &s, function_record *r) { r->sibling = s.value; }\n};\n\n/// Process an attribute which indicates that this function is a method\ntemplate <>\nstruct process_attribute<is_method> : process_attribute_default<is_method> {\n    static void init(const is_method &s, function_record *r) {\n        r->is_method = true;\n        r->scope = s.class_;\n    }\n};\n\n/// Process an attribute which indicates that this function is a setter\ntemplate <>\nstruct process_attribute<is_setter> : process_attribute_default<is_setter> {\n    static void init(const is_setter &, function_record *r) { r->is_setter = true; }\n};\n\n/// Process an attribute which indicates the parent scope of a method\ntemplate <>\nstruct process_attribute<scope> : process_attribute_default<scope> {\n    static void init(const scope &s, function_record *r) { r->scope = s.value; }\n};\n\n/// Process an attribute which indicates that this function is an operator\ntemplate <>\nstruct process_attribute<is_operator> : process_attribute_default<is_operator> {\n    static void init(const is_operator &, function_record *r) { r->is_operator = true; }\n};\n\ntemplate <>\nstruct process_attribute<is_new_style_constructor>\n    : process_attribute_default<is_new_style_constructor> {\n    static void init(const is_new_style_constructor &, function_record *r) {\n        r->is_new_style_constructor = true;\n    }\n};\n\ninline void check_kw_only_arg(const arg &a, function_record *r) {\n    if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\\0')) {\n        pybind11_fail(\"arg(): cannot specify an unnamed argument after a kw_only() annotation or \"\n                      \"args() argument\");\n    }\n}\n\ninline void append_self_arg_if_needed(function_record *r) {\n    if (r->is_method && r->args.empty()) {\n        r->args.emplace_back(\"self\", nullptr, handle(), /*convert=*/true, /*none=*/false);\n    }\n}\n\n/// Process a keyword argument attribute (*without* a default value)\ntemplate <>\nstruct process_attribute<arg> : process_attribute_default<arg> {\n    static void init(const arg &a, function_record *r) {\n        append_self_arg_if_needed(r);\n        r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);\n\n        check_kw_only_arg(a, r);\n    }\n};\n\n/// Process a keyword argument attribute (*with* a default value)\ntemplate <>\nstruct process_attribute<arg_v> : process_attribute_default<arg_v> {\n    static void init(const arg_v &a, function_record *r) {\n        if (r->is_method && r->args.empty()) {\n            r->args.emplace_back(\n                \"self\", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);\n        }\n\n        if (!a.value) {\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            std::string descr(\"'\");\n            if (a.name) {\n                descr += std::string(a.name) + \": \";\n            }\n            descr += a.type + \"'\";\n            if (r->is_method) {\n                if (r->name) {\n                    descr += \" in method '\" + (std::string) str(r->scope) + \".\"\n                             + (std::string) r->name + \"'\";\n                } else {\n                    descr += \" in method of '\" + (std::string) str(r->scope) + \"'\";\n                }\n            } else if (r->name) {\n                descr += \" in function '\" + (std::string) r->name + \"'\";\n            }\n            pybind11_fail(\"arg(): could not convert default argument \" + descr\n                          + \" into a Python object (type not registered yet?)\");\n#else\n            pybind11_fail(\"arg(): could not convert default argument \"\n                          \"into a Python object (type not registered yet?). \"\n                          \"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for \"\n                          \"more information.\");\n#endif\n        }\n        r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);\n\n        check_kw_only_arg(a, r);\n    }\n};\n\n/// Process a keyword-only-arguments-follow pseudo argument\ntemplate <>\nstruct process_attribute<kw_only> : process_attribute_default<kw_only> {\n    static void init(const kw_only &, function_record *r) {\n        append_self_arg_if_needed(r);\n        if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {\n            pybind11_fail(\"Mismatched args() and kw_only(): they must occur at the same relative \"\n                          \"argument location (or omit kw_only() entirely)\");\n        }\n        r->nargs_pos = static_cast<std::uint16_t>(r->args.size());\n    }\n};\n\n/// Process a positional-only-argument maker\ntemplate <>\nstruct process_attribute<pos_only> : process_attribute_default<pos_only> {\n    static void init(const pos_only &, function_record *r) {\n        append_self_arg_if_needed(r);\n        r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());\n        if (r->nargs_pos_only > r->nargs_pos) {\n            pybind11_fail(\"pos_only(): cannot follow a py::args() argument\");\n        }\n        // It also can't follow a kw_only, but a static_assert in pybind11.h checks that\n    }\n};\n\n/// Process a parent class attribute.  Single inheritance only (class_ itself already guarantees\n/// that)\ntemplate <typename T>\nstruct process_attribute<T, enable_if_t<is_pyobject<T>::value>>\n    : process_attribute_default<handle> {\n    static void init(const handle &h, type_record *r) { r->bases.append(h); }\n};\n\n/// Process a parent class attribute (deprecated, does not support multiple inheritance)\ntemplate <typename T>\nstruct process_attribute<base<T>> : process_attribute_default<base<T>> {\n    static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }\n};\n\n/// Process a multiple inheritance attribute\ntemplate <>\nstruct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {\n    static void init(const multiple_inheritance &, type_record *r) {\n        r->multiple_inheritance = true;\n    }\n};\n\ntemplate <>\nstruct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {\n    static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }\n};\n\ntemplate <>\nstruct process_attribute<custom_type_setup> {\n    static void init(const custom_type_setup &value, type_record *r) {\n        r->custom_type_setup_callback = value.value;\n    }\n};\n\ntemplate <>\nstruct process_attribute<is_final> : process_attribute_default<is_final> {\n    static void init(const is_final &, type_record *r) { r->is_final = true; }\n};\n\ntemplate <>\nstruct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {\n    static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }\n};\n\ntemplate <>\nstruct process_attribute<metaclass> : process_attribute_default<metaclass> {\n    static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }\n};\n\ntemplate <>\nstruct process_attribute<module_local> : process_attribute_default<module_local> {\n    static void init(const module_local &l, type_record *r) { r->module_local = l.value; }\n};\n\ntemplate <>\nstruct process_attribute<release_gil_before_calling_cpp_dtor>\n    : process_attribute_default<release_gil_before_calling_cpp_dtor> {\n    static void init(const release_gil_before_calling_cpp_dtor &, type_record *r) {\n        r->release_gil_before_calling_cpp_dtor = true;\n    }\n};\n\n/// Process a 'prepend' attribute, putting this at the beginning of the overload chain\ntemplate <>\nstruct process_attribute<prepend> : process_attribute_default<prepend> {\n    static void init(const prepend &, function_record *r) { r->prepend = true; }\n};\n\n/// Process an 'arithmetic' attribute for enums (does nothing here)\ntemplate <>\nstruct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};\n\ntemplate <typename... Ts>\nstruct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};\n\n/**\n * Process a keep_alive call policy -- invokes keep_alive_impl during the\n * pre-call handler if both Nurse, Patient != 0 and use the post-call handler\n * otherwise\n */\ntemplate <size_t Nurse, size_t Patient>\nstruct process_attribute<keep_alive<Nurse, Patient>>\n    : public process_attribute_default<keep_alive<Nurse, Patient>> {\n    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>\n    static void precall(function_call &call) {\n        keep_alive_impl(Nurse, Patient, call, handle());\n    }\n    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>\n    static void postcall(function_call &, handle) {}\n    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>\n    static void precall(function_call &) {}\n    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>\n    static void postcall(function_call &call, handle ret) {\n        keep_alive_impl(Nurse, Patient, call, ret);\n    }\n};\n\n/// Recursively iterate over variadic template arguments\ntemplate <typename... Args>\nstruct process_attributes {\n    static void init(const Args &...args, function_record *r) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);\n        PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);\n        using expander = int[];\n        (void) expander{\n            0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};\n    }\n    static void init(const Args &...args, type_record *r) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);\n        PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);\n        using expander = int[];\n        (void) expander{0,\n                        (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};\n    }\n    static void precall(function_call &call) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);\n        using expander = int[];\n        (void) expander{0,\n                        (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};\n    }\n    static void postcall(function_call &call, handle fn_ret) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);\n        PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);\n        using expander = int[];\n        (void) expander{\n            0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};\n    }\n};\n\ntemplate <typename T>\nstruct is_keep_alive : std::false_type {};\n\ntemplate <size_t Nurse, size_t Patient>\nstruct is_keep_alive<keep_alive<Nurse, Patient>> : std::true_type {};\n\ntemplate <typename T>\nusing is_call_guard = is_instantiation<call_guard, T>;\n\n/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)\ntemplate <typename... Extra>\nusing extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;\n\n/// Check the number of named arguments at compile time\ntemplate <typename... Extra,\n          size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),\n          size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>\nconstexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);\n    return named == 0\n           || (self + named + static_cast<size_t>(has_args) + static_cast<size_t>(has_kwargs))\n                  == nargs;\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/buffer_info.h",
    "content": "/*\n    pybind11/buffer_info.h: Python buffer object interface\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Default, C-style strides\ninline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {\n    auto ndim = shape.size();\n    std::vector<ssize_t> strides(ndim, itemsize);\n    if (ndim > 0) {\n        for (size_t i = ndim - 1; i > 0; --i) {\n            strides[i - 1] = strides[i] * shape[i];\n        }\n    }\n    return strides;\n}\n\n// F-style strides; default when constructing an array_t with `ExtraFlags & f_style`\ninline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {\n    auto ndim = shape.size();\n    std::vector<ssize_t> strides(ndim, itemsize);\n    for (size_t i = 1; i < ndim; ++i) {\n        strides[i] = strides[i - 1] * shape[i - 1];\n    }\n    return strides;\n}\n\ntemplate <typename T, typename SFINAE = void>\nstruct compare_buffer_info;\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Information record describing a Python buffer object\nstruct buffer_info {\n    void *ptr = nullptr;          // Pointer to the underlying storage\n    ssize_t itemsize = 0;         // Size of individual items in bytes\n    ssize_t size = 0;             // Total number of entries\n    std::string format;           // For homogeneous buffers, this should be set to\n                                  // format_descriptor<T>::format()\n    ssize_t ndim = 0;             // Number of dimensions\n    std::vector<ssize_t> shape;   // Shape of the tensor (1 entry per dimension)\n    std::vector<ssize_t> strides; // Number of bytes between adjacent entries\n                                  // (for each per dimension)\n    bool readonly = false;        // flag to indicate if the underlying storage may be written to\n\n    buffer_info() = default;\n\n    buffer_info(void *ptr,\n                ssize_t itemsize,\n                const std::string &format,\n                ssize_t ndim,\n                detail::any_container<ssize_t> shape_in,\n                detail::any_container<ssize_t> strides_in,\n                bool readonly = false)\n        : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),\n          shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {\n        if (ndim != static_cast<ssize_t>(shape.size())\n            || ndim != static_cast<ssize_t>(strides.size())) {\n            pybind11_fail(\"buffer_info: ndim doesn't match shape and/or strides length\");\n        }\n        for (size_t i = 0; i < static_cast<size_t>(ndim); ++i) {\n            size *= shape[i];\n        }\n    }\n\n    template <typename T>\n    buffer_info(T *ptr,\n                detail::any_container<ssize_t> shape_in,\n                detail::any_container<ssize_t> strides_in,\n                bool readonly = false)\n        : buffer_info(private_ctr_tag(),\n                      ptr,\n                      sizeof(T),\n                      format_descriptor<T>::format(),\n                      static_cast<ssize_t>(shape_in->size()),\n                      std::move(shape_in),\n                      std::move(strides_in),\n                      readonly) {}\n\n    buffer_info(void *ptr,\n                ssize_t itemsize,\n                const std::string &format,\n                ssize_t size,\n                bool readonly = false)\n        : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}\n\n    template <typename T>\n    buffer_info(T *ptr, ssize_t size, bool readonly = false)\n        : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}\n\n    template <typename T>\n    buffer_info(const T *ptr, ssize_t size, bool readonly = true)\n        : buffer_info(\n              const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}\n\n    explicit buffer_info(Py_buffer *view, bool ownview = true)\n        : buffer_info(\n              view->buf,\n              view->itemsize,\n              view->format,\n              view->ndim,\n              {view->shape, view->shape + view->ndim},\n              /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects\n               * ignore this flag and return a view with NULL strides.\n               * When strides are NULL, build them manually.  */\n              view->strides\n                  ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)\n                  : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),\n              (view->readonly != 0)) {\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        this->m_view = view;\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        this->ownview = ownview;\n    }\n\n    buffer_info(const buffer_info &) = delete;\n    buffer_info &operator=(const buffer_info &) = delete;\n\n    buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }\n\n    buffer_info &operator=(buffer_info &&rhs) noexcept {\n        ptr = rhs.ptr;\n        itemsize = rhs.itemsize;\n        size = rhs.size;\n        format = std::move(rhs.format);\n        ndim = rhs.ndim;\n        shape = std::move(rhs.shape);\n        strides = std::move(rhs.strides);\n        std::swap(m_view, rhs.m_view);\n        std::swap(ownview, rhs.ownview);\n        readonly = rhs.readonly;\n        return *this;\n    }\n\n    ~buffer_info() {\n        if (m_view && ownview) {\n            PyBuffer_Release(m_view);\n            delete m_view;\n        }\n    }\n\n    Py_buffer *view() const { return m_view; }\n    Py_buffer *&view() { return m_view; }\n\n    /* True if the buffer item type is equivalent to `T`. */\n    // To define \"equivalent\" by example:\n    // `buffer_info::item_type_is_equivalent_to<int>(b)` and\n    // `buffer_info::item_type_is_equivalent_to<long>(b)` may both be true\n    // on some platforms, but `int` and `unsigned` will never be equivalent.\n    // For the ground truth, please inspect `detail::compare_buffer_info<>`.\n    template <typename T>\n    bool item_type_is_equivalent_to() const {\n        return detail::compare_buffer_info<T>::compare(*this);\n    }\n\nprivate:\n    struct private_ctr_tag {};\n\n    buffer_info(private_ctr_tag,\n                void *ptr,\n                ssize_t itemsize,\n                const std::string &format,\n                ssize_t ndim,\n                detail::any_container<ssize_t> &&shape_in,\n                detail::any_container<ssize_t> &&strides_in,\n                bool readonly)\n        : buffer_info(\n              ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}\n\n    Py_buffer *m_view = nullptr;\n    bool ownview = false;\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename T, typename SFINAE>\nstruct compare_buffer_info {\n    static bool compare(const buffer_info &b) {\n        // NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *`\n        return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);\n    }\n};\n\ntemplate <typename T>\nstruct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {\n    static bool compare(const buffer_info &b) {\n        return static_cast<size_t>(b.itemsize) == sizeof(T)\n               && (b.format == format_descriptor<T>::value\n                   || ((sizeof(T) == sizeof(long))\n                       && b.format == (std::is_unsigned<T>::value ? \"L\" : \"l\"))\n                   || ((sizeof(T) == sizeof(size_t))\n                       && b.format == (std::is_unsigned<T>::value ? \"N\" : \"n\")));\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/cast.h",
    "content": "/*\n    pybind11/cast.h: Partial template specializations to cast between\n    C++ and Python types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/argument_vector.h\"\n#include \"detail/common.h\"\n#include \"detail/descr.h\"\n#include \"detail/holder_caster_foreign_helpers.h\"\n#include \"detail/native_enum_data.h\"\n#include \"detail/type_caster_base.h\"\n#include \"detail/typeid.h\"\n#include \"pytypes.h\"\n\n#include <array>\n#include <cstring>\n#include <functional>\n#include <iosfwd>\n#include <iterator>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename type, typename SFINAE = void>\nclass type_caster : public type_caster_base<type> {};\ntemplate <typename type>\nusing make_caster = type_caster<intrinsic_t<type>>;\n\n// Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T\ntemplate <typename T>\ntypename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {\n    using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893\n    return caster.operator result_t();\n}\ntemplate <typename T>\ntypename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>\ncast_op(make_caster<T> &&caster) {\n    using result_t = typename make_caster<T>::template cast_op_type<\n        typename std::add_rvalue_reference<T>::type>; // See PR #4893\n    return std::move(caster).operator result_t();\n}\n\ntemplate <typename EnumType>\nclass type_caster_enum_type {\nprivate:\n    using Underlying = typename std::underlying_type<EnumType>::type;\n\npublic:\n    static constexpr auto name = const_name<EnumType>();\n\n    template <typename SrcType>\n    static handle cast(SrcType &&src, return_value_policy, handle parent) {\n        handle native_enum\n            = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));\n        if (native_enum) {\n            return native_enum(static_cast<Underlying>(src)).release();\n        }\n        return type_caster_base<EnumType>::cast(\n            std::forward<SrcType>(src),\n            // Fixes https://github.com/pybind/pybind11/pull/3643#issuecomment-1022987818:\n            return_value_policy::copy,\n            parent);\n    }\n\n    template <typename SrcType>\n    static handle cast(SrcType *src, return_value_policy policy, handle parent) {\n        return cast(*src, policy, parent);\n    }\n\n    bool load(handle src, bool convert) {\n        handle native_enum\n            = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));\n        if (native_enum) {\n            if (!isinstance(src, native_enum)) {\n                return false;\n            }\n            type_caster<Underlying> underlying_caster;\n            if (!underlying_caster.load(src.attr(\"value\"), convert)) {\n                pybind11_fail(\"native_enum internal consistency failure.\");\n            }\n            native_value = static_cast<EnumType>(static_cast<Underlying>(underlying_caster));\n            native_loaded = true;\n            return true;\n        }\n\n        type_caster_base<EnumType> legacy_caster;\n        if (legacy_caster.load(src, convert)) {\n            legacy_ptr = static_cast<EnumType *>(legacy_caster);\n            return true;\n        }\n        return false;\n    }\n\n    template <typename T>\n    using cast_op_type = detail::cast_op_type<T>;\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator EnumType *() { return native_loaded ? &native_value : legacy_ptr; }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator EnumType &() {\n        if (!native_loaded && !legacy_ptr) {\n            throw reference_cast_error();\n        }\n        return native_loaded ? native_value : *legacy_ptr;\n    }\n\nprivate:\n    EnumType native_value; // if loading a py::native_enum\n    bool native_loaded = false;\n    EnumType *legacy_ptr = nullptr; // if loading a py::enum_\n};\n\ntemplate <typename EnumType, typename SFINAE = void>\nstruct type_caster_enum_type_enabled : std::true_type {};\n\ntemplate <typename T>\nstruct type_uses_type_caster_enum_type {\n    static constexpr bool value\n        = std::is_enum<T>::value && type_caster_enum_type_enabled<T>::value;\n};\n\ntemplate <typename EnumType>\nclass type_caster<EnumType, detail::enable_if_t<type_uses_type_caster_enum_type<EnumType>::value>>\n    : public type_caster_enum_type<EnumType> {};\n\ntemplate <typename T, detail::enable_if_t<std::is_enum<T>::value, int> = 0>\nbool isinstance_native_enum_impl(handle obj, const std::type_info &tp) {\n    handle native_enum = global_internals_native_enum_type_map_get_item(tp);\n    if (!native_enum) {\n        return false;\n    }\n    return isinstance(obj, native_enum);\n}\n\ntemplate <typename T, detail::enable_if_t<!std::is_enum<T>::value, int> = 0>\nbool isinstance_native_enum_impl(handle, const std::type_info &) {\n    return false;\n}\n\ntemplate <typename T>\nbool isinstance_native_enum(handle obj, const std::type_info &tp) {\n    return isinstance_native_enum_impl<intrinsic_t<T>>(obj, tp);\n}\n\ntemplate <typename type>\nclass type_caster<std::reference_wrapper<type>> {\nprivate:\n    using caster_t = make_caster<type>;\n    caster_t subcaster;\n    using reference_t = type &;\n    using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;\n\n    static_assert(\n        std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value\n            || std::is_same<reference_t, subcaster_cast_op_type>::value,\n        \"std::reference_wrapper<T> caster requires T to have a caster with an \"\n        \"`operator T &()` or `operator const T &()`\");\n\npublic:\n    bool load(handle src, bool convert) { return subcaster.load(src, convert); }\n    static constexpr auto name = caster_t::name;\n    static handle\n    cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {\n        // It is definitely wrong to take ownership of this pointer, so mask that rvp\n        if (policy == return_value_policy::take_ownership\n            || policy == return_value_policy::automatic) {\n            policy = return_value_policy::automatic_reference;\n        }\n        return caster_t::cast(&src.get(), policy, parent);\n    }\n    template <typename T>\n    using cast_op_type = std::reference_wrapper<type>;\n    explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }\n};\n\n#define PYBIND11_TYPE_CASTER(type, py_name)                                                       \\\nprotected:                                                                                        \\\n    type value;                                                                                   \\\n                                                                                                  \\\npublic:                                                                                           \\\n    static constexpr auto name = py_name;                                                         \\\n    template <typename T_,                                                                        \\\n              ::pybind11::detail::enable_if_t<                                                    \\\n                  std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value,                 \\\n                  int>                                                                            \\\n              = 0>                                                                                \\\n    static ::pybind11::handle cast(                                                               \\\n        T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) {             \\\n        if (!src)                                                                                 \\\n            return ::pybind11::none().release();                                                  \\\n        if (policy == ::pybind11::return_value_policy::take_ownership) {                          \\\n            auto h = cast(std::move(*src), policy, parent);                                       \\\n            delete src;                                                                           \\\n            return h;                                                                             \\\n        }                                                                                         \\\n        return cast(*src, policy, parent);                                                        \\\n    }                                                                                             \\\n    operator type *() { return &value; }               /* NOLINT(bugprone-macro-parentheses) */   \\\n    operator type &() { return value; }                /* NOLINT(bugprone-macro-parentheses) */   \\\n    operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */   \\\n    template <typename T_>                                                                        \\\n    using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>\n\ntemplate <typename CharT>\nusing is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */\n#if defined(PYBIND11_HAS_U8STRING)\n                                std::is_same<CharT, char8_t>, /* std::u8string */\n#endif\n                                std::is_same<CharT, char16_t>, /* std::u16string */\n                                std::is_same<CharT, char32_t>, /* std::u32string */\n                                std::is_same<CharT, wchar_t>   /* std::wstring */\n                                >;\n\ntemplate <typename T>\nstruct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {\n    using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;\n    using _py_type_1 = conditional_t<std::is_signed<T>::value,\n                                     _py_type_0,\n                                     typename std::make_unsigned<_py_type_0>::type>;\n    using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;\n\npublic:\n    bool load(handle src, bool convert) {\n        py_type py_value;\n\n        if (!src) {\n            return false;\n        }\n\n        if (std::is_floating_point<T>::value) {\n            if (convert || PyFloat_Check(src.ptr()) || PYBIND11_LONG_CHECK(src.ptr())) {\n                py_value = (py_type) PyFloat_AsDouble(src.ptr());\n            } else {\n                return false;\n            }\n        } else if (PyFloat_Check(src.ptr())\n                   || !(convert || PYBIND11_LONG_CHECK(src.ptr())\n                        || PYBIND11_INDEX_CHECK(src.ptr()))) {\n            // Explicitly reject float → int conversion even in convert mode.\n            // This prevents silent truncation (e.g., 1.9 → 1).\n            // Only int → float conversion is allowed (widening, no precision loss).\n            // Also reject if none of the conversion conditions are met.\n            return false;\n        } else {\n            handle src_or_index = src;\n            // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.\n#if defined(PYPY_VERSION)\n            object index;\n            // If not a PyLong, we need to call PyNumber_Index explicitly on PyPy.\n            // When convert is false, we only reach here if PYBIND11_INDEX_CHECK passed above.\n            if (!PYBIND11_LONG_CHECK(src.ptr())) {\n                index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));\n                if (!index) {\n                    PyErr_Clear();\n                    if (!convert)\n                        return false;\n                } else {\n                    src_or_index = index;\n                }\n            }\n#endif\n            if (std::is_unsigned<py_type>::value) {\n                py_value = as_unsigned<py_type>(src_or_index.ptr());\n            } else { // signed integer:\n                py_value = sizeof(T) <= sizeof(long)\n                               ? (py_type) PyLong_AsLong(src_or_index.ptr())\n                               : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());\n            }\n        }\n\n        bool py_err = (PyErr_Occurred() != nullptr);\n        if (py_err) {\n            assert(py_value == static_cast<py_type>(-1));\n        }\n\n        // Check to see if the conversion is valid (integers should match exactly)\n        // Signed/unsigned checks happen elsewhere\n        if (py_err\n            || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)\n                && py_value != (py_type) (T) py_value)) {\n            PyErr_Clear();\n            if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {\n                auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value\n                                                         ? PyNumber_Float(src.ptr())\n                                                         : PyNumber_Long(src.ptr()));\n                PyErr_Clear();\n                return load(tmp, false);\n            }\n            return false;\n        }\n\n        value = (T) py_value;\n        return true;\n    }\n\n    template <typename U = T>\n    static typename std::enable_if<std::is_floating_point<U>::value, handle>::type\n    cast(U src, return_value_policy /* policy */, handle /* parent */) {\n        return PyFloat_FromDouble((double) src);\n    }\n\n    template <typename U = T>\n    static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value\n                                       && (sizeof(U) <= sizeof(long)),\n                                   handle>::type\n    cast(U src, return_value_policy /* policy */, handle /* parent */) {\n        return PYBIND11_LONG_FROM_SIGNED((long) src);\n    }\n\n    template <typename U = T>\n    static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value\n                                       && (sizeof(U) <= sizeof(unsigned long)),\n                                   handle>::type\n    cast(U src, return_value_policy /* policy */, handle /* parent */) {\n        return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);\n    }\n\n    template <typename U = T>\n    static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value\n                                       && (sizeof(U) > sizeof(long)),\n                                   handle>::type\n    cast(U src, return_value_policy /* policy */, handle /* parent */) {\n        return PyLong_FromLongLong((long long) src);\n    }\n\n    template <typename U = T>\n    static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value\n                                       && (sizeof(U) > sizeof(unsigned long)),\n                                   handle>::type\n    cast(U src, return_value_policy /* policy */, handle /* parent */) {\n        return PyLong_FromUnsignedLongLong((unsigned long long) src);\n    }\n\n    PYBIND11_TYPE_CASTER(\n        T,\n        io_name<std::is_integral<T>::value>(\"typing.SupportsInt | typing.SupportsIndex\",\n                                            \"int\",\n                                            \"typing.SupportsFloat | typing.SupportsIndex\",\n                                            \"float\"));\n};\n\ntemplate <typename T>\nstruct void_caster {\npublic:\n    bool load(handle src, bool) {\n        if (src && src.is_none()) {\n            return true;\n        }\n        return false;\n    }\n    static handle cast(T, return_value_policy /* policy */, handle /* parent */) {\n        return none().release();\n    }\n    PYBIND11_TYPE_CASTER(T, const_name(\"None\"));\n};\n\ntemplate <>\nclass type_caster<void_type> : public void_caster<void_type> {};\n\ntemplate <>\nclass type_caster<void> : public type_caster<void_type> {\npublic:\n    using type_caster<void_type>::cast;\n\n    bool load(handle h, bool) {\n        if (!h) {\n            return false;\n        }\n        if (h.is_none()) {\n            value = nullptr;\n            return true;\n        }\n\n        /* Check if this is a capsule */\n        if (isinstance<capsule>(h)) {\n            value = reinterpret_borrow<capsule>(h);\n            return true;\n        }\n\n        /* Check if this is a C++ type */\n        const auto &bases\n            = all_type_info(reinterpret_cast<PyTypeObject *>(type::handle_of(h).ptr()));\n        if (bases.size() == 1) { // Only allowing loading from a single-value type\n            value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();\n            return true;\n        }\n\n        /* Fail */\n        return false;\n    }\n\n    static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {\n        if (ptr) {\n            return capsule(ptr).release();\n        }\n        return none().release();\n    }\n\n    template <typename T>\n    using cast_op_type = void *&;\n    explicit operator void *&() { return value; }\n    static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);\n\nprivate:\n    void *value = nullptr;\n};\n\ntemplate <>\nclass type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};\n\ntemplate <>\nclass type_caster<bool> {\npublic:\n    bool load(handle src, bool convert) {\n        if (!src) {\n            return false;\n        }\n        if (src.ptr() == Py_True) {\n            value = true;\n            return true;\n        }\n        if (src.ptr() == Py_False) {\n            value = false;\n            return true;\n        }\n        if (convert || is_numpy_bool(src)) {\n            // (allow non-implicit conversion for numpy booleans), use strncmp\n            // since NumPy 1.x had an additional trailing underscore.\n\n            Py_ssize_t res = -1;\n            if (src.is_none()) {\n                res = 0; // None is implicitly converted to False\n            }\n#if defined(PYPY_VERSION)\n            // On PyPy, check that \"__bool__\" attr exists\n            else if (hasattr(src, PYBIND11_BOOL_ATTR)) {\n                res = PyObject_IsTrue(src.ptr());\n            }\n#else\n            // Alternate approach for CPython: this does the same as the above, but optimized\n            // using the CPython API so as to avoid an unneeded attribute lookup.\n            else if (auto *tp_as_number = Py_TYPE(src.ptr())->tp_as_number) {\n                if (PYBIND11_NB_BOOL(tp_as_number)) {\n                    res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());\n                }\n            }\n#endif\n            if (res == 0 || res == 1) {\n                value = (res != 0);\n                return true;\n            }\n            PyErr_Clear();\n        }\n        return false;\n    }\n    static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {\n        return handle(src ? Py_True : Py_False).inc_ref();\n    }\n    PYBIND11_TYPE_CASTER(bool, const_name(\"bool\"));\n\nprivate:\n    // Test if an object is a NumPy boolean (without fetching the type).\n    static bool is_numpy_bool(handle object) {\n        const char *type_name = Py_TYPE(object.ptr())->tp_name;\n        // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support\n        return std::strcmp(\"numpy.bool\", type_name) == 0\n               || std::strcmp(\"numpy.bool_\", type_name) == 0;\n    }\n};\n\n// Helper class for UTF-{8,16,32} C++ stl strings:\ntemplate <typename StringType, bool IsView = false>\nstruct string_caster {\n    using CharT = typename StringType::value_type;\n\n    // Simplify life by being able to assume standard char sizes (the standard only guarantees\n    // minimums, but Python requires exact sizes)\n    static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,\n                  \"Unsupported char size != 1\");\n#if defined(PYBIND11_HAS_U8STRING)\n    static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,\n                  \"Unsupported char8_t size != 1\");\n#endif\n    static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,\n                  \"Unsupported char16_t size != 2\");\n    static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,\n                  \"Unsupported char32_t size != 4\");\n    // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)\n    static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,\n                  \"Unsupported wchar_t size != 2/4\");\n    static constexpr size_t UTF_N = 8 * sizeof(CharT);\n\n    bool load(handle src, bool) {\n        handle load_src = src;\n        if (!src) {\n            return false;\n        }\n        if (!PyUnicode_Check(load_src.ptr())) {\n            return load_raw(load_src);\n        }\n\n        // For UTF-8 we avoid the need for a temporary `bytes` object by using\n        // `PyUnicode_AsUTF8AndSize`.\n        if (UTF_N == 8) {\n            Py_ssize_t size = -1;\n            const auto *buffer\n                = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));\n            if (!buffer) {\n                PyErr_Clear();\n                return false;\n            }\n            value = StringType(buffer, static_cast<size_t>(size));\n            return true;\n        }\n\n        auto utfNbytes\n            = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),\n                                                                  UTF_N == 8    ? \"utf-8\"\n                                                                  : UTF_N == 16 ? \"utf-16\"\n                                                                                : \"utf-32\",\n                                                                  nullptr));\n        if (!utfNbytes) {\n            PyErr_Clear();\n            return false;\n        }\n\n        const auto *buffer\n            = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));\n        size_t length = static_cast<size_t>(PYBIND11_BYTES_SIZE(utfNbytes.ptr())) / sizeof(CharT);\n        // Skip BOM for UTF-16/32\n        if (UTF_N > 8) {\n            buffer++;\n            length--;\n        }\n        value = StringType(buffer, length);\n\n        // If we're loading a string_view we need to keep the encoded Python object alive:\n        if (IsView) {\n            loader_life_support::add_patient(utfNbytes);\n        }\n\n        return true;\n    }\n\n    static handle\n    cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {\n        const char *buffer = reinterpret_cast<const char *>(src.data());\n        auto nbytes = ssize_t(src.size() * sizeof(CharT));\n        handle s = decode_utfN(buffer, nbytes);\n        if (!s) {\n            throw error_already_set();\n        }\n        return s;\n    }\n\n    PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));\n\nprivate:\n    static handle decode_utfN(const char *buffer, ssize_t nbytes) {\n#if !defined(PYPY_VERSION)\n        return UTF_N == 8    ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)\n               : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)\n                             : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);\n#else\n        // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as\n        // well), so bypass the whole thing by just passing the encoding as a string value, which\n        // works properly:\n        return PyUnicode_Decode(buffer,\n                                nbytes,\n                                UTF_N == 8    ? \"utf-8\"\n                                : UTF_N == 16 ? \"utf-16\"\n                                              : \"utf-32\",\n                                nullptr);\n#endif\n    }\n\n    // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.\n    // without any encoding/decoding attempt).  For other C++ char sizes this is a no-op.\n    // which supports loading a unicode from a str, doesn't take this path.\n    template <typename C = CharT>\n    bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {\n        if (PYBIND11_BYTES_CHECK(src.ptr())) {\n            // We were passed raw bytes; accept it into a std::string or char*\n            // without any encoding attempt.\n            const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());\n            if (!bytes) {\n                pybind11_fail(\"Unexpected PYBIND11_BYTES_AS_STRING() failure.\");\n            }\n            value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));\n            return true;\n        }\n        if (PyByteArray_Check(src.ptr())) {\n            // We were passed a bytearray; accept it into a std::string or char*\n            // without any encoding attempt.\n            const char *bytearray = PyByteArray_AsString(src.ptr());\n            if (!bytearray) {\n                pybind11_fail(\"Unexpected PyByteArray_AsString() failure.\");\n            }\n            value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));\n            return true;\n        }\n\n        return false;\n    }\n\n    template <typename C = CharT>\n    bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {\n        return false;\n    }\n};\n\ntemplate <typename CharT, class Traits, class Allocator>\nstruct type_caster<std::basic_string<CharT, Traits, Allocator>,\n                   enable_if_t<is_std_char_type<CharT>::value>>\n    : string_caster<std::basic_string<CharT, Traits, Allocator>> {};\n\n#ifdef PYBIND11_HAS_STRING_VIEW\ntemplate <typename CharT, class Traits>\nstruct type_caster<std::basic_string_view<CharT, Traits>,\n                   enable_if_t<is_std_char_type<CharT>::value>>\n    : string_caster<std::basic_string_view<CharT, Traits>, true> {};\n#endif\n\n// Type caster for C-style strings.  We basically use a std::string type caster, but also add the\n// ability to use None as a nullptr char* (which the string caster doesn't allow).\ntemplate <typename CharT>\nstruct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {\n    using StringType = std::basic_string<CharT>;\n    using StringCaster = make_caster<StringType>;\n    StringCaster str_caster;\n    bool none = false;\n    CharT one_char = 0;\n\npublic:\n    bool load(handle src, bool convert) {\n        if (!src) {\n            return false;\n        }\n        if (src.is_none()) {\n            // Defer accepting None to other overloads (if we aren't in convert mode):\n            if (!convert) {\n                return false;\n            }\n            none = true;\n            return true;\n        }\n        return str_caster.load(src, convert);\n    }\n\n    static handle cast(const CharT *src, return_value_policy policy, handle parent) {\n        if (src == nullptr) {\n            return pybind11::none().release();\n        }\n        return StringCaster::cast(StringType(src), policy, parent);\n    }\n\n    static handle cast(CharT src, return_value_policy policy, handle parent) {\n        if (std::is_same<char, CharT>::value) {\n            handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);\n            if (!s) {\n                throw error_already_set();\n            }\n            return s;\n        }\n        return StringCaster::cast(StringType(1, src), policy, parent);\n    }\n\n    explicit operator CharT *() {\n        return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());\n    }\n    explicit operator CharT &() {\n        if (none) {\n            throw value_error(\"Cannot convert None to a character\");\n        }\n\n        auto &value = static_cast<StringType &>(str_caster);\n        size_t str_len = value.size();\n        if (str_len == 0) {\n            throw value_error(\"Cannot convert empty string to a character\");\n        }\n\n        // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that\n        // is too high, and one for multiple unicode characters (caught later), so we need to\n        // figure out how long the first encoded character is in bytes to distinguish between these\n        // two errors.  We also allow want to allow unicode characters U+0080 through U+00FF, as\n        // those can fit into a single char value.\n        if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {\n            auto v0 = static_cast<unsigned char>(value[0]);\n            // low bits only: 0-127\n            // 0b110xxxxx - start of 2-byte sequence\n            // 0b1110xxxx - start of 3-byte sequence\n            // 0b11110xxx - start of 4-byte sequence\n            size_t char0_bytes = (v0 & 0x80) == 0      ? 1\n                                 : (v0 & 0xE0) == 0xC0 ? 2\n                                 : (v0 & 0xF0) == 0xE0 ? 3\n                                                       : 4;\n\n            if (char0_bytes == str_len) {\n                // If we have a 128-255 value, we can decode it into a single char:\n                if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx\n                    one_char = static_cast<CharT>(((v0 & 3) << 6)\n                                                  + (static_cast<unsigned char>(value[1]) & 0x3F));\n                    return one_char;\n                }\n                // Otherwise we have a single character, but it's > U+00FF\n                throw value_error(\"Character code point not in range(0x100)\");\n            }\n        }\n\n        // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a\n        // surrogate pair with total length 2 instantly indicates a range error (but not a \"your\n        // string was too long\" error).\n        else if (StringCaster::UTF_N == 16 && str_len == 2) {\n            one_char = static_cast<CharT>(value[0]);\n            if (one_char >= 0xD800 && one_char < 0xE000) {\n                throw value_error(\"Character code point not in range(0x10000)\");\n            }\n        }\n\n        if (str_len != 1) {\n            throw value_error(\"Expected a character, but multi-character string found\");\n        }\n\n        one_char = value[0];\n        return one_char;\n    }\n\n    static constexpr auto name = const_name(PYBIND11_STRING_NAME);\n    template <typename _T>\n    using cast_op_type = pybind11::detail::cast_op_type<_T>;\n};\n\n// Base implementation for std::tuple and std::pair\ntemplate <template <typename...> class Tuple, typename... Ts>\nclass tuple_caster {\n    using type = Tuple<Ts...>;\n    static constexpr auto size = sizeof...(Ts);\n    using indices = make_index_sequence<size>;\n\npublic:\n    bool load(handle src, bool convert) {\n        if (!isinstance<sequence>(src)) {\n            return false;\n        }\n        const auto seq = reinterpret_borrow<sequence>(src);\n        if (seq.size() != size) {\n            return false;\n        }\n        return load_impl(seq, convert, indices{});\n    }\n\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        return cast_impl(std::forward<T>(src), policy, parent, indices{});\n    }\n\n    // copied from the PYBIND11_TYPE_CASTER macro\n    template <typename T>\n    static handle cast(T *src, return_value_policy policy, handle parent) {\n        if (!src) {\n            return none().release();\n        }\n        if (policy == return_value_policy::take_ownership) {\n            auto h = cast(std::move(*src), policy, parent);\n            delete src;\n            return h;\n        }\n        return cast(*src, policy, parent);\n    }\n\n    static constexpr auto name = const_name(\"tuple[\")\n                                 + ::pybind11::detail::concat(make_caster<Ts>::name...)\n                                 + const_name(\"]\");\n\n    template <typename T>\n    using cast_op_type = type;\n\n    explicit operator type() & { return implicit_cast(indices{}); }\n    explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }\n\nprotected:\n    template <size_t... Is>\n    type implicit_cast(index_sequence<Is...>) & {\n        return type(cast_op<Ts>(std::get<Is>(subcasters))...);\n    }\n    template <size_t... Is>\n    type implicit_cast(index_sequence<Is...>) && {\n        return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);\n    }\n\n    static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }\n\n    template <size_t... Is>\n    bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {\n#ifdef __cpp_fold_expressions\n        if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {\n            return false;\n        }\n#else\n        for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {\n            if (!r) {\n                return false;\n            }\n        }\n#endif\n        return true;\n    }\n\n    /* Implementation: Convert a C++ tuple into a Python tuple */\n    template <typename T, size_t... Is>\n    static handle\n    cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);\n        PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);\n\n        std::array<object, size> entries{{reinterpret_steal<object>(\n            // NOLINTNEXTLINE(bugprone-use-after-move)\n            make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};\n        for (const auto &entry : entries) {\n            if (!entry) {\n                return handle();\n            }\n        }\n        tuple result(size);\n        int counter = 0;\n        for (auto &entry : entries) {\n            PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());\n        }\n        return result.release();\n    }\n\n    Tuple<make_caster<Ts>...> subcasters;\n};\n\ntemplate <typename T1, typename T2>\nclass type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};\n\ntemplate <typename... Ts>\nclass type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};\n\ntemplate <>\nclass type_caster<std::tuple<>> : public tuple_caster<std::tuple> {\npublic:\n    // PEP 484 specifies this syntax for an empty tuple\n    static constexpr auto name = const_name(\"tuple[()]\");\n};\n\n/// Helper class which abstracts away certain actions. Users can provide specializations for\n/// custom holders, but it's only necessary if the type has a non-standard interface.\ntemplate <typename T>\nstruct holder_helper {\n    static auto get(const T &p) -> decltype(p.get()) { return p.get(); }\n};\n\n// SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to shared_ptr specialization.\n/// Type caster for holder types like std::shared_ptr, etc.\n/// The SFINAE hook is provided to help work around the current lack of support\n/// for smart-pointer interoperability. Please consider it an implementation\n/// detail that may change in the future, as formal support for smart-pointer\n/// interoperability is added into pybind11.\ntemplate <typename type, typename holder_type, typename SFINAE = void>\nstruct copyable_holder_caster : public type_caster_base<type> {\npublic:\n    using base = type_caster_base<type>;\n    static_assert(std::is_base_of<base, type_caster<type>>::value,\n                  \"Holder classes are only supported for custom types\");\n    using base::base;\n    using base::cast;\n    using base::typeinfo;\n    using base::value;\n\n    bool load(handle src, bool convert) {\n        return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);\n    }\n\n    explicit operator type *() { return this->value; }\n    // static_cast works around compiler error with MSVC 17 and CUDA 10.2\n    // see issue #2180\n    explicit operator type &() { return *(static_cast<type *>(this->value)); }\n    explicit operator holder_type *() { return std::addressof(holder); }\n    explicit operator holder_type &() { return holder; }\n\n    static handle cast(const holder_type &src, return_value_policy, handle) {\n        const auto *ptr = holder_helper<holder_type>::get(src);\n        return type_caster_base<type>::cast_holder(ptr, &src);\n    }\n\nprotected:\n    friend class type_caster_generic;\n    void check_holder_compat() {\n        // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.\n        bool inst_has_unique_ptr_holder\n            = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);\n        if (inst_has_unique_ptr_holder) {\n            throw cast_error(\"Unable to load a custom holder type from a default-holder instance\");\n        }\n    }\n\n    bool set_foreign_holder(handle src) {\n        return holder_caster_foreign_helpers::set_foreign_holder(src, (type *) value, &holder);\n    }\n\n    void load_value(value_and_holder &&v_h) {\n        if (v_h.holder_constructed()) {\n            value = v_h.value_ptr();\n            holder = v_h.template holder<holder_type>();\n            return;\n        }\n        throw cast_error(\"Unable to cast from non-held to held instance (T& to Holder<T>) \"\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                         \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for \"\n                         \"type information)\");\n#else\n                         \"of type '\"\n                         + type_id<holder_type>() + \"''\");\n#endif\n    }\n\n    template <typename T = holder_type,\n              detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>\n    bool try_implicit_casts(handle, bool) {\n        return false;\n    }\n\n    template <typename T = holder_type,\n              detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>\n    bool try_implicit_casts(handle src, bool convert) {\n        for (auto &cast : typeinfo->implicit_casts) {\n            copyable_holder_caster sub_caster(*cast.first);\n            if (sub_caster.load(src, convert)) {\n                value = cast.second(sub_caster.value);\n                holder = holder_type(sub_caster.holder, (type *) value);\n                return true;\n            }\n        }\n        return false;\n    }\n\n    static bool try_direct_conversions(handle) { return false; }\n\n    holder_type holder;\n};\n\ntemplate <typename, typename SFINAE = void>\nstruct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled : std::true_type {};\n\n// SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor copyable_holder_caster to reduce code duplication.\ntemplate <typename type>\nstruct copyable_holder_caster<\n    type,\n    std::shared_ptr<type>,\n    enable_if_t<copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<type>::value>>\n    : public type_caster_base<type> {\npublic:\n    using base = type_caster_base<type>;\n    static_assert(std::is_base_of<base, type_caster<type>>::value,\n                  \"Holder classes are only supported for custom types\");\n    using base::base;\n    using base::cast;\n    using base::typeinfo;\n    using base::value;\n\n    bool load(handle src, bool convert) {\n        if (base::template load_impl<copyable_holder_caster<type, std::shared_ptr<type>>>(\n                src, convert)) {\n            sh_load_helper.maybe_set_python_instance_is_alias(src);\n            return true;\n        }\n        return false;\n    }\n\n    explicit operator std::shared_ptr<type> *() {\n        if (sh_load_helper.was_populated) {\n            pybind11_fail(\"Passing `std::shared_ptr<T> *` from Python to C++ is not supported \"\n                          \"(inherently unsafe).\");\n        }\n        return std::addressof(shared_ptr_storage);\n    }\n\n    explicit operator std::shared_ptr<type> &() {\n        if (sh_load_helper.was_populated) {\n            shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);\n        }\n        return shared_ptr_storage;\n    }\n\n    std::weak_ptr<type> potentially_slicing_weak_ptr() {\n        if (sh_load_helper.was_populated) {\n            // Reusing shared_ptr code to minimize code complexity.\n            shared_ptr_storage\n                = sh_load_helper.load_as_shared_ptr(typeinfo,\n                                                    value,\n                                                    /*responsible_parent=*/nullptr,\n                                                    /*force_potentially_slicing_shared_ptr=*/true);\n        }\n        return shared_ptr_storage;\n    }\n\n    static handle\n    cast(const std::shared_ptr<type> &src, return_value_policy policy, handle parent) {\n        const auto *ptr = src.get();\n        typename type_caster_base<type>::cast_sources srcs{ptr};\n        if (srcs.creates_smart_holder()) {\n            return smart_holder_type_caster_support::smart_holder_from_shared_ptr(\n                src, policy, parent, srcs.result);\n        }\n        return type_caster_base<type>::cast_holder(srcs, &src);\n    }\n\n    // This function will succeed even if the `responsible_parent` does not own the\n    // wrapped C++ object directly.\n    // It is the responsibility of the caller to ensure that the `responsible_parent`\n    // has a `keep_alive` relationship with the owner of the wrapped C++ object, or\n    // that the wrapped C++ object lives for the duration of the process.\n    static std::shared_ptr<type> shared_ptr_with_responsible_parent(handle responsible_parent) {\n        copyable_holder_caster loader;\n        loader.load(responsible_parent, /*convert=*/false);\n        assert(loader.typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder);\n        return loader.sh_load_helper.load_as_shared_ptr(\n            loader.typeinfo, loader.value, responsible_parent);\n    }\n\nprotected:\n    friend class type_caster_generic;\n    void check_holder_compat() {\n        // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.\n        bool inst_has_unique_ptr_holder\n            = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);\n        if (inst_has_unique_ptr_holder) {\n            throw cast_error(\"Unable to load a custom holder type from a default-holder instance\");\n        }\n    }\n\n    bool set_foreign_holder(handle src) {\n        return holder_caster_foreign_helpers::set_foreign_holder(\n            src, (type *) value, &shared_ptr_storage);\n    }\n\n    void load_value(value_and_holder &&v_h) {\n        if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n            sh_load_helper.loaded_v_h = v_h;\n            sh_load_helper.was_populated = true;\n            value = sh_load_helper.get_void_ptr_or_nullptr();\n            return;\n        }\n        if (v_h.holder_constructed()) {\n            value = v_h.value_ptr();\n            shared_ptr_storage = v_h.template holder<std::shared_ptr<type>>();\n            return;\n        }\n        throw cast_error(\"Unable to cast from non-held to held instance (T& to Holder<T>) \"\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                         \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for \"\n                         \"type information)\");\n#else\n                         \"of type '\"\n                         + type_id<std::shared_ptr<type>>() + \"''\");\n#endif\n    }\n\n    template <typename T = std::shared_ptr<type>,\n              detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>\n    bool try_implicit_casts(handle, bool) {\n        return false;\n    }\n\n    template <typename T = std::shared_ptr<type>,\n              detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>\n    bool try_implicit_casts(handle src, bool convert) {\n        for (auto &cast : typeinfo->implicit_casts) {\n            copyable_holder_caster sub_caster(*cast.first);\n            if (sub_caster.load(src, convert)) {\n                value = cast.second(sub_caster.value);\n                if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n                    sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;\n                    sh_load_helper.was_populated = true;\n                } else {\n                    shared_ptr_storage\n                        = std::shared_ptr<type>(sub_caster.shared_ptr_storage, (type *) value);\n                }\n                return true;\n            }\n        }\n        return false;\n    }\n\n    static bool try_direct_conversions(handle) { return false; }\n\n    smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl\n    std::shared_ptr<type> shared_ptr_storage;\n};\n\n/// Specialize for the common std::shared_ptr, so users don't need to\ntemplate <typename T>\nclass type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Return a std::shared_ptr with the SAME CONTROL BLOCK as the std::shared_ptr owned by the\n/// class_ holder. For class_-wrapped types with trampolines, the returned std::shared_ptr\n/// does NOT keep any derived Python objects alive (see issue #1333).\n///\n/// For class_-wrapped types using std::shared_ptr as the holder, the following expressions\n/// produce equivalent results (see tests/test_potentially_slicing_weak_ptr.cpp,py):\n///\n///     - obj.cast<std::shared_ptr<T>>()\n///     - py::potentially_slicing_weak_ptr<T>(obj).lock()\n///\n/// For class_-wrapped types with trampolines and using py::smart_holder, obj.cast<>()\n/// produces a std::shared_ptr that keeps any derived Python objects alive for its own lifetime,\n/// but this is achieved by introducing a std::shared_ptr control block that is independent of\n/// the one owned by the py::smart_holder. This can lead to surprising std::weak_ptr behavior\n/// (see issue #5623). An easy solution is to use py::potentially_slicing_weak_ptr<>(obj),\n/// as exercised in tests/test_potentially_slicing_weak_ptr.cpp,py (look for\n/// \"set_wp_potentially_slicing\"). Note, however, that this reintroduces the inheritance\n/// slicing issue (see issue #1333). The ideal — but usually more involved — solution is to use\n/// a Python weakref to the derived Python object, instead of a C++ base-class std::weak_ptr.\n///\n/// It is not possible (at least no known approach exists at the time of this writing) to\n/// simultaneously achieve both desirable properties:\n///\n///     - the same std::shared_ptr control block as the class_ holder\n///     - automatic lifetime extension of any derived Python objects\n///\n/// The reason is that this would introduce a reference cycle that cannot be garbage collected:\n///\n///     - the derived Python object owns the class_ holder\n///     - the class_ holder owns the std::shared_ptr\n///     - the std::shared_ptr would own a reference to the derived Python object,\n///       completing the cycle\ntemplate <typename T>\nstd::weak_ptr<T> potentially_slicing_weak_ptr(handle obj) {\n    detail::make_caster<std::shared_ptr<T>> caster;\n    if (caster.load(obj, /*convert=*/true)) {\n        return caster.potentially_slicing_weak_ptr();\n    }\n    const char *obj_type_name = detail::obj_class_name(obj.ptr());\n    throw type_error(\"\\\"\" + std::string(obj_type_name)\n                     + \"\\\" object is not convertible to std::weak_ptr<T> (with T = \" + type_id<T>()\n                     + \")\");\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to unique_ptr specialization.\n/// Type caster for holder types like std::unique_ptr.\n/// Please consider the SFINAE hook an implementation detail, as explained\n/// in the comment for the copyable_holder_caster.\ntemplate <typename type, typename holder_type, typename SFINAE = void>\nstruct move_only_holder_caster {\n    static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,\n                  \"Holder classes are only supported for custom types\");\n\n    static handle cast(holder_type &&src, return_value_policy, handle) {\n        auto *ptr = holder_helper<holder_type>::get(src);\n        return type_caster_base<type>::cast_holder(ptr, std::addressof(src));\n    }\n    static constexpr auto name = type_caster_base<type>::name;\n};\n\ntemplate <typename, typename SFINAE = void>\nstruct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled : std::true_type {};\n\n// SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor move_only_holder_caster to reduce code duplication.\ntemplate <typename type, typename deleter>\nstruct move_only_holder_caster<\n    type,\n    std::unique_ptr<type, deleter>,\n    enable_if_t<move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<type>::value>>\n    : public type_caster_base<type> {\npublic:\n    using base = type_caster_base<type>;\n    static_assert(std::is_base_of<base, type_caster<type>>::value,\n                  \"Holder classes are only supported for custom types\");\n    using base::base;\n    using base::cast;\n    using base::typeinfo;\n    using base::value;\n\n    static handle\n    cast(std::unique_ptr<type, deleter> &&src, return_value_policy policy, handle parent) {\n        auto *ptr = src.get();\n        typename type_caster_base<type>::cast_sources srcs{ptr};\n        if (srcs.creates_smart_holder()) {\n            return smart_holder_type_caster_support::smart_holder_from_unique_ptr(\n                std::move(src), policy, parent, srcs.result);\n        }\n        return type_caster_base<type>::cast_holder(srcs, &src);\n    }\n\n    static handle\n    cast(const std::unique_ptr<type, deleter> &src, return_value_policy policy, handle parent) {\n        if (!src) {\n            return none().release();\n        }\n        if (policy == return_value_policy::automatic) {\n            policy = return_value_policy::reference_internal;\n        }\n        if (policy != return_value_policy::reference_internal) {\n            throw cast_error(\"Invalid return_value_policy for const unique_ptr&\");\n        }\n        return type_caster_base<type>::cast(src.get(), policy, parent);\n    }\n\n    bool load(handle src, bool convert) {\n        if (base::template load_impl<\n                move_only_holder_caster<type, std::unique_ptr<type, deleter>>>(src, convert)) {\n            sh_load_helper.maybe_set_python_instance_is_alias(src);\n            return true;\n        }\n        return false;\n    }\n\n    bool set_foreign_holder(handle) {\n        throw cast_error(\"Foreign instance cannot be converted to std::unique_ptr \"\n                         \"because we don't know how to make it relinquish \"\n                         \"ownership\");\n    }\n\n    void load_value(value_and_holder &&v_h) {\n        if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n            sh_load_helper.loaded_v_h = v_h;\n            sh_load_helper.loaded_v_h.type = typeinfo;\n            sh_load_helper.was_populated = true;\n            value = sh_load_helper.get_void_ptr_or_nullptr();\n            return;\n        }\n        pybind11_fail(\"Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, \"\n                      \"py::smart_holder>` (with T = \"\n                      + clean_type_id(typeinfo->cpptype->name()) + \")\");\n    }\n\n    template <typename T_>\n    using cast_op_type\n        = conditional_t<std::is_same<typename std::remove_volatile<T_>::type,\n                                     const std::unique_ptr<type, deleter> &>::value\n                            || std::is_same<typename std::remove_volatile<T_>::type,\n                                            const std::unique_ptr<const type, deleter> &>::value,\n                        const std::unique_ptr<type, deleter> &,\n                        std::unique_ptr<type, deleter>>;\n\n    explicit operator std::unique_ptr<type, deleter>() {\n        if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n            return sh_load_helper.template load_as_unique_ptr<deleter>(typeinfo, value);\n        }\n        pybind11_fail(\"Expected to be UNREACHABLE: \" __FILE__ \":\" PYBIND11_TOSTRING(__LINE__));\n    }\n\n    explicit operator const std::unique_ptr<type, deleter> &() {\n        if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n            // Get shared_ptr to ensure that the Python object is not disowned elsewhere.\n            shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);\n            // Build a temporary unique_ptr that is meant to never expire.\n            unique_ptr_storage = std::shared_ptr<std::unique_ptr<type, deleter>>(\n                new std::unique_ptr<type, deleter>{\n                    sh_load_helper.template load_as_const_unique_ptr<deleter>(\n                        typeinfo, shared_ptr_storage.get())},\n                [](std::unique_ptr<type, deleter> *ptr) {\n                    if (!ptr) {\n                        pybind11_fail(\"FATAL: `const std::unique_ptr<T, D> &` was disowned \"\n                                      \"(EXPECT UNDEFINED BEHAVIOR).\");\n                    }\n                    (void) ptr->release();\n                    delete ptr;\n                });\n            return *unique_ptr_storage;\n        }\n        pybind11_fail(\"Expected to be UNREACHABLE: \" __FILE__ \":\" PYBIND11_TOSTRING(__LINE__));\n    }\n\n    bool try_implicit_casts(handle src, bool convert) {\n        for (auto &cast : typeinfo->implicit_casts) {\n            move_only_holder_caster sub_caster(*cast.first);\n            if (sub_caster.load(src, convert)) {\n                value = cast.second(sub_caster.value);\n                if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n                    sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;\n                    sh_load_helper.was_populated = true;\n                } else {\n                    pybind11_fail(\"Expected to be UNREACHABLE: \" __FILE__\n                                  \":\" PYBIND11_TOSTRING(__LINE__));\n                }\n                return true;\n            }\n        }\n        return false;\n    }\n\n    static bool try_direct_conversions(handle) { return false; }\n\n    smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl\n    std::shared_ptr<type> shared_ptr_storage; // Serves as a pseudo lock.\n    std::shared_ptr<std::unique_ptr<type, deleter>> unique_ptr_storage;\n};\n\ntemplate <typename type, typename deleter>\nclass type_caster<std::unique_ptr<type, deleter>>\n    : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};\n\ntemplate <typename type, typename holder_type>\nusing type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,\n                                         copyable_holder_caster<type, holder_type>,\n                                         move_only_holder_caster<type, holder_type>>;\n\ntemplate <bool Value = false>\nstruct always_construct_holder_value {\n    static constexpr bool value = Value;\n};\n\ntemplate <typename T, bool Value = false>\nstruct always_construct_holder : always_construct_holder_value<Value> {};\n\n/// Create a specialization for custom holder types (silently ignores std::shared_ptr)\n#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...)                                      \\\n    PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \\\n    namespace detail {                                                                            \\\n    template <typename type>                                                                      \\\n    struct always_construct_holder<holder_type> : always_construct_holder_value<__VA_ARGS__> {};  \\\n    template <typename type>                                                                      \\\n    class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>>               \\\n        : public type_caster_holder<type, holder_type> {};                                        \\\n    }                                                                                             \\\n    PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\n// PYBIND11_DECLARE_HOLDER_TYPE holder types:\ntemplate <typename base, typename holder>\nstruct is_holder_type\n    : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};\n\n// Specializations for always-supported holders:\ntemplate <typename base, typename deleter>\nstruct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};\n\ntemplate <typename base>\nstruct is_holder_type<base, smart_holder> : std::true_type {};\n\n#ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888\n\n// This leads to compilation errors if a specialization is missing.\ntemplate <typename T>\nstruct handle_type_name;\n\n#else\n\ntemplate <typename T>\nstruct handle_type_name {\n    static constexpr auto name = const_name<T>();\n};\n\n#endif\n\ntemplate <>\nstruct handle_type_name<object> {\n    static constexpr auto name = const_name(\"object\");\n};\ntemplate <>\nstruct handle_type_name<list> {\n    static constexpr auto name = const_name(\"list\");\n};\ntemplate <>\nstruct handle_type_name<dict> {\n    static constexpr auto name = const_name(\"dict\");\n};\ntemplate <>\nstruct handle_type_name<anyset> {\n    static constexpr auto name = const_name(\"set | frozenset\");\n};\ntemplate <>\nstruct handle_type_name<set> {\n    static constexpr auto name = const_name(\"set\");\n};\ntemplate <>\nstruct handle_type_name<frozenset> {\n    static constexpr auto name = const_name(\"frozenset\");\n};\ntemplate <>\nstruct handle_type_name<str> {\n    static constexpr auto name = const_name(\"str\");\n};\ntemplate <>\nstruct handle_type_name<tuple> {\n    static constexpr auto name = const_name(\"tuple\");\n};\ntemplate <>\nstruct handle_type_name<bool_> {\n    static constexpr auto name = const_name(\"bool\");\n};\ntemplate <>\nstruct handle_type_name<bytes> {\n    static constexpr auto name = const_name(PYBIND11_BYTES_NAME);\n};\ntemplate <>\nstruct handle_type_name<buffer> {\n    static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);\n};\ntemplate <>\nstruct handle_type_name<int_> {\n    static constexpr auto name = const_name(\"int\");\n};\ntemplate <>\nstruct handle_type_name<iterable> {\n    static constexpr auto name = const_name(\"collections.abc.Iterable\");\n};\ntemplate <>\nstruct handle_type_name<iterator> {\n    static constexpr auto name = const_name(\"collections.abc.Iterator\");\n};\ntemplate <>\nstruct handle_type_name<float_> {\n    static constexpr auto name = const_name(\"float\");\n};\ntemplate <>\nstruct handle_type_name<function> {\n    static constexpr auto name = const_name(\"collections.abc.Callable\");\n};\ntemplate <>\nstruct handle_type_name<handle> {\n    static constexpr auto name = handle_type_name<object>::name;\n};\ntemplate <>\nstruct handle_type_name<none> {\n    static constexpr auto name = const_name(\"None\");\n};\ntemplate <>\nstruct handle_type_name<sequence> {\n    static constexpr auto name = const_name(\"collections.abc.Sequence\");\n};\ntemplate <>\nstruct handle_type_name<bytearray> {\n    static constexpr auto name = const_name(\"bytearray\");\n};\ntemplate <>\nstruct handle_type_name<memoryview> {\n    static constexpr auto name = const_name(\"memoryview\");\n};\ntemplate <>\nstruct handle_type_name<slice> {\n    static constexpr auto name = const_name(\"slice\");\n};\ntemplate <>\nstruct handle_type_name<type> {\n    static constexpr auto name = const_name(\"type\");\n};\ntemplate <>\nstruct handle_type_name<capsule> {\n    static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);\n};\ntemplate <>\nstruct handle_type_name<ellipsis> {\n    static constexpr auto name = const_name(\"ellipsis\");\n};\ntemplate <>\nstruct handle_type_name<weakref> {\n    static constexpr auto name = const_name(\"weakref.ReferenceType\");\n};\n// args/Args/kwargs/KWArgs have name as well as typehint included\ntemplate <>\nstruct handle_type_name<args> {\n    static constexpr auto name = io_name(\"*args\", \"tuple\");\n};\ntemplate <typename T>\nstruct handle_type_name<Args<T>> {\n    static constexpr auto name\n        = io_name(\"*args: \", \"tuple[\") + make_caster<T>::name + io_name(\"\", \", ...]\");\n};\ntemplate <>\nstruct handle_type_name<kwargs> {\n    static constexpr auto name = io_name(\"**kwargs\", \"dict[str, typing.Any]\");\n};\ntemplate <typename T>\nstruct handle_type_name<KWArgs<T>> {\n    static constexpr auto name\n        = io_name(\"**kwargs: \", \"dict[str, \") + make_caster<T>::name + io_name(\"\", \"]\");\n};\ntemplate <>\nstruct handle_type_name<obj_attr_accessor> {\n    static constexpr auto name = const_name<obj_attr_accessor>();\n};\ntemplate <>\nstruct handle_type_name<str_attr_accessor> {\n    static constexpr auto name = const_name<str_attr_accessor>();\n};\ntemplate <>\nstruct handle_type_name<item_accessor> {\n    static constexpr auto name = const_name<item_accessor>();\n};\ntemplate <>\nstruct handle_type_name<sequence_accessor> {\n    static constexpr auto name = const_name<sequence_accessor>();\n};\ntemplate <>\nstruct handle_type_name<list_accessor> {\n    static constexpr auto name = const_name<list_accessor>();\n};\ntemplate <>\nstruct handle_type_name<tuple_accessor> {\n    static constexpr auto name = const_name<tuple_accessor>();\n};\n\ntemplate <typename type>\nstruct pyobject_caster {\n    template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>\n    pyobject_caster() : value() {}\n\n    // `type` may not be default constructible (e.g. frozenset, anyset).  Initializing `value`\n    // to a nil handle is safe since it will only be accessed if `load` succeeds.\n    template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>\n    pyobject_caster() : value(reinterpret_steal<type>(handle())) {}\n\n    template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>\n    bool load(handle src, bool /* convert */) {\n        value = src;\n        return static_cast<bool>(value);\n    }\n\n    template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>\n    bool load(handle src, bool /* convert */) {\n        if (!isinstance<type>(src)) {\n            return false;\n        }\n        value = reinterpret_borrow<type>(src);\n        return true;\n    }\n\n    static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {\n        return src.inc_ref();\n    }\n    PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);\n};\n\ntemplate <typename T>\nclass type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};\n\ntemplate <>\nclass type_caster<float_> : public pyobject_caster<float_> {\npublic:\n    bool load(handle src, bool /* convert */) {\n        if (isinstance<float_>(src)) {\n            value = reinterpret_borrow<float_>(src);\n        } else if (isinstance<int_>(src)) {\n            value = float_(reinterpret_borrow<int_>(src));\n        } else {\n            return false;\n        }\n        return true;\n    }\n};\n\n// Our conditions for enabling moving are quite restrictive:\n// At compile time:\n// - T needs to be a non-const, non-pointer, non-reference type\n// - type_caster<T>::operator T&() must exist\n// - the type must be move constructible (obviously)\n// At run-time:\n// - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it\n//   must have ref_count() == 1)h\n// If any of the above are not satisfied, we fall back to copying.\ntemplate <typename T>\nusing move_is_plain_type\n    = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;\ntemplate <typename T, typename SFINAE = void>\nstruct move_always : std::false_type {};\ntemplate <typename T>\nstruct move_always<\n    T,\n    enable_if_t<\n        all_of<move_is_plain_type<T>,\n               negation<is_copy_constructible<T>>,\n               is_move_constructible<T>,\n               std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>\n    : std::true_type {};\ntemplate <typename T, typename SFINAE = void>\nstruct move_if_unreferenced : std::false_type {};\ntemplate <typename T>\nstruct move_if_unreferenced<\n    T,\n    enable_if_t<\n        all_of<move_is_plain_type<T>,\n               negation<move_always<T>>,\n               is_move_constructible<T>,\n               std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>\n    : std::true_type {};\ntemplate <typename T>\nusing move_never = none_of<move_always<T>, move_if_unreferenced<T>>;\n\n// Detect whether returning a `type` from a cast on type's type_caster is going to result in a\n// reference or pointer to a local variable of the type_caster.  Basically, only\n// non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;\n// everything else returns a reference/pointer to a local variable.\ntemplate <typename type>\nusing cast_is_temporary_value_reference\n    = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)\n                    && !std::is_base_of<type_caster_generic, make_caster<type>>::value\n                    && !std::is_same<intrinsic_t<type>, void>::value>;\n\n// When a value returned from a C++ function is being cast back to Python, we almost always want to\n// force `policy = move`, regardless of the return value policy the function/method was declared\n// with.\ntemplate <typename Return, typename SFINAE = void>\nstruct return_value_policy_override {\n    static return_value_policy policy(return_value_policy p) { return p; }\n};\n\ntemplate <typename Return>\nstruct return_value_policy_override<\n    Return,\n    detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {\n    static return_value_policy policy(return_value_policy p) {\n        return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value\n                   ? return_value_policy::move\n                   : p;\n    }\n};\n\n// Basic python -> C++ casting; throws if casting fails\ntemplate <typename T, typename SFINAE>\ntype_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {\n    static_assert(!detail::is_pyobject<T>::value,\n                  \"Internal error: type_caster should only be used for C++ types\");\n    if (!conv.load(handle, true)) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n        throw cast_error(\n            \"Unable to cast Python instance of type \"\n            + str(type::handle_of(handle)).cast<std::string>()\n            + \" to C++ type '?' (#define \"\n              \"PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\");\n#else\n        throw cast_error(\"Unable to cast Python instance of type \"\n                         + str(type::handle_of(handle)).cast<std::string>() + \" to C++ type '\"\n                         + type_id<T>() + \"'\");\n#endif\n    }\n    return conv;\n}\n// Wrapper around the above that also constructs and returns a type_caster\ntemplate <typename T>\nmake_caster<T> load_type(const handle &handle) {\n    make_caster<T> conv;\n    load_type(conv, handle);\n    return conv;\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n// pytype -> C++ type\ntemplate <typename T,\n          detail::enable_if_t<!detail::is_pyobject<T>::value\n                                  && !detail::is_same_ignoring_cvref<T, PyObject *>::value,\n                              int>\n          = 0>\nT cast(const handle &handle) {\n    using namespace detail;\n    constexpr bool is_enum_cast = type_uses_type_caster_enum_type<intrinsic_t<T>>::value;\n    static_assert(!cast_is_temporary_value_reference<T>::value || is_enum_cast,\n                  \"Unable to cast type to reference: value is local to type caster\");\n#ifndef NDEBUG\n    if (is_enum_cast && cast_is_temporary_value_reference<T>::value) {\n        if (detail::global_internals_native_enum_type_map_contains(\n                std::type_index(typeid(intrinsic_t<T>)))) {\n            pybind11_fail(\"Unable to cast native enum type to reference\");\n        }\n    }\n#endif\n    return cast_op<T>(load_type<T>(handle));\n}\n\n// pytype -> pytype (calls converting constructor)\ntemplate <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>\nT cast(const handle &handle) {\n    return T(reinterpret_borrow<object>(handle));\n}\n\n// Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.\n// This is necessary for the case that `obj` is a temporary, and could\n// not possibly be different, given\n// 1. the established convention that the passed `handle` is borrowed, and\n// 2. we don't want to force all generic code using `cast<T>()` to special-case\n//    handling of `T` = `PyObject *` (to increment the reference count there).\n// It is the responsibility of the caller to ensure that the reference count\n// is decremented.\ntemplate <typename T,\n          typename Handle,\n          detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value\n                                  && detail::is_same_ignoring_cvref<Handle, handle>::value,\n                              int>\n          = 0>\nT cast(Handle &&handle) {\n    return handle.inc_ref().ptr();\n}\n// To optimize way an inc_ref/dec_ref cycle:\ntemplate <typename T,\n          typename Object,\n          detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value\n                                  && detail::is_same_ignoring_cvref<Object, object>::value,\n                              int>\n          = 0>\nT cast(Object &&obj) {\n    return obj.release().ptr();\n}\n\n// C++ type -> py::object\ntemplate <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>\nobject cast(T &&value,\n            return_value_policy policy = return_value_policy::automatic_reference,\n            handle parent = handle()) {\n    using no_ref_T = typename std::remove_reference<T>::type;\n    if (policy == return_value_policy::automatic) {\n        policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::take_ownership\n                 : std::is_lvalue_reference<T>::value ? return_value_policy::copy\n                                                      : return_value_policy::move;\n    } else if (policy == return_value_policy::automatic_reference) {\n        policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::reference\n                 : std::is_lvalue_reference<T>::value ? return_value_policy::copy\n                                                      : return_value_policy::move;\n    }\n    return reinterpret_steal<object>(\n        detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));\n}\n\ntemplate <typename T>\nT handle::cast() const {\n    return pybind11::cast<T>(*this);\n}\ntemplate <>\ninline void handle::cast() const {\n    return;\n}\n\ntemplate <typename T>\ndetail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {\n    if (obj.ref_count() > 1) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n        throw cast_error(\n            \"Unable to cast Python \" + str(type::handle_of(obj)).cast<std::string>()\n            + \" instance to C++ rvalue: instance has multiple references\"\n              \" (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\");\n#else\n        throw cast_error(\"Unable to move from Python \"\n                         + str(type::handle_of(obj)).cast<std::string>() + \" instance to C++ \"\n                         + type_id<T>() + \" instance: instance has multiple references\");\n#endif\n    }\n\n    // Move into a temporary and return that, because the reference may be a local value of `conv`\n    T ret = std::move(detail::load_type<T>(obj).operator T &());\n    return ret;\n}\n\n// Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:\n// - If we have to move (because T has no copy constructor), do it.  This will fail if the moved\n//   object has multiple references, but trying to copy will fail to compile.\n// - If both movable and copyable, check ref count: if 1, move; otherwise copy\n// - Otherwise (not movable), copy.\ntemplate <typename T>\ndetail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>\ncast(object &&object) {\n    return move<T>(std::move(object));\n}\ntemplate <typename T>\ndetail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>\ncast(object &&object) {\n    if (object.ref_count() > 1) {\n        return cast<T>(object);\n    }\n    return move<T>(std::move(object));\n}\ntemplate <typename T>\ndetail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>\ncast(object &&object) {\n    return cast<T>(object);\n}\n\n// pytype rvalue -> pytype (calls converting constructor)\ntemplate <typename T>\ndetail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {\n    return T(std::move(object));\n}\n\ntemplate <typename T>\nT object::cast() const & {\n    return pybind11::cast<T>(*this);\n}\ntemplate <typename T>\nT object::cast() && {\n    return pybind11::cast<T>(std::move(*this));\n}\ntemplate <>\ninline void object::cast() const & {\n    return;\n}\ntemplate <>\ninline void object::cast() && {\n    return;\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// forward declaration (definition in pybind11.h)\ntemplate <typename T>\nstd::string generate_type_signature();\n\n// Declared in pytypes.h:\ntemplate <typename T, enable_if_t<!is_pyobject<T>::value, int>>\nobject object_or_cast(T &&o) {\n    return pybind11::cast(std::forward<T>(o));\n}\n\n// Declared in pytypes.h:\n// Implemented here so that make_caster<T> can be used.\ntemplate <typename D>\ntemplate <typename T>\nstr_attr_accessor object_api<D>::attr_with_type_hint(const char *key) const {\n#if !defined(__cpp_inline_variables)\n    static_assert(always_false<T>::value,\n                  \"C++17 feature __cpp_inline_variables not available: \"\n                  \"https://en.cppreference.com/w/cpp/language/static#Static_data_members\");\n#endif\n    object ann = annotations();\n    if (ann.contains(key)) {\n        throw std::runtime_error(\"__annotations__[\\\"\" + std::string(key) + \"\\\"] was set already.\");\n    }\n\n    ann[key] = generate_type_signature<T>();\n    return {derived(), key};\n}\n\ntemplate <typename D>\ntemplate <typename T>\nobj_attr_accessor object_api<D>::attr_with_type_hint(handle key) const {\n    (void) attr_with_type_hint<T>(key.cast<std::string>().c_str());\n    return {derived(), reinterpret_borrow<object>(key)};\n}\n\n// Placeholder type for the unneeded (and dead code) static variable in the\n// PYBIND11_OVERRIDE_OVERRIDE macro\nstruct override_unused {};\ntemplate <typename ret_type>\nusing override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,\n                                        make_caster<ret_type>,\n                                        override_unused>;\n\n// Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then\n// store the result in the given variable.  For other types, this is a no-op.\ntemplate <typename T>\nenable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,\n                                                                     make_caster<T> &caster) {\n    return cast_op<T>(load_type(caster, o));\n}\ntemplate <typename T>\nenable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,\n                                                                      override_unused &) {\n    pybind11_fail(\"Internal error: cast_ref fallback invoked\");\n}\n\n// Trampoline use: Having a pybind11::cast with an invalid reference type is going to\n// static_assert, even though if it's in dead code, so we provide a \"trampoline\" to pybind11::cast\n// that only does anything in cases where pybind11::cast is valid.\ntemplate <typename T>\nenable_if_t<cast_is_temporary_value_reference<T>::value\n                && !detail::is_same_ignoring_cvref<T, PyObject *>::value,\n            T>\ncast_safe(object &&) {\n    pybind11_fail(\"Internal error: cast_safe fallback invoked\");\n}\ntemplate <typename T>\nenable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}\ntemplate <typename T>\nenable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>\ncast_safe(object &&o) {\n    return o.release().ptr();\n}\ntemplate <typename T>\nenable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,\n                            detail::is_same_ignoring_cvref<T, PyObject *>,\n                            std::is_void<T>>::value,\n            T>\ncast_safe(object &&o) {\n    return pybind11::cast<T>(std::move(o));\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n// The overloads could coexist, i.e. the #if is not strictly speaking needed,\n// but it is an easy minor optimization.\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\ninline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {\n    return cast_error(\"Unable to convert call argument '\" + name\n                      + \"' to Python object (#define \"\n                        \"PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\");\n}\n#else\ninline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,\n                                                        const std::string &type) {\n    return cast_error(\"Unable to convert call argument '\" + name + \"' of type '\" + type\n                      + \"' to Python object\");\n}\n#endif\n\nnamespace typing {\ntemplate <typename... Types>\nclass Tuple : public tuple {\n    using tuple::tuple;\n};\n} // namespace typing\n\ntemplate <return_value_policy policy = return_value_policy::automatic_reference>\ntyping::Tuple<> make_tuple() {\n    return tuple(0);\n}\n\ntemplate <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>\ntyping::Tuple<Args...> make_tuple(Args &&...args_) {\n    constexpr size_t size = sizeof...(Args);\n    std::array<object, size> args{{reinterpret_steal<object>(\n        detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};\n    for (size_t i = 0; i < args.size(); i++) {\n        if (!args[i]) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            throw cast_error_unable_to_convert_call_arg(std::to_string(i));\n#else\n            std::array<std::string, size> argtypes{{type_id<Args>()...}};\n            throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);\n#endif\n        }\n    }\n    tuple result(size);\n    int counter = 0;\n    for (auto &arg_value : args) {\n        PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());\n    }\n    PYBIND11_WARNING_PUSH\n#ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING\n    PYBIND11_WARNING_DISABLE_CLANG(\"-Wreturn-std-move\")\n#endif\n    return result;\n    PYBIND11_WARNING_POP\n}\n\n/// \\ingroup annotations\n/// Annotation for arguments\nstruct arg {\n    /// Constructs an argument with the name of the argument; if null or omitted, this is a\n    /// positional argument.\n    constexpr explicit arg(const char *name = nullptr)\n        : name(name), flag_noconvert(false), flag_none(true) {}\n    /// Assign a value to this argument\n    template <typename T>\n    arg_v operator=(T &&value) const;\n    /// Indicate that the type should not be converted in the type caster\n    arg &noconvert(bool flag = true) {\n        flag_noconvert = flag;\n        return *this;\n    }\n    /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)\n    arg &none(bool flag = true) {\n        flag_none = flag;\n        return *this;\n    }\n\n    const char *name;        ///< If non-null, this is a named kwargs argument\n    bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type\n                             ///< caster!)\n    bool flag_none : 1;      ///< If set (the default), allow None to be passed to this argument\n};\n\n/// \\ingroup annotations\n/// Annotation for arguments with values\nstruct arg_v : arg {\nprivate:\n    template <typename T>\n    arg_v(arg &&base, T &&x, const char *descr = nullptr)\n        : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(\n                         std::forward<T>(x), return_value_policy::automatic, {}))),\n          descr(descr)\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n          ,\n          type(type_id<T>())\n#endif\n    {\n        // Workaround! See:\n        // https://github.com/pybind/pybind11/issues/2336\n        // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700\n        if (PyErr_Occurred()) {\n            PyErr_Clear();\n        }\n    }\n\npublic:\n    /// Direct construction with name, default, and description\n    template <typename T>\n    arg_v(const char *name, T &&x, const char *descr = nullptr)\n        : arg_v(arg(name), std::forward<T>(x), descr) {}\n\n    /// Called internally when invoking `py::arg(\"a\") = value`\n    template <typename T>\n    arg_v(const arg &base, T &&x, const char *descr = nullptr)\n        : arg_v(arg(base), std::forward<T>(x), descr) {}\n\n    /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&\n    arg_v &noconvert(bool flag = true) {\n        arg::noconvert(flag);\n        return *this;\n    }\n\n    /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&\n    arg_v &none(bool flag = true) {\n        arg::none(flag);\n        return *this;\n    }\n\n    /// The default value\n    object value;\n    /// The (optional) description of the default value\n    const char *descr;\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n    /// The C++ type name of the default value (only available when compiled in debug mode)\n    std::string type;\n#endif\n};\n\n/// \\ingroup annotations\n/// Annotation indicating that all following arguments are keyword-only; the is the equivalent of\n/// an unnamed '*' argument\nstruct kw_only {};\n\n/// \\ingroup annotations\n/// Annotation indicating that all previous arguments are positional-only; the is the equivalent of\n/// an unnamed '/' argument\nstruct pos_only {};\n\ntemplate <typename T>\narg_v arg::operator=(T &&value) const {\n    return {*this, std::forward<T>(value)};\n}\n\n/// Alias for backward compatibility -- to be removed in version 2.0\ntemplate <typename /*unused*/>\nusing arg_t = arg_v;\n\ninline namespace literals {\n/** \\rst\n    String literal version of `arg`\n \\endrst */\nconstexpr arg\n#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5\noperator\"\" _a // gcc 4.8.5 insists on having a space (hard error).\n#else\noperator\"\"_a // clang 17 generates a deprecation warning if there is a space.\n#endif\n    (const char *name, size_t) {\n    return arg(name);\n}\n} // namespace literals\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename T>\nusing is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;\ntemplate <typename T>\nusing is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;\n\n// forward declaration (definition in attr.h)\nstruct function_record;\n\n/// Inline size chosen mostly arbitrarily.\nconstexpr std::size_t arg_vector_small_size = 6;\n\n/// Internal data associated with a single function call\nstruct function_call {\n    function_call(const function_record &f, handle p); // Implementation in attr.h\n\n    /// The function data:\n    const function_record &func;\n\n    /// Arguments passed to the function:\n    argument_vector<arg_vector_small_size> args;\n\n    /// The `convert` value the arguments should be loaded with\n    args_convert_vector<arg_vector_small_size> args_convert;\n\n    /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if\n    /// present, are also in `args` but without a reference).\n    object args_ref, kwargs_ref;\n\n    /// The parent, if any\n    handle parent;\n\n    /// If this is a call to an initializer, this argument contains `self`\n    handle init_self;\n};\n\n// See PR #5396 for the discussion that led to this\ntemplate <typename Base, typename Derived, typename = void>\nstruct is_same_or_base_of : std::is_same<Base, Derived> {};\n\n// Only evaluate is_base_of if Derived is complete.\n// is_base_of raises a compiler error if Derived is incomplete.\ntemplate <typename Base, typename Derived>\nstruct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>\n    : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};\n\n/// Helper class which loads arguments for C++ functions called from Python\ntemplate <typename... Args>\nclass argument_loader {\n    using indices = make_index_sequence<sizeof...(Args)>;\n    template <typename Arg>\n    using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;\n    template <typename Arg>\n    using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;\n    // Get kwargs argument position, or -1 if not present:\n    static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();\n\n    static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,\n                  \"py::kwargs is only permitted as the last argument of a function\");\n\npublic:\n    static constexpr bool has_kwargs = kwargs_pos != -1;\n\n    // py::args argument position; -1 if not present.\n    static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();\n\n    static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),\n                  \"py::args cannot be specified more than once\");\n\n    static constexpr auto arg_names\n        = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);\n\n    bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }\n\n    template <typename Return, typename Guard, typename Func>\n    // NOLINTNEXTLINE(readability-const-return-type)\n    enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {\n        return std::move(*this).template call_impl<remove_cv_t<Return>>(\n            std::forward<Func>(f), indices{}, Guard{});\n    }\n\n    template <typename Return, typename Guard, typename Func>\n    enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {\n        std::move(*this).template call_impl<remove_cv_t<Return>>(\n            std::forward<Func>(f), indices{}, Guard{});\n        return void_type();\n    }\n\nprivate:\n    static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }\n\n    template <size_t... Is>\n    bool load_impl_sequence(function_call &call, index_sequence<Is...>) {\n        PYBIND11_WARNING_PUSH\n#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 13\n        // Work around a GCC -Warray-bounds false positive in argument_vector usage.\n        PYBIND11_WARNING_DISABLE_GCC(\"-Warray-bounds\")\n#endif\n#ifdef __cpp_fold_expressions\n        if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {\n            return false;\n        }\n#else\n        for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {\n            if (!r) {\n                return false;\n            }\n        }\n#endif\n        PYBIND11_WARNING_POP\n        return true;\n    }\n\n    template <typename Return, typename Func, size_t... Is, typename Guard>\n    Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {\n        return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);\n    }\n\n    std::tuple<make_caster<Args>...> argcasters;\n};\n\n// [workaround(intel)] Separate function required here\n// We need to put this into a separate function because the Intel compiler\n// fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>\n// (tested with ICC 2021.1 Beta 20200827).\ntemplate <typename... Args>\nconstexpr bool args_has_keyword_or_ds() {\n    return any_of<is_keyword_or_ds<Args>...>::value;\n}\n\n/// Helper class which collects positional, keyword, * and ** arguments for a Python function call\ntemplate <return_value_policy policy>\nclass unpacking_collector {\npublic:\n    template <typename... Ts>\n    explicit unpacking_collector(Ts &&...values)\n        : m_names(reinterpret_steal<tuple>(\n              handle())) // initialize to null to avoid useless allocation of 0-length tuple\n    {\n        /*\n        Python can sometimes utilize an extra space before the arguments to prepend `self`.\n        This is important enough that there is a special flag for it:\n        PY_VECTORCALL_ARGUMENTS_OFFSET.\n        All we have to do is allocate an extra space at the beginning of this array, and set the\n        flag. Note that the extra space is not passed directly in to vectorcall.\n        */\n        m_args.reserve(sizeof...(values) + 1);\n        m_args.push_back_null();\n\n        if (args_has_keyword_or_ds<Ts...>()) {\n            list names_list;\n\n            // collect_arguments guarantees this can't be constructed with kwargs before the last\n            // positional so we don't need to worry about Ts... being in anything but normal python\n            // order.\n            using expander = int[];\n            (void) expander{0, (process(names_list, std::forward<Ts>(values)), 0)...};\n\n            m_names = reinterpret_steal<tuple>(PyList_AsTuple(names_list.ptr()));\n        } else {\n            auto not_used\n                = reinterpret_steal<list>(handle()); // initialize as null (to avoid an allocation)\n\n            using expander = int[];\n            (void) expander{0, (process(not_used, std::forward<Ts>(values)), 0)...};\n        }\n    }\n\n    /// Call a Python function and pass the collected arguments\n    object call(PyObject *ptr) const {\n        size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)\n        if (m_names) {\n            nargs -= m_names.size();\n        }\n        PyObject *result = _PyObject_Vectorcall(\n            ptr, m_args.data() + 1, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, m_names.ptr());\n        if (!result) {\n            throw error_already_set();\n        }\n        return reinterpret_steal<object>(result);\n    }\n\n    tuple args() const {\n        size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)\n        if (m_names) {\n            nargs -= m_names.size();\n        }\n        tuple val(nargs);\n        for (size_t i = 0; i < nargs; ++i) {\n            // +1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)\n            val[i] = reinterpret_borrow<object>(m_args[i + 1]);\n        }\n        return val;\n    }\n\n    dict kwargs() const {\n        dict val;\n        if (m_names) {\n            size_t offset = m_args.size() - m_names.size();\n            for (size_t i = 0; i < m_names.size(); ++i, ++offset) {\n                val[m_names[i]] = reinterpret_borrow<object>(m_args[offset]);\n            }\n        }\n        return val;\n    }\n\nprivate:\n    // normal argument, possibly needing conversion\n    template <typename T>\n    void process(list & /*names_list*/, T &&x) {\n        handle h = detail::make_caster<T>::cast(std::forward<T>(x), policy, {});\n        if (!h) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1));\n#else\n            throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1),\n                                                        type_id<T>());\n#endif\n        }\n        m_args.push_back_steal(h.ptr()); // cast returns a new reference\n    }\n\n    // * unpacking\n    void process(list & /*names_list*/, detail::args_proxy ap) {\n        if (!ap) {\n            return;\n        }\n        for (auto a : ap) {\n            m_args.push_back_borrow(a.ptr());\n        }\n    }\n\n    // named argument\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    void process(list &names_list, arg_v a) {\n        assert(names_list);\n        if (!a.name) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            nameless_argument_error();\n#else\n            nameless_argument_error(a.type);\n#endif\n        }\n        auto name = str(a.name);\n        if (names_list.contains(name)) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            multiple_values_error();\n#else\n            multiple_values_error(a.name);\n#endif\n        }\n        if (!a.value) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            throw cast_error_unable_to_convert_call_arg(a.name);\n#else\n            throw cast_error_unable_to_convert_call_arg(a.name, a.type);\n#endif\n        }\n        names_list.append(std::move(name));\n        m_args.push_back_borrow(a.value.ptr());\n    }\n\n    // ** unpacking\n    void process(list &names_list, detail::kwargs_proxy kp) {\n        if (!kp) {\n            return;\n        }\n        assert(names_list);\n        for (auto &&k : reinterpret_borrow<dict>(kp)) {\n            auto name = str(k.first);\n            if (names_list.contains(name)) {\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                multiple_values_error();\n#else\n                multiple_values_error(name);\n#endif\n            }\n            names_list.append(std::move(name));\n            m_args.push_back_borrow(k.second.ptr());\n        }\n    }\n\n    [[noreturn]] static void nameless_argument_error() {\n        throw type_error(\n            \"Got kwargs without a name; only named arguments \"\n            \"may be passed via py::arg() to a python function call. \"\n            \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\");\n    }\n    [[noreturn]] static void nameless_argument_error(const std::string &type) {\n        throw type_error(\"Got kwargs without a name of type '\" + type\n                         + \"'; only named \"\n                           \"arguments may be passed via py::arg() to a python function call. \");\n    }\n    [[noreturn]] static void multiple_values_error() {\n        throw type_error(\n            \"Got multiple values for keyword argument \"\n            \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\");\n    }\n\n    [[noreturn]] static void multiple_values_error(const std::string &name) {\n        throw type_error(\"Got multiple values for keyword argument '\" + name + \"'\");\n    }\n\nprivate:\n    ref_small_vector<arg_vector_small_size> m_args;\n    tuple m_names;\n};\n\n/// Collect all arguments, including keywords and unpacking\ntemplate <return_value_policy policy, typename... Args>\nunpacking_collector<policy> collect_arguments(Args &&...args) {\n    // Following argument order rules for generalized unpacking according to PEP 448\n    static_assert(\n        constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>(),\n        \"Invalid function call: positional args must precede keywords and */** unpacking;\");\n    static_assert(constexpr_last<is_s_unpacking, Args...>()\n                      < constexpr_first<is_ds_unpacking, Args...>(),\n                  \"Invalid function call: * unpacking must precede ** unpacking\");\n    return unpacking_collector<policy>(std::forward<Args>(args)...);\n}\n\ntemplate <typename Derived>\ntemplate <return_value_policy policy, typename... Args>\nobject object_api<Derived>::operator()(Args &&...args) const {\n#ifndef NDEBUG\n    if (!PyGILState_Check()) {\n        pybind11_fail(\"pybind11::object_api<>::operator() PyGILState_Check() failure.\");\n    }\n#endif\n    return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());\n}\n\ntemplate <typename Derived>\ntemplate <return_value_policy policy, typename... Args>\nobject object_api<Derived>::call(Args &&...args) const {\n    return operator()<policy>(std::forward<Args>(args)...);\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename T>\nhandle type::handle_of() {\n    static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,\n                  \"py::type::of<T> only supports the case where T is a registered C++ types.\");\n\n    return detail::get_type_handle(typeid(T), true);\n}\n\n#define PYBIND11_MAKE_OPAQUE(...)                                                                 \\\n    PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \\\n    namespace detail {                                                                            \\\n    template <>                                                                                   \\\n    class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {};                     \\\n    }                                                                                             \\\n    PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\n/// Lets you pass a type containing a `,` through a macro parameter without needing a separate\n/// typedef, e.g.:\n/// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`\n#define PYBIND11_TYPE(...) __VA_ARGS__\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/chrono.h",
    "content": "/*\n    pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime\n\n    Copyright (c) 2016 Trent Houliston <trent@houliston.me> and\n                       Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\n#include <chrono>\n#include <cmath>\n#include <ctime>\n#include <datetime.h>\n#include <mutex>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename type>\nclass duration_caster {\npublic:\n    using rep = typename type::rep;\n    using period = typename type::period;\n\n    // signed 25 bits required by the standard.\n    using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;\n\n    bool load(handle src, bool) {\n        using namespace std::chrono;\n\n        // Lazy initialise the PyDateTime import\n        if (!PyDateTimeAPI) {\n            PyDateTime_IMPORT;\n        }\n\n        if (!src) {\n            return false;\n        }\n        // If invoked with datetime.delta object\n        if (PyDelta_Check(src.ptr())) {\n            value = type(duration_cast<duration<rep, period>>(\n                days(PyDateTime_DELTA_GET_DAYS(src.ptr()))\n                + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))\n                + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));\n            return true;\n        }\n        // If invoked with a float we assume it is seconds and convert\n        if (PyFloat_Check(src.ptr())) {\n            value = type(duration_cast<duration<rep, period>>(\n                duration<double>(PyFloat_AsDouble(src.ptr()))));\n            return true;\n        }\n        return false;\n    }\n\n    // If this is a duration just return it back\n    static const std::chrono::duration<rep, period> &\n    get_duration(const std::chrono::duration<rep, period> &src) {\n        return src;\n    }\n    static const std::chrono::duration<rep, period> &\n    get_duration(const std::chrono::duration<rep, period> &&)\n        = delete;\n\n    // If this is a time_point get the time_since_epoch\n    template <typename Clock>\n    static std::chrono::duration<rep, period>\n    get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {\n        return src.time_since_epoch();\n    }\n\n    static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {\n        using namespace std::chrono;\n\n        // Use overloaded function to get our duration from our source\n        // Works out if it is a duration or time_point and get the duration\n        auto d = get_duration(src);\n\n        // Lazy initialise the PyDateTime import\n        if (!PyDateTimeAPI) {\n            PyDateTime_IMPORT;\n        }\n\n        // Declare these special duration types so the conversions happen with the correct\n        // primitive types (int)\n        using dd_t = duration<int, std::ratio<86400>>;\n        using ss_t = duration<int, std::ratio<1>>;\n        using us_t = duration<int, std::micro>;\n\n        auto dd = duration_cast<dd_t>(d);\n        auto subd = d - dd;\n        auto ss = duration_cast<ss_t>(subd);\n        auto us = duration_cast<us_t>(subd - ss);\n        return PyDelta_FromDSU(dd.count(), ss.count(), us.count());\n    }\n\n    PYBIND11_TYPE_CASTER(type, const_name(\"datetime.timedelta\"));\n};\n\ninline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {\n#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)\n    if (localtime_s(buf, time))\n        return nullptr;\n    return buf;\n#else\n    static std::mutex mtx;\n    std::lock_guard<std::mutex> lock(mtx);\n    std::tm *tm_ptr = std::localtime(time);\n    if (tm_ptr != nullptr) {\n        *buf = *tm_ptr;\n    }\n    return tm_ptr;\n#endif\n}\n\n// This is for casting times on the system clock into datetime.datetime instances\ntemplate <typename Duration>\nclass type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {\npublic:\n    using type = std::chrono::time_point<std::chrono::system_clock, Duration>;\n    bool load(handle src, bool) {\n        using namespace std::chrono;\n\n        // Lazy initialise the PyDateTime import\n        if (!PyDateTimeAPI) {\n            PyDateTime_IMPORT;\n        }\n\n        if (!src) {\n            return false;\n        }\n\n        std::tm cal;\n        microseconds msecs;\n\n        if (PyDateTime_Check(src.ptr())) {\n            cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());\n            cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());\n            cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());\n            cal.tm_mday = PyDateTime_GET_DAY(src.ptr());\n            cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;\n            cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;\n            cal.tm_isdst = -1;\n            msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));\n        } else if (PyDate_Check(src.ptr())) {\n            cal.tm_sec = 0;\n            cal.tm_min = 0;\n            cal.tm_hour = 0;\n            cal.tm_mday = PyDateTime_GET_DAY(src.ptr());\n            cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;\n            cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;\n            cal.tm_isdst = -1;\n            msecs = microseconds(0);\n        } else if (PyTime_Check(src.ptr())) {\n            cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());\n            cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());\n            cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());\n            cal.tm_mday = 1;  // This date (day, month, year) = (1, 0, 70)\n            cal.tm_mon = 0;   // represents 1-Jan-1970, which is the first\n            cal.tm_year = 70; // earliest available date for Python's datetime\n            cal.tm_isdst = -1;\n            msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));\n        } else {\n            return false;\n        }\n\n        value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);\n        return true;\n    }\n\n    static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,\n                       return_value_policy /* policy */,\n                       handle /* parent */) {\n        using namespace std::chrono;\n\n        // Lazy initialise the PyDateTime import\n        if (!PyDateTimeAPI) {\n            PyDateTime_IMPORT;\n        }\n\n        // Get out microseconds, and make sure they are positive, to avoid bug in eastern\n        // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)\n        using us_t = duration<int, std::micro>;\n        auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));\n        if (us.count() < 0) {\n            us += duration_cast<us_t>(seconds(1));\n        }\n\n        // Subtract microseconds BEFORE `system_clock::to_time_t`, because:\n        // > If std::time_t has lower precision, it is implementation-defined whether the value is\n        // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)\n        std::time_t tt\n            = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));\n\n        std::tm localtime;\n        std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);\n        if (!localtime_ptr) {\n            throw cast_error(\"Unable to represent system_clock in local time\");\n        }\n        return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,\n                                          localtime.tm_mon + 1,\n                                          localtime.tm_mday,\n                                          localtime.tm_hour,\n                                          localtime.tm_min,\n                                          localtime.tm_sec,\n                                          us.count());\n    }\n    PYBIND11_TYPE_CASTER(type, const_name(\"datetime.datetime\"));\n};\n\n// Other clocks that are not the system clock are not measured as datetime.datetime objects\n// since they are not measured on calendar time. So instead we just make them timedeltas\n// Or if they have passed us a time as a float we convert that\ntemplate <typename Clock, typename Duration>\nclass type_caster<std::chrono::time_point<Clock, Duration>>\n    : public duration_caster<std::chrono::time_point<Clock, Duration>> {};\n\ntemplate <typename Rep, typename Period>\nclass type_caster<std::chrono::duration<Rep, Period>>\n    : public duration_caster<std::chrono::duration<Rep, Period>> {};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/common.h",
    "content": "#include \"detail/common.h\"\n#warning \"Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'.\"\n"
  },
  {
    "path": "include/pybind11/complex.h",
    "content": "/*\n    pybind11/complex.h: Complex number support\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\n#include <complex>\n\n/// glibc defines I as a macro which breaks things, e.g., boost template names\n#ifdef I\n#    undef I\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\ntemplate <typename T>\nstruct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {\n    static constexpr const char c = format_descriptor<T>::c;\n    static constexpr const char value[3] = {'Z', c, '\\0'};\n    static std::string format() { return std::string(value); }\n};\n\n#ifndef PYBIND11_CPP17\n\ntemplate <typename T>\nconstexpr const char\n    format_descriptor<std::complex<T>,\n                      detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];\n\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename T>\nstruct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {\n    static constexpr bool value = true;\n    static constexpr int index = is_fmt_numeric<T>::index + 3;\n};\n\ntemplate <typename T>\nclass type_caster<std::complex<T>> {\npublic:\n    bool load(handle src, bool convert) {\n        if (!src) {\n            return false;\n        }\n        if (!convert\n            && !(PyComplex_Check(src.ptr()) || PyFloat_Check(src.ptr())\n                 || PYBIND11_LONG_CHECK(src.ptr()))) {\n            return false;\n        }\n        handle src_or_index = src;\n        // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.\n        // The same logic is used in numeric_caster for ints and floats\n#if defined(PYPY_VERSION)\n        object index;\n        if (PYBIND11_INDEX_CHECK(src.ptr())) {\n            index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));\n            if (!index) {\n                PyErr_Clear();\n                if (!convert)\n                    return false;\n            } else {\n                src_or_index = index;\n            }\n        }\n#endif\n        Py_complex result = PyComplex_AsCComplex(src_or_index.ptr());\n        if (result.real == -1.0 && PyErr_Occurred()) {\n            PyErr_Clear();\n            return false;\n        }\n        value = std::complex<T>((T) result.real, (T) result.imag);\n        return true;\n    }\n\n    static handle\n    cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {\n        return PyComplex_FromDoubles((double) src.real(), (double) src.imag());\n    }\n\n    PYBIND11_TYPE_CASTER(\n        std::complex<T>,\n        io_name(\"typing.SupportsComplex | typing.SupportsFloat | typing.SupportsIndex\",\n                \"complex\"));\n};\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/conduit/README.txt",
    "content": "NOTE\n----\n\nThe C++ code here\n\n** only depends on <Python.h> **\n\nand nothing else.\n\nDO NOT ADD CODE WITH OTHER EXTERNAL DEPENDENCIES TO THIS DIRECTORY.\n\nRead on:\n\npybind11_conduit_v1.h — Type-safe interoperability between different\n                        independent Python/C++ bindings systems.\n"
  },
  {
    "path": "include/pybind11/conduit/pybind11_conduit_v1.h",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n/* The pybind11_conduit_v1 feature enables type-safe interoperability between\n\n* different independent Python/C++ bindings systems,\n\n* including pybind11 versions with different PYBIND11_INTERNALS_VERSION's.\n\n    * NOTE: The conduit feature\n            only covers    from-Python-to-C++ conversions, it\n            does not cover from-C++-to-Python conversions.\n            (For the latter, a different feature would have to be added.)\n\nThe naming of the feature is a bit misleading:\n\n* The feature is in no way tied to pybind11 internals.\n\n* It just happens to originate from pybind11 and currently still lives there.\n\n* The only external dependency is <Python.h>.\n\nThe implementation is a VERY light-weight dependency. It is designed to be\ncompatible with any ISO C++11 (or higher) compiler, and does NOT require\nC++ Exception Handling to be enabled.\n\nPlease see https://github.com/pybind/pybind11/pull/5296 for more background.\n\nThe implementation involves a\n\ndef _pybind11_conduit_v1_(\n    self,\n    pybind11_platform_abi_id: bytes,\n    cpp_type_info_capsule: capsule,\n    pointer_kind: bytes) -> capsule\n\nmethod that is meant to be added to Python objects wrapping C++ objects\n(e.g. pybind11::class_-wrapped types).\n\nThe design of the _pybind11_conduit_v1_ feature provides two layers of\nprotection against C++ ABI mismatches:\n\n* The first and most important layer is that the pybind11_platform_abi_id's\n  must match between extensions. — This will never be perfect, but is the same\n  pragmatic approach used in pybind11 since 2017\n  (https://github.com/pybind/pybind11/commit/96997a4b9d4ec3d389a570604394af5d5eee2557,\n  PYBIND11_INTERNALS_ID).\n\n* The second layer is that the typeid(std::type_info).name()'s must match\n  between extensions.\n\nThe implementation below (which is shorter than this comment!), serves as a\nbattle-tested specification. The main API is this one function:\n\nauto *cpp_pointer = pybind11_conduit_v1::get_type_pointer_ephemeral<YourType>(py_obj);\n\nIt is meant to be a minimalistic reference implementation, intentionally\nwithout comprehensive error reporting. It is expected that major bindings\nsystems will roll their own, compatible implementations, potentially with\nsystem-specific error reporting. The essential specifications all bindings\nsystems need to agree on are merely:\n\n* PYBIND11_PLATFORM_ABI_ID (const char* literal).\n\n* The cpp_type_info capsule (see below: a void *ptr and a const char *name).\n\n* The cpp_conduit capsule (see below: a void *ptr and a const char *name).\n\n* \"raw_pointer_ephemeral\" means: the lifetime of the pointer is the lifetime\n  of the py_obj.\n\n*/\n\n// THIS MUST STAY AT THE TOP!\n#include \"pybind11_platform_abi_id.h\"\n\n#include <Python.h>\n#include <typeinfo>\n\nnamespace pybind11_conduit_v1 {\n\ninline void *get_raw_pointer_ephemeral(PyObject *py_obj, const std::type_info *cpp_type_info) {\n    PyObject *cpp_type_info_capsule\n        = PyCapsule_New(const_cast<void *>(static_cast<const void *>(cpp_type_info)),\n                        typeid(std::type_info).name(),\n                        nullptr);\n    if (cpp_type_info_capsule == nullptr) {\n        return nullptr;\n    }\n    PyObject *cpp_conduit = PyObject_CallMethod(py_obj,\n                                                \"_pybind11_conduit_v1_\",\n                                                \"yOy\",\n                                                PYBIND11_PLATFORM_ABI_ID,\n                                                cpp_type_info_capsule,\n                                                \"raw_pointer_ephemeral\");\n    Py_DECREF(cpp_type_info_capsule);\n    if (cpp_conduit == nullptr) {\n        return nullptr;\n    }\n    void *raw_ptr = PyCapsule_GetPointer(cpp_conduit, cpp_type_info->name());\n    Py_DECREF(cpp_conduit);\n    if (PyErr_Occurred()) {\n        return nullptr;\n    }\n    return raw_ptr;\n}\n\ntemplate <typename T>\nT *get_type_pointer_ephemeral(PyObject *py_obj) {\n    void *raw_ptr = get_raw_pointer_ephemeral(py_obj, &typeid(T));\n    if (raw_ptr == nullptr) {\n        return nullptr;\n    }\n    return static_cast<T *>(raw_ptr);\n}\n\n} // namespace pybind11_conduit_v1\n"
  },
  {
    "path": "include/pybind11/conduit/pybind11_platform_abi_id.h",
    "content": "#pragma once\n\n// Copyright (c) 2024 The pybind Community.\n\n// To maximize reusability:\n// DO NOT ADD CODE THAT REQUIRES C++ EXCEPTION HANDLING.\n\n#include \"wrap_include_python_h.h\"\n\n// Implementation details. DO NOT USE ELSEWHERE. (Unfortunately we cannot #undef them.)\n// This is duplicated here to maximize portability.\n#define PYBIND11_PLATFORM_ABI_ID_STRINGIFY(x) #x\n#define PYBIND11_PLATFORM_ABI_ID_TOSTRING(x) PYBIND11_PLATFORM_ABI_ID_STRINGIFY(x)\n\n#ifdef PYBIND11_COMPILER_TYPE\n//   // To maintain backward compatibility (see PR #5439).\n#    define PYBIND11_COMPILER_TYPE_LEADING_UNDERSCORE \"\"\n#else\n#    define PYBIND11_COMPILER_TYPE_LEADING_UNDERSCORE \"_\"\n#    if defined(__MINGW32__)\n#        define PYBIND11_COMPILER_TYPE \"mingw\"\n#    elif defined(__CYGWIN__)\n#        define PYBIND11_COMPILER_TYPE \"gcc_cygwin\"\n#    elif defined(_MSC_VER)\n#        define PYBIND11_COMPILER_TYPE \"msvc\"\n#    elif defined(__clang__) || defined(__GNUC__)\n#        define PYBIND11_COMPILER_TYPE \"system\" // Assumed compatible with system compiler.\n#    else\n#        error \"Unknown PYBIND11_COMPILER_TYPE: PLEASE REVISE THIS CODE.\"\n#    endif\n#endif\n\n// PR #5439 made this macro obsolete. However, there are many manipulations of this macro in the\n// wild. Therefore, to maintain backward compatibility, it is kept around.\n#ifndef PYBIND11_STDLIB\n#    define PYBIND11_STDLIB \"\"\n#endif\n\n#ifndef PYBIND11_BUILD_ABI\n#    if defined(_MSC_VER)                 // See PR #4953.\n#        if defined(_MT) && defined(_DLL) // Corresponding to CL command line options /MD or /MDd.\n#            if (_MSC_VER) / 100 == 19\n#                define PYBIND11_BUILD_ABI \"_md_mscver19\"\n#            else\n#                error \"Unknown major version for MSC_VER: PLEASE REVISE THIS CODE.\"\n#            endif\n#        elif defined(_MT) // Corresponding to CL command line options /MT or /MTd.\n#            define PYBIND11_BUILD_ABI \"_mt_mscver\" PYBIND11_PLATFORM_ABI_ID_TOSTRING(_MSC_VER)\n#        else\n#            if (_MSC_VER) / 100 == 19\n#                define PYBIND11_BUILD_ABI \"_none_mscver19\"\n#            else\n#                error \"Unknown major version for MSC_VER: PLEASE REVISE THIS CODE.\"\n#            endif\n#        endif\n#    elif defined(_LIBCPP_ABI_VERSION) // https://libcxx.llvm.org/DesignDocs/ABIVersioning.html\n#        define PYBIND11_BUILD_ABI                                                                \\\n            \"_libcpp_abi\" PYBIND11_PLATFORM_ABI_ID_TOSTRING(_LIBCPP_ABI_VERSION)\n#    elif defined(_GLIBCXX_USE_CXX11_ABI) // See PR #5439.\n#        if defined(__NVCOMPILER)\n//           // Assume that NVHPC is in the 1xxx ABI family.\n//           // THIS ASSUMPTION IS NOT FUTURE PROOF but apparently the best we can do.\n//           // Please let us know if there is a way to validate the assumption here.\n#        elif !defined(__GXX_ABI_VERSION)\n#            error                                                                                \\\n                \"Unknown platform or compiler (_GLIBCXX_USE_CXX11_ABI): PLEASE REVISE THIS CODE.\"\n#        endif\n#        if defined(__GXX_ABI_VERSION) && __GXX_ABI_VERSION < 1002 || __GXX_ABI_VERSION >= 2000\n#            error \"Unknown platform or compiler (__GXX_ABI_VERSION): PLEASE REVISE THIS CODE.\"\n#        endif\n#        define PYBIND11_BUILD_ABI                                                                \\\n            \"_libstdcpp_gxx_abi_1xxx_use_cxx11_abi_\" PYBIND11_PLATFORM_ABI_ID_TOSTRING(           \\\n                _GLIBCXX_USE_CXX11_ABI)\n#    else\n#        error \"Unknown platform or compiler: PLEASE REVISE THIS CODE.\"\n#    endif\n#endif\n\n// On MSVC, debug and release builds are not ABI-compatible!\n#if defined(_MSC_VER) && defined(_DEBUG)\n#    define PYBIND11_BUILD_TYPE \"_debug\"\n#else\n#    define PYBIND11_BUILD_TYPE \"\"\n#endif\n\n#define PYBIND11_PLATFORM_ABI_ID                                                                  \\\n    PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE\n"
  },
  {
    "path": "include/pybind11/conduit/wrap_include_python_h.h",
    "content": "#pragma once\n\n// Copyright (c) 2024 The pybind Community.\n\n// STRONG REQUIREMENT:\n//   This header is a wrapper around `#include <Python.h>`, therefore it\n//   MUST BE INCLUDED BEFORE ANY STANDARD HEADERS are included.\n// See also:\n//   https://docs.python.org/3/c-api/intro.html#include-files\n// Quoting from there:\n//   Note: Since Python may define some pre-processor definitions which affect\n//   the standard headers on some systems, you must include Python.h before\n//   any standard headers are included.\n\n// To maximize reusability:\n// DO NOT ADD CODE THAT REQUIRES C++ EXCEPTION HANDLING.\n\n// Disable linking to pythonX_d.lib on Windows in debug mode.\n#if defined(_MSC_VER) && defined(_DEBUG) && !defined(Py_DEBUG)\n// Workaround for a VS 2022 issue.\n// See https://github.com/pybind/pybind11/pull/3497 for full context.\n// NOTE: This workaround knowingly violates the Python.h include order\n//       requirement (see above).\n#    include <yvals.h>\n#    if _MSVC_STL_VERSION >= 143\n#        include <crtdefs.h>\n#    endif\n#    define PYBIND11_DEBUG_MARKER\n#    undef _DEBUG\n#endif\n\n// Don't let Python.h #define (v)snprintf as macro because they are implemented\n// properly in Visual Studio since 2015.\n#if defined(_MSC_VER)\n#    define HAVE_SNPRINTF 1\n#endif\n\n#if defined(_MSC_VER)\n#    pragma warning(push)\n#    pragma warning(disable : 4505)\n// C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed\n#endif\n\n#include <Python.h>\n#include <frameobject.h>\n#include <pythread.h>\n\n#if defined(_MSC_VER)\n#    pragma warning(pop)\n#endif\n\n#if defined(PYBIND11_DEBUG_MARKER)\n#    define _DEBUG 1\n#    undef PYBIND11_DEBUG_MARKER\n#endif\n\n// Python #defines overrides on all sorts of core functions, which\n// tends to wreak havok in C++ codebases that expect these to work\n// like regular functions (potentially with several overloads).\n#if defined(isalnum)\n#    undef isalnum\n#    undef isalpha\n#    undef islower\n#    undef isspace\n#    undef isupper\n#    undef tolower\n#    undef toupper\n#endif\n\n#if defined(copysign)\n#    undef copysign\n#endif\n"
  },
  {
    "path": "include/pybind11/critical_section.h",
    "content": "// Copyright (c) 2016-2025 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"pytypes.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\n/// This does not do anything if there's a GIL. On free-threaded Python,\n/// it locks an object. This uses the CPython API, which has limits\nclass scoped_critical_section {\npublic:\n#ifdef Py_GIL_DISABLED\n    explicit scoped_critical_section(handle obj1, handle obj2 = handle{}) {\n        if (obj1) {\n            if (obj2) {\n                PyCriticalSection2_Begin(&section2, obj1.ptr(), obj2.ptr());\n                rank = 2;\n            } else {\n                PyCriticalSection_Begin(&section, obj1.ptr());\n                rank = 1;\n            }\n        } else if (obj2) {\n            PyCriticalSection_Begin(&section, obj2.ptr());\n            rank = 1;\n        }\n    }\n\n    ~scoped_critical_section() {\n        if (rank == 1) {\n            PyCriticalSection_End(&section);\n        } else if (rank == 2) {\n            PyCriticalSection2_End(&section2);\n        }\n    }\n#else\n    explicit scoped_critical_section(handle, handle = handle{}) {};\n    ~scoped_critical_section() = default;\n#endif\n\n    scoped_critical_section(const scoped_critical_section &) = delete;\n    scoped_critical_section &operator=(const scoped_critical_section &) = delete;\n\nprivate:\n#ifdef Py_GIL_DISABLED\n    int rank{0};\n    union {\n        PyCriticalSection section;\n        PyCriticalSection2 section2;\n    };\n#endif\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/argument_vector.h",
    "content": "/*\n    pybind11/detail/argument_vector.h: small_vector-like containers to\n    avoid heap allocation of arguments during function call dispatch.\n\n    Copyright (c) Meta Platforms, Inc. and affiliates.\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/pytypes.h>\n\n#include \"common.h\"\n\n#include <algorithm>\n#include <array>\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n#include <iterator>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Shared implementation utility for our small_vector-like containers.\n// We support C++11 and C++14, so we cannot use\n// std::variant. Union with the tag packed next to the inline\n// array's size is smaller anyway, allowing 1 extra handle of\n// inline storage for free. Compare the layouts (1 line per\n// size_t/void*, assuming a 64-bit machine):\n// With variant, total is N + 2 for N >= 2:\n// - variant tag (cannot be packed with the array size)\n// - array size (or first pointer of 3 in std::vector)\n// - N pointers of inline storage (or 2 remaining pointers of std::vector)\n// Custom union, total is N + 1 for N >= 3:\n// - variant tag & array size if applicable\n// - N pointers of inline storage (or 3 pointers of std::vector)\n//\n// NOTE: this is a low-level representational convenience; the two\n// use cases of this union are materially different and in particular\n// have different semantics for inline_array::size. All that is being\n// shared is the memory management behavior.\ntemplate <typename ArrayT, std::size_t InlineSize, typename VectorT = ArrayT>\nunion inline_array_or_vector {\n    struct inline_array {\n        bool is_inline = true;\n        std::uint32_t size = 0;\n        std::array<ArrayT, InlineSize> arr;\n    };\n    struct heap_vector {\n        bool is_inline = false;\n        std::vector<VectorT> vec;\n\n        heap_vector() = default;\n        heap_vector(std::size_t count, VectorT value) : vec(count, value) {}\n    };\n\n    inline_array iarray;\n    heap_vector hvector;\n\n    inline_array_or_vector() : iarray() {}\n\n    ~inline_array_or_vector() {\n        if (is_inline()) {\n            iarray.~inline_array();\n        } else {\n            hvector.~heap_vector();\n        }\n    }\n\n    // Disable copy ctor and assignment.\n    inline_array_or_vector(const inline_array_or_vector &) = delete;\n    inline_array_or_vector &operator=(const inline_array_or_vector &) = delete;\n\n    inline_array_or_vector(inline_array_or_vector &&rhs) noexcept {\n        if (rhs.is_inline()) {\n            new (&iarray) inline_array(std::move(rhs.iarray));\n        } else {\n            new (&hvector) heap_vector(std::move(rhs.hvector));\n        }\n        assert(is_inline() == rhs.is_inline());\n    }\n\n    inline_array_or_vector &operator=(inline_array_or_vector &&rhs) noexcept {\n        if (this == &rhs) {\n            return *this;\n        }\n\n        if (is_inline()) {\n            iarray.~inline_array();\n        } else {\n            hvector.~heap_vector();\n        }\n\n        if (rhs.is_inline()) {\n            new (&iarray) inline_array(std::move(rhs.iarray));\n        } else {\n            new (&hvector) heap_vector(std::move(rhs.hvector));\n        }\n        return *this;\n    }\n\n    bool is_inline() const {\n        // It is undefined behavior to access the inactive member of a\n        // union directly. However, it is well-defined to reinterpret_cast any\n        // pointer into a pointer to char and examine it as an array\n        // of bytes. See\n        // https://dev-discuss.pytorch.org/t/unionizing-for-profit-how-to-exploit-the-power-of-unions-in-c/444#the-memcpy-loophole-4\n        bool result = false;\n        static_assert(offsetof(inline_array, is_inline) == 0,\n                      \"untagged union implementation relies on this\");\n        static_assert(offsetof(heap_vector, is_inline) == 0,\n                      \"untagged union implementation relies on this\");\n        std::memcpy(&result, reinterpret_cast<const char *>(this), sizeof(bool));\n        return result;\n    }\n};\n\ntemplate <typename T, std::size_t InlineSize>\nstruct small_vector {\npublic:\n    small_vector() = default;\n\n    // Disable copy ctor and assignment.\n    small_vector(const small_vector &) = delete;\n    small_vector &operator=(const small_vector &) = delete;\n    small_vector(small_vector &&) noexcept = default;\n    small_vector &operator=(small_vector &&) noexcept = default;\n\n    std::size_t size() const {\n        if (is_inline()) {\n            return m_repr.iarray.size;\n        }\n        return m_repr.hvector.vec.size();\n    }\n\n    T const *data() const {\n        if (is_inline()) {\n            return m_repr.iarray.arr.data();\n        }\n        return m_repr.hvector.vec.data();\n    }\n\n    T &operator[](std::size_t idx) {\n        assert(idx < size());\n        if (is_inline()) {\n            return m_repr.iarray.arr[idx];\n        }\n        return m_repr.hvector.vec[idx];\n    }\n\n    T const &operator[](std::size_t idx) const {\n        assert(idx < size());\n        if (is_inline()) {\n            return m_repr.iarray.arr[idx];\n        }\n        return m_repr.hvector.vec[idx];\n    }\n\n    void push_back(const T &x) { emplace_back(x); }\n\n    void push_back(T &&x) { emplace_back(std::move(x)); }\n\n    template <typename... Args>\n    void emplace_back(Args &&...x) {\n        if (is_inline()) {\n            auto &ha = m_repr.iarray;\n            if (ha.size == InlineSize) {\n                move_to_heap_vector_with_reserved_size(InlineSize + 1);\n                m_repr.hvector.vec.emplace_back(std::forward<Args>(x)...);\n            } else {\n                ha.arr[ha.size++] = T(std::forward<Args>(x)...);\n            }\n        } else {\n            m_repr.hvector.vec.emplace_back(std::forward<Args>(x)...);\n        }\n    }\n\n    void reserve(std::size_t sz) {\n        if (is_inline()) {\n            if (sz > InlineSize) {\n                move_to_heap_vector_with_reserved_size(sz);\n            }\n        } else {\n            reserve_slow_path(sz);\n        }\n    }\n\nprivate:\n    using repr_type = inline_array_or_vector<T, InlineSize>;\n    repr_type m_repr;\n\n    PYBIND11_NOINLINE void move_to_heap_vector_with_reserved_size(std::size_t reserved_size) {\n        assert(is_inline());\n        auto &ha = m_repr.iarray;\n        using heap_vector = typename repr_type::heap_vector;\n        heap_vector hv;\n        hv.vec.reserve(reserved_size);\n        static_assert(std::is_nothrow_move_constructible<T>::value,\n                      \"this conversion is not exception safe\");\n        static_assert(std::is_nothrow_move_constructible<heap_vector>::value,\n                      \"this conversion is not exception safe\");\n        std::move(ha.arr.begin(), ha.arr.begin() + ha.size, std::back_inserter(hv.vec));\n        new (&m_repr.hvector) heap_vector(std::move(hv));\n    }\n\n    PYBIND11_NOINLINE void reserve_slow_path(std::size_t sz) { m_repr.hvector.vec.reserve(sz); }\n\n    bool is_inline() const { return m_repr.is_inline(); }\n};\n\n// Container to avoid heap allocation for kRequestedInlineSize or fewer booleans.\ntemplate <std::size_t kRequestedInlineSize>\nstruct small_vector<bool, kRequestedInlineSize> {\nprivate:\npublic:\n    small_vector() = default;\n\n    // Disable copy ctor and assignment.\n    small_vector(const small_vector &) = delete;\n    small_vector &operator=(const small_vector &) = delete;\n    small_vector(small_vector &&) noexcept = default;\n    small_vector &operator=(small_vector &&) noexcept = default;\n\n    small_vector(std::size_t count, bool value) {\n        if (count > kInlineSize) {\n            new (&m_repr.hvector) typename repr_type::heap_vector(count, value);\n        } else {\n            auto &inline_arr = m_repr.iarray;\n            inline_arr.arr.fill(value ? static_cast<std::size_t>(-1) : 0);\n            inline_arr.size = static_cast<decltype(inline_arr.size)>(count);\n        }\n    }\n\n    std::size_t size() const {\n        if (is_inline()) {\n            return m_repr.iarray.size;\n        }\n        return m_repr.hvector.vec.size();\n    }\n\n    void reserve(std::size_t sz) {\n        if (is_inline()) {\n            if (sz > kInlineSize) {\n                move_to_heap_vector_with_reserved_size(sz);\n            }\n        } else {\n            m_repr.hvector.vec.reserve(sz);\n        }\n    }\n\n    bool operator[](std::size_t idx) const {\n        if (is_inline()) {\n            return inline_index(idx);\n        }\n        assert(idx < m_repr.hvector.vec.size());\n        return m_repr.hvector.vec[idx];\n    }\n\n    void push_back(bool b) {\n        if (is_inline()) {\n            auto &ha = m_repr.iarray;\n            if (ha.size == kInlineSize) {\n                move_to_heap_vector_with_reserved_size(kInlineSize + 1);\n                push_back_slow_path(b);\n            } else {\n                assert(ha.size < kInlineSize);\n                const auto wbi = word_and_bit_index(ha.size++);\n                assert(wbi.word < kWords);\n                assert(wbi.bit < kBitsPerWord);\n                if (b) {\n                    ha.arr[wbi.word] |= (static_cast<std::size_t>(1) << wbi.bit);\n                } else {\n                    ha.arr[wbi.word] &= ~(static_cast<std::size_t>(1) << wbi.bit);\n                }\n                assert(operator[](ha.size - 1) == b);\n            }\n        } else {\n            push_back_slow_path(b);\n        }\n    }\n\n    void set(std::size_t idx, bool value = true) {\n        if (is_inline()) {\n            auto &ha = m_repr.iarray;\n            assert(ha.size < kInlineSize);\n            const auto wbi = word_and_bit_index(idx);\n            assert(wbi.word < kWords);\n            assert(wbi.bit < kBitsPerWord);\n            if (value) {\n                ha.arr[wbi.word] |= (static_cast<std::size_t>(1) << wbi.bit);\n            } else {\n                ha.arr[wbi.word] &= ~(static_cast<std::size_t>(1) << wbi.bit);\n            }\n        } else {\n            m_repr.hvector.vec[idx] = value;\n        }\n    }\n\n    void swap(small_vector &rhs) noexcept { std::swap(m_repr, rhs.m_repr); }\n\nprivate:\n    struct WordAndBitIndex {\n        std::size_t word;\n        std::size_t bit;\n    };\n\n    static WordAndBitIndex word_and_bit_index(std::size_t idx) {\n        return WordAndBitIndex{idx / kBitsPerWord, idx % kBitsPerWord};\n    }\n\n    bool inline_index(std::size_t idx) const {\n        const auto wbi = word_and_bit_index(idx);\n        assert(wbi.word < kWords);\n        assert(wbi.bit < kBitsPerWord);\n        return m_repr.iarray.arr[wbi.word] & (static_cast<std::size_t>(1) << wbi.bit);\n    }\n\n    PYBIND11_NOINLINE void move_to_heap_vector_with_reserved_size(std::size_t reserved_size) {\n        auto &inline_arr = m_repr.iarray;\n        using heap_vector = typename repr_type::heap_vector;\n        heap_vector hv;\n        hv.vec.reserve(reserved_size);\n        for (std::size_t ii = 0; ii < inline_arr.size; ++ii) {\n            hv.vec.push_back(inline_index(ii));\n        }\n        new (&m_repr.hvector) heap_vector(std::move(hv));\n    }\n\n    PYBIND11_NOINLINE void push_back_slow_path(bool b) { m_repr.hvector.vec.push_back(b); }\n\n    static constexpr auto kBitsPerWord = 8 * sizeof(std::size_t);\n    static constexpr auto kWords = (kRequestedInlineSize + kBitsPerWord - 1) / kBitsPerWord;\n    static constexpr auto kInlineSize = kWords * kBitsPerWord;\n\n    using repr_type = inline_array_or_vector<std::size_t, kWords, bool>;\n    repr_type m_repr;\n\n    bool is_inline() const { return m_repr.is_inline(); }\n};\n\n// Container to avoid heap allocation for N or fewer arguments.\ntemplate <size_t N>\nusing argument_vector = small_vector<handle, N>;\n\n// Container to avoid heap allocation for N or fewer booleans.\ntemplate <size_t N>\nusing args_convert_vector = small_vector<bool, N>;\n\n/// A small_vector of PyObject* that holds references and releases them on destruction.\n/// This provides explicit ownership semantics without relying on py::object's\n/// destructor, and avoids the need for reinterpret_cast when passing to vectorcall.\ntemplate <std::size_t InlineSize>\nclass ref_small_vector {\npublic:\n    ref_small_vector() = default;\n\n    ~ref_small_vector() {\n        for (std::size_t i = 0; i < m_ptrs.size(); ++i) {\n            Py_XDECREF(m_ptrs[i]);\n        }\n    }\n\n    // Disable copy (prevent accidental double-decref)\n    ref_small_vector(const ref_small_vector &) = delete;\n    ref_small_vector &operator=(const ref_small_vector &) = delete;\n\n    // Move is allowed\n    ref_small_vector(ref_small_vector &&other) noexcept : m_ptrs(std::move(other.m_ptrs)) {\n        // other.m_ptrs is now empty, so its destructor won't decref anything\n    }\n\n    ref_small_vector &operator=(ref_small_vector &&other) noexcept {\n        if (this != &other) {\n            // Decref our current contents\n            for (std::size_t i = 0; i < m_ptrs.size(); ++i) {\n                Py_XDECREF(m_ptrs[i]);\n            }\n            m_ptrs = std::move(other.m_ptrs);\n        }\n        return *this;\n    }\n\n    /// Add a pointer, taking ownership (no incref, will decref on destruction)\n    void push_back_steal(PyObject *p) { m_ptrs.push_back(p); }\n\n    /// Add a pointer, borrowing (increfs now, will decref on destruction)\n    void push_back_borrow(PyObject *p) {\n        Py_XINCREF(p);\n        m_ptrs.push_back(p);\n    }\n\n    /// Add a null pointer (for PY_VECTORCALL_ARGUMENTS_OFFSET slot)\n    void push_back_null() { m_ptrs.push_back(nullptr); }\n\n    void reserve(std::size_t sz) { m_ptrs.reserve(sz); }\n\n    std::size_t size() const { return m_ptrs.size(); }\n\n    PyObject *operator[](std::size_t idx) const { return m_ptrs[idx]; }\n\n    PyObject *const *data() const { return m_ptrs.data(); }\n\nprivate:\n    small_vector<PyObject *, InlineSize> m_ptrs;\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/class.h",
    "content": "/*\n    pybind11/detail/class.h: Python C API implementation details for py::class_\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/attr.h>\n#include <pybind11/options.h>\n\n#include \"exception_translation.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n#if !defined(PYPY_VERSION)\n#    define PYBIND11_BUILTIN_QUALNAME\n#    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)\n#else\n// In PyPy, we still set __qualname__ so that we can produce reliable function type\n// signatures; in CPython this macro expands to nothing:\n#    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)                                             \\\n        setattr((PyObject *) obj, \"__qualname__\", nameobj)\n#endif\n\ninline std::string get_fully_qualified_tp_name(PyTypeObject *type) {\n#if !defined(PYPY_VERSION)\n    return type->tp_name;\n#else\n    auto module_name = handle((PyObject *) type).attr(\"__module__\").cast<std::string>();\n    if (module_name == PYBIND11_BUILTINS_MODULE)\n        return type->tp_name;\n    else\n        return std::move(module_name) + \".\" + type->tp_name;\n#endif\n}\n\ninline PyTypeObject *type_incref(PyTypeObject *type) {\n    Py_INCREF(type);\n    return type;\n}\n\n#if !defined(PYPY_VERSION)\n\n/// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.\nextern \"C\" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {\n    return PyProperty_Type.tp_descr_get(self, cls, cls);\n}\n\n/// `pybind11_static_property.__set__()`: Just like the above `__get__()`.\nextern \"C\" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {\n    PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);\n    return PyProperty_Type.tp_descr_set(self, cls, value);\n}\n\n// Forward declaration to use in `make_static_property_type()`\ninline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);\n\n/** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`\n    methods are modified to always use the object type instead of a concrete instance.\n    Return value: New reference. */\ninline PyTypeObject *make_static_property_type() {\n    constexpr auto *name = \"pybind11_static_property\";\n    auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));\n\n    /* Danger zone: from now (and until PyType_Ready), make sure to\n       issue no Python C API calls which could potentially invoke the\n       garbage collector (the GC will call type_traverse(), which will in\n       turn find the newly constructed type in an invalid state) */\n    auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));\n    if (!heap_type) {\n        pybind11_fail(\"make_static_property_type(): error allocating type!\");\n    }\n\n    heap_type->ht_name = name_obj.inc_ref().ptr();\n#    ifdef PYBIND11_BUILTIN_QUALNAME\n    heap_type->ht_qualname = name_obj.inc_ref().ptr();\n#    endif\n\n    auto *type = &heap_type->ht_type;\n    type->tp_name = name;\n    type->tp_base = type_incref(&PyProperty_Type);\n    type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;\n    type->tp_descr_get = pybind11_static_get;\n    type->tp_descr_set = pybind11_static_set;\n\n#    if PY_VERSION_HEX >= 0x030C0000\n    // Since Python-3.12 property-derived types are required to\n    // have dynamic attributes (to set `__doc__`)\n    enable_dynamic_attributes(heap_type);\n#    endif\n\n    if (PyType_Ready(type) < 0) {\n        pybind11_fail(\"make_static_property_type(): failure in PyType_Ready()!\");\n    }\n\n    setattr(reinterpret_cast<PyObject *>(type), \"__module__\", str(PYBIND11_DUMMY_MODULE_NAME));\n    PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);\n\n    return type;\n}\n\n#else // PYPY\n\n/** PyPy has some issues with the above C API, so we evaluate Python code instead.\n    This function will only be called once so performance isn't really a concern.\n    Return value: New reference. */\ninline PyTypeObject *make_static_property_type() {\n    auto d = dict();\n    PyObject *result = PyRun_String(R\"(\\\nclass pybind11_static_property(property):\n    def __get__(self, obj, cls):\n        return property.__get__(self, cls, cls)\n\n    def __set__(self, obj, value):\n        cls = obj if isinstance(obj, type) else type(obj)\n        property.__set__(self, cls, value)\n)\",\n                                    Py_file_input,\n                                    d.ptr(),\n                                    d.ptr());\n    if (result == nullptr)\n        throw error_already_set();\n    Py_DECREF(result);\n    return (PyTypeObject *) d[\"pybind11_static_property\"].cast<object>().release().ptr();\n}\n\n#endif // PYPY\n\n/** Types with static properties need to handle `Type.static_prop = x` in a specific way.\n    By default, Python replaces the `static_property` itself, but for wrapped C++ types\n    we need to call `static_property.__set__()` in order to propagate the new value to\n    the underlying C++ data structure. */\nextern \"C\" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {\n    // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw\n    // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).\n    PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);\n\n    // The following assignment combinations are possible:\n    //   1. `Type.static_prop = value`             --> descr_set: `Type.static_prop.__set__(value)`\n    //   2. `Type.static_prop = other_static_prop` --> setattro:  replace existing `static_prop`\n    //   3. `Type.regular_attribute = value`       --> setattro:  regular attribute assignment\n    auto *const static_prop = (PyObject *) get_internals().static_property_type;\n    const auto call_descr_set = (descr != nullptr) && (value != nullptr)\n                                && (PyObject_IsInstance(descr, static_prop) != 0)\n                                && (PyObject_IsInstance(value, static_prop) == 0);\n    if (call_descr_set) {\n        // Call `static_property.__set__()` instead of replacing the `static_property`.\n#if !defined(PYPY_VERSION)\n        return Py_TYPE(descr)->tp_descr_set(descr, obj, value);\n#else\n        if (PyObject *result = PyObject_CallMethod(descr, \"__set__\", \"OO\", obj, value)) {\n            Py_DECREF(result);\n            return 0;\n        } else {\n            return -1;\n        }\n#endif\n    } else {\n        // Replace existing attribute.\n        return PyType_Type.tp_setattro(obj, name, value);\n    }\n}\n\n/**\n * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing\n * methods via cls.attr(\"m2\") = cls.attr(\"m1\"): instead the tp_descr_get returns a plain function,\n * when called on a class, or a PyMethod, when called on an instance.  Override that behaviour here\n * to do a special case bypass for PyInstanceMethod_Types.\n */\nextern \"C\" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {\n    PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);\n    if (descr && PyInstanceMethod_Check(descr)) {\n        Py_INCREF(descr);\n        return descr;\n    }\n    return PyType_Type.tp_getattro(obj, name);\n}\n\n/// metaclass `__call__` function that is used to create all pybind11 objects.\nextern \"C\" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {\n\n    // use the default metaclass call to create/initialize the object\n    PyObject *self = PyType_Type.tp_call(type, args, kwargs);\n    if (self == nullptr) {\n        return nullptr;\n    }\n\n    // Ensure that the base __init__ function(s) were called\n    values_and_holders vhs(self);\n    for (const auto &vh : vhs) {\n        if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {\n            PyErr_Format(PyExc_TypeError,\n                         \"%.200s.__init__() must be called when overriding __init__\",\n                         get_fully_qualified_tp_name(vh.type->type).c_str());\n            Py_DECREF(self);\n            return nullptr;\n        }\n    }\n\n    return self;\n}\n\n/// Cleanup the type-info for a pybind11-registered type.\nextern \"C\" inline void pybind11_meta_dealloc(PyObject *obj) {\n    with_internals_if_internals([obj](internals &internals) {\n        auto *type = (PyTypeObject *) obj;\n\n        // A pybind11-registered type will:\n        // 1) be found in internals.registered_types_py\n        // 2) have exactly one associated `detail::type_info`\n        auto found_type = internals.registered_types_py.find(type);\n        if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1\n            && found_type->second[0]->type == type) {\n\n            auto *tinfo = found_type->second[0];\n            auto tindex = std::type_index(*tinfo->cpptype);\n            internals.direct_conversions.erase(tindex);\n\n            auto &local_internals = get_local_internals();\n            if (tinfo->module_local) {\n                local_internals.registered_types_cpp.erase(tinfo->cpptype);\n            } else {\n                internals.registered_types_cpp.erase(tindex);\n#if PYBIND11_INTERNALS_VERSION >= 12\n                internals.registered_types_cpp_fast.erase(tinfo->cpptype);\n                for (const std::type_info *alias : tinfo->alias_chain) {\n                    auto num_erased = internals.registered_types_cpp_fast.erase(alias);\n                    (void) num_erased;\n                    assert(num_erased > 0);\n                }\n#endif\n            }\n            internals.registered_types_py.erase(tinfo->type);\n\n            // Actually just `std::erase_if`, but that's only available in C++20\n            auto &cache = internals.inactive_override_cache;\n            for (auto it = cache.begin(), last = cache.end(); it != last;) {\n                if (it->first == (PyObject *) tinfo->type) {\n                    it = cache.erase(it);\n                } else {\n                    ++it;\n                }\n            }\n\n            delete tinfo;\n        }\n    });\n\n    PyType_Type.tp_dealloc(obj);\n}\n\n/** This metaclass is assigned by default to all pybind11 types and is required in order\n    for static properties to function correctly. Users may override this using `py::metaclass`.\n    Return value: New reference. */\ninline PyTypeObject *make_default_metaclass() {\n    constexpr auto *name = \"pybind11_type\";\n    auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));\n\n    /* Danger zone: from now (and until PyType_Ready), make sure to\n       issue no Python C API calls which could potentially invoke the\n       garbage collector (the GC will call type_traverse(), which will in\n       turn find the newly constructed type in an invalid state) */\n    auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));\n    if (!heap_type) {\n        pybind11_fail(\"make_default_metaclass(): error allocating metaclass!\");\n    }\n\n    heap_type->ht_name = name_obj.inc_ref().ptr();\n#ifdef PYBIND11_BUILTIN_QUALNAME\n    heap_type->ht_qualname = name_obj.inc_ref().ptr();\n#endif\n\n    auto *type = &heap_type->ht_type;\n    type->tp_name = name;\n    type->tp_base = type_incref(&PyType_Type);\n    type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;\n\n    type->tp_call = pybind11_meta_call;\n\n    type->tp_setattro = pybind11_meta_setattro;\n    type->tp_getattro = pybind11_meta_getattro;\n\n    type->tp_dealloc = pybind11_meta_dealloc;\n\n    if (PyType_Ready(type) < 0) {\n        pybind11_fail(\"make_default_metaclass(): failure in PyType_Ready()!\");\n    }\n\n    setattr(reinterpret_cast<PyObject *>(type), \"__module__\", str(PYBIND11_DUMMY_MODULE_NAME));\n    PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);\n\n    return type;\n}\n\n/// For multiple inheritance types we need to recursively register/deregister base pointers for any\n/// base classes with pointers that are difference from the instance value pointer so that we can\n/// correctly recognize an offset base class pointer. This calls a function with any offset base\n/// ptrs.\ninline void traverse_offset_bases(void *valueptr,\n                                  const detail::type_info *tinfo,\n                                  instance *self,\n                                  bool (*f)(void * /*parentptr*/, instance * /*self*/)) {\n    for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {\n        if (auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()))) {\n            for (auto &c : parent_tinfo->implicit_casts) {\n                if (c.first == tinfo->cpptype) {\n                    auto *parentptr = c.second(valueptr);\n                    if (parentptr != valueptr) {\n                        f(parentptr, self);\n                    }\n                    traverse_offset_bases(parentptr, parent_tinfo, self, f);\n                    break;\n                }\n            }\n        }\n    }\n}\n\n#ifdef Py_GIL_DISABLED\ninline void enable_try_inc_ref(PyObject *obj) {\n#    if PY_VERSION_HEX >= 0x030E00A4\n    PyUnstable_EnableTryIncRef(obj);\n#    else\n    if (_Py_IsImmortal(obj)) {\n        return;\n    }\n    for (;;) {\n        Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared);\n        if ((shared & _Py_REF_SHARED_FLAG_MASK) != 0) {\n            // Nothing to do if it's in WEAKREFS, QUEUED, or MERGED states.\n            return;\n        }\n        if (_Py_atomic_compare_exchange_ssize(\n                &obj->ob_ref_shared, &shared, shared | _Py_REF_MAYBE_WEAKREF)) {\n            return;\n        }\n    }\n#    endif\n}\n#endif\n\ninline bool register_instance_impl(void *ptr, instance *self) {\n    assert(ptr);\n#ifdef Py_GIL_DISABLED\n    enable_try_inc_ref(reinterpret_cast<PyObject *>(self));\n#endif\n    with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });\n    return true; // unused, but gives the same signature as the deregister func\n}\ninline bool deregister_instance_impl(void *ptr, instance *self) {\n    assert(ptr);\n    return with_instance_map(ptr, [&](instance_map &instances) {\n        auto range = instances.equal_range(ptr);\n        for (auto it = range.first; it != range.second; ++it) {\n            if (self == it->second) {\n                instances.erase(it);\n                return true;\n            }\n        }\n        return false;\n    });\n}\n\ninline void register_instance(instance *self, void *valptr, const type_info *tinfo) {\n    register_instance_impl(valptr, self);\n    if (!tinfo->simple_ancestors) {\n        traverse_offset_bases(valptr, tinfo, self, register_instance_impl);\n    }\n}\n\ninline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {\n    bool ret = deregister_instance_impl(valptr, self);\n    if (!tinfo->simple_ancestors) {\n        traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);\n    }\n    return ret;\n}\n\n/// Instance creation function for all pybind11 types. It allocates the internal instance layout\n/// for holding C++ objects and holders.  Allocation is done lazily (the first time the instance is\n/// cast to a reference or pointer), and initialization is done by an `__init__` function.\ninline PyObject *make_new_instance(PyTypeObject *type) {\n#if defined(PYPY_VERSION)\n    // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first\n    // inherited object is a plain Python type (i.e. not derived from an extension type).  Fix it.\n    ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));\n    if (type->tp_basicsize < instance_size) {\n        type->tp_basicsize = instance_size;\n    }\n#endif\n    PyObject *self = type->tp_alloc(type, 0);\n    auto *inst = reinterpret_cast<instance *>(self);\n    // Allocate the value/holder internals:\n    inst->allocate_layout();\n\n    return self;\n}\n\n/// Instance creation function for all pybind11 types. It only allocates space for the\n/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.\nextern \"C\" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {\n    return make_new_instance(type);\n}\n\n/// An `__init__` function constructs the C++ object. Users should provide at least one\n/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the\n/// following default function will be used which simply throws an exception.\nextern \"C\" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {\n    PyTypeObject *type = Py_TYPE(self);\n    std::string msg = get_fully_qualified_tp_name(type) + \": No constructor defined!\";\n    set_error(PyExc_TypeError, msg.c_str());\n    return -1;\n}\n\ninline void add_patient(PyObject *nurse, PyObject *patient) {\n    auto *instance = reinterpret_cast<detail::instance *>(nurse);\n    instance->has_patients = true;\n    Py_INCREF(patient);\n\n    with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });\n}\n\ninline void clear_patients(PyObject *self) {\n    auto *instance = reinterpret_cast<detail::instance *>(self);\n    std::vector<PyObject *> patients;\n\n    with_internals([&](internals &internals) {\n        auto pos = internals.patients.find(self);\n\n        if (pos == internals.patients.end()) {\n            pybind11_fail(\n                \"FATAL: Internal consistency check failed: Invalid clear_patients() call.\");\n        }\n\n        // Clearing the patients can cause more Python code to run, which\n        // can invalidate the iterator. Extract the vector of patients\n        // from the unordered_map first.\n        patients = std::move(pos->second);\n        internals.patients.erase(pos);\n    });\n\n    instance->has_patients = false;\n    for (PyObject *&patient : patients) {\n        Py_CLEAR(patient);\n    }\n}\n\n/// Clears all internal data from the instance and removes it from registered instances in\n/// preparation for deallocation.\ninline void clear_instance(PyObject *self) {\n    auto *instance = reinterpret_cast<detail::instance *>(self);\n\n    // Deallocate any values/holders, if present:\n    for (auto &v_h : values_and_holders(instance)) {\n        if (v_h) {\n\n            // We have to deregister before we call dealloc because, for virtual MI types, we still\n            // need to be able to get the parent pointers.\n            if (v_h.instance_registered()\n                && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {\n                pybind11_fail(\n                    \"pybind11_object_dealloc(): Tried to deallocate unregistered instance!\");\n            }\n\n            if (instance->owned || v_h.holder_constructed()) {\n                v_h.type->dealloc(v_h);\n            }\n        } else if (v_h.holder_constructed()) {\n            v_h.type->dealloc(v_h); // Disowned instance.\n        }\n    }\n    // Deallocate the value/holder layout internals:\n    instance->deallocate_layout();\n\n    if (instance->weakrefs) {\n        PyObject_ClearWeakRefs(self);\n    }\n\n    PyObject **dict_ptr = _PyObject_GetDictPtr(self);\n    if (dict_ptr) {\n        Py_CLEAR(*dict_ptr);\n    }\n\n    if (instance->has_patients) {\n        clear_patients(self);\n    }\n}\n\n/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`\n/// to destroy the C++ object itself, while the rest is Python bookkeeping.\nextern \"C\" inline void pybind11_object_dealloc(PyObject *self) {\n    auto *type = Py_TYPE(self);\n\n    // If this is a GC tracked object, untrack it first\n    // Note that the track call is implicitly done by the\n    // default tp_alloc, which we never override.\n    if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {\n        PyObject_GC_UnTrack(self);\n    }\n\n    clear_instance(self);\n\n    type->tp_free(self);\n\n    // This was not needed before Python 3.8 (Python issue 35810)\n    // https://github.com/pybind/pybind11/issues/1946\n    Py_DECREF(type);\n}\n\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_GCC(\"-Wredundant-decls\")\n\nstd::string error_string();\n\nPYBIND11_WARNING_POP\n\n/** Create the type which can be used as a common base for all classes.  This is\n    needed in order to satisfy Python's requirements for multiple inheritance.\n    Return value: New reference. */\ninline PyObject *make_object_base_type(PyTypeObject *metaclass) {\n    constexpr auto *name = \"pybind11_object\";\n    auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));\n\n    /* Danger zone: from now (and until PyType_Ready), make sure to\n       issue no Python C API calls which could potentially invoke the\n       garbage collector (the GC will call type_traverse(), which will in\n       turn find the newly constructed type in an invalid state) */\n    auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));\n    if (!heap_type) {\n        pybind11_fail(\"make_object_base_type(): error allocating type!\");\n    }\n\n    heap_type->ht_name = name_obj.inc_ref().ptr();\n#ifdef PYBIND11_BUILTIN_QUALNAME\n    heap_type->ht_qualname = name_obj.inc_ref().ptr();\n#endif\n\n    auto *type = &heap_type->ht_type;\n    type->tp_name = name;\n    type->tp_base = type_incref(&PyBaseObject_Type);\n    type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));\n    type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;\n\n    type->tp_new = pybind11_object_new;\n    type->tp_init = pybind11_object_init;\n    type->tp_dealloc = pybind11_object_dealloc;\n\n    /* Support weak references (needed for the keep_alive feature) */\n    type->tp_weaklistoffset = offsetof(instance, weakrefs);\n\n    if (PyType_Ready(type) < 0) {\n        pybind11_fail(\"PyType_Ready failed in make_object_base_type(): \" + error_string());\n    }\n\n    setattr(reinterpret_cast<PyObject *>(type), \"__module__\", str(PYBIND11_DUMMY_MODULE_NAME));\n    PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);\n\n    assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));\n    return reinterpret_cast<PyObject *>(heap_type);\n}\n\n/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.\nextern \"C\" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {\n#if PY_VERSION_HEX >= 0x030D0000\n    PyObject_VisitManagedDict(self, visit, arg);\n#else\n    PyObject *&dict = *_PyObject_GetDictPtr(self);\n    Py_VISIT(dict);\n#endif\n// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse\n#if PY_VERSION_HEX >= 0x03090000\n    Py_VISIT(Py_TYPE(self));\n#endif\n    return 0;\n}\n\n/// dynamic_attr: Allow the GC to clear the dictionary.\nextern \"C\" inline int pybind11_clear(PyObject *self) {\n#if PY_VERSION_HEX >= 0x030D0000\n    PyObject_ClearManagedDict(self);\n#else\n    PyObject *&dict = *_PyObject_GetDictPtr(self);\n    Py_CLEAR(dict);\n#endif\n    return 0;\n}\n\n/// Give instances of this type a `__dict__` and opt into garbage collection.\ninline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {\n    auto *type = &heap_type->ht_type;\n    type->tp_flags |= Py_TPFLAGS_HAVE_GC;\n#ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET\n    type->tp_dictoffset = type->tp_basicsize;           // place dict at the end\n    type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it\n#else\n    type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;\n#endif\n    type->tp_traverse = pybind11_traverse;\n    type->tp_clear = pybind11_clear;\n\n    static PyGetSetDef getset[]\n        = {{\"__dict__\", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},\n           {nullptr, nullptr, nullptr, nullptr, nullptr}};\n    type->tp_getset = getset;\n}\n\n/// buffer_protocol: Fill in the view as specified by flags.\nextern \"C\" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {\n    // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).\n    type_info *tinfo = nullptr;\n    for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {\n        tinfo = get_type_info((PyTypeObject *) type.ptr());\n        if (tinfo && tinfo->get_buffer) {\n            break;\n        }\n    }\n    if (view == nullptr || !tinfo || !tinfo->get_buffer) {\n        if (view) {\n            view->obj = nullptr;\n        }\n        set_error(PyExc_BufferError, \"pybind11_getbuffer(): Internal error\");\n        return -1;\n    }\n    std::memset(view, 0, sizeof(Py_buffer));\n    std::unique_ptr<buffer_info> info = nullptr;\n    try {\n        info.reset(tinfo->get_buffer(obj, tinfo->get_buffer_data));\n    } catch (...) {\n        try_translate_exceptions();\n        raise_from(PyExc_BufferError, \"Error getting buffer\");\n        return -1;\n    }\n    if (info == nullptr) {\n        pybind11_fail(\"FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr.\");\n    }\n\n    if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {\n        // view->obj = nullptr;  // Was just memset to 0, so not necessary\n        set_error(PyExc_BufferError, \"Writable buffer requested for readonly storage\");\n        return -1;\n    }\n\n    // Fill in all the information, and then downgrade as requested by the caller, or raise an\n    // error if that's not possible.\n    view->itemsize = info->itemsize;\n    view->len = view->itemsize;\n    for (auto s : info->shape) {\n        view->len *= s;\n    }\n    view->ndim = static_cast<int>(info->ndim);\n    view->shape = info->shape.data();\n    view->strides = info->strides.data();\n    view->readonly = static_cast<int>(info->readonly);\n    if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {\n        view->format = const_cast<char *>(info->format.c_str());\n    }\n\n    // Note, all contiguity flags imply PyBUF_STRIDES and lower.\n    if ((flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) {\n        if (PyBuffer_IsContiguous(view, 'C') == 0) {\n            std::memset(view, 0, sizeof(Py_buffer));\n            set_error(PyExc_BufferError,\n                      \"C-contiguous buffer requested for discontiguous storage\");\n            return -1;\n        }\n    } else if ((flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) {\n        if (PyBuffer_IsContiguous(view, 'F') == 0) {\n            std::memset(view, 0, sizeof(Py_buffer));\n            set_error(PyExc_BufferError,\n                      \"Fortran-contiguous buffer requested for discontiguous storage\");\n            return -1;\n        }\n    } else if ((flags & PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS) {\n        if (PyBuffer_IsContiguous(view, 'A') == 0) {\n            std::memset(view, 0, sizeof(Py_buffer));\n            set_error(PyExc_BufferError, \"Contiguous buffer requested for discontiguous storage\");\n            return -1;\n        }\n\n    } else if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES) {\n        // If no strides are requested, the buffer must be C-contiguous.\n        // https://docs.python.org/3/c-api/buffer.html#contiguity-requests\n        if (PyBuffer_IsContiguous(view, 'C') == 0) {\n            std::memset(view, 0, sizeof(Py_buffer));\n            set_error(PyExc_BufferError,\n                      \"C-contiguous buffer requested for discontiguous storage\");\n            return -1;\n        }\n\n        view->strides = nullptr;\n\n        // Since this is a contiguous buffer, it can also pretend to be 1D.\n        if ((flags & PyBUF_ND) != PyBUF_ND) {\n            view->shape = nullptr;\n            view->ndim = 0;\n        }\n    }\n\n    // Set these after all checks so they don't leak out into the caller, and can be automatically\n    // cleaned up on error.\n    view->buf = info->ptr;\n    view->internal = info.release();\n    view->obj = obj;\n    Py_INCREF(view->obj);\n    return 0;\n}\n\n/// buffer_protocol: Release the resources of the buffer.\nextern \"C\" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {\n    delete (buffer_info *) view->internal;\n}\n\n/// Give this type a buffer interface.\ninline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {\n    heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;\n\n    heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;\n    heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;\n}\n\n/** Create a brand new Python type according to the `type_record` specification.\n    Return value: New reference. */\ninline PyObject *make_new_python_type(const type_record &rec) {\n    auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));\n\n    auto qualname = name;\n    if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, \"__qualname__\")) {\n        qualname = reinterpret_steal<object>(\n            PyUnicode_FromFormat(\"%U.%U\", rec.scope.attr(\"__qualname__\").ptr(), name.ptr()));\n    }\n\n    object module_ = get_module_name_if_available(rec.scope);\n    const auto *full_name = c_str(\n#if !defined(PYPY_VERSION)\n        module_ ? str(module_).cast<std::string>() + \".\" + rec.name :\n#endif\n                rec.name);\n\n    char *tp_doc = nullptr;\n    if (rec.doc && options::show_user_defined_docstrings()) {\n        /* Allocate memory for docstring (Python will free this later on) */\n        size_t size = std::strlen(rec.doc) + 1;\n#if PY_VERSION_HEX >= 0x030D0000\n        tp_doc = static_cast<char *>(PyMem_MALLOC(size));\n#else\n        tp_doc = (char *) PyObject_MALLOC(size);\n#endif\n        std::memcpy((void *) tp_doc, rec.doc, size);\n    }\n\n    auto &internals = get_internals();\n    auto bases = tuple(rec.bases);\n    auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();\n\n    /* Danger zone: from now (and until PyType_Ready), make sure to\n       issue no Python C API calls which could potentially invoke the\n       garbage collector (the GC will call type_traverse(), which will in\n       turn find the newly constructed type in an invalid state) */\n    auto *metaclass = rec.metaclass.ptr() ? reinterpret_cast<PyTypeObject *>(rec.metaclass.ptr())\n                                          : internals.default_metaclass;\n\n    auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));\n    if (!heap_type) {\n        pybind11_fail(std::string(rec.name) + \": Unable to create type object!\");\n    }\n\n    heap_type->ht_name = name.release().ptr();\n#ifdef PYBIND11_BUILTIN_QUALNAME\n    heap_type->ht_qualname = qualname.inc_ref().ptr();\n#endif\n\n    auto *type = &heap_type->ht_type;\n    type->tp_name = full_name;\n    type->tp_doc = tp_doc;\n    type->tp_base = type_incref(reinterpret_cast<PyTypeObject *>(base));\n    type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));\n    if (!bases.empty()) {\n        type->tp_bases = bases.release().ptr();\n    }\n\n    /* Don't inherit base __init__ */\n    type->tp_init = pybind11_object_init;\n\n    /* Supported protocols */\n    type->tp_as_number = &heap_type->as_number;\n    type->tp_as_sequence = &heap_type->as_sequence;\n    type->tp_as_mapping = &heap_type->as_mapping;\n    type->tp_as_async = &heap_type->as_async;\n\n    /* Flags */\n    type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;\n    if (!rec.is_final) {\n        type->tp_flags |= Py_TPFLAGS_BASETYPE;\n    }\n\n    if (rec.dynamic_attr) {\n        enable_dynamic_attributes(heap_type);\n    }\n\n    if (rec.buffer_protocol) {\n        enable_buffer_protocol(heap_type);\n    }\n\n    if (rec.custom_type_setup_callback) {\n        rec.custom_type_setup_callback(heap_type);\n    }\n\n    if (PyType_Ready(type) < 0) {\n        pybind11_fail(std::string(rec.name) + \": PyType_Ready failed: \" + error_string());\n    }\n\n    assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));\n\n    /* Register type with the parent scope */\n    if (rec.scope) {\n        setattr(rec.scope, rec.name, reinterpret_cast<PyObject *>(type));\n    } else {\n        Py_INCREF(type); // Keep it alive forever (reference leak)\n    }\n\n    if (module_) { // Needed by pydoc\n        setattr(reinterpret_cast<PyObject *>(type), \"__module__\", module_);\n    }\n\n    PYBIND11_SET_OLDPY_QUALNAME(type, qualname);\n\n    return reinterpret_cast<PyObject *>(type);\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/common.h",
    "content": "/*\n    pybind11/detail/common.h -- Basic macros\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/conduit/wrap_include_python_h.h>\n#if PY_VERSION_HEX < 0x03080000\n#    error \"PYTHON < 3.8 IS UNSUPPORTED. pybind11 v2.13 was the last to support Python 3.7.\"\n#endif\n\n// Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html\n// See also: https://github.com/python/cpython/blob/HEAD/Include/patchlevel.h\n/* -- start version constants -- */\n#define PYBIND11_VERSION_MAJOR 3\n#define PYBIND11_VERSION_MINOR 1\n#define PYBIND11_VERSION_MICRO 0\n// ALPHA = 0xA, BETA = 0xB, GAMMA = 0xC (release candidate), FINAL = 0xF (stable release)\n// - The release level is set to \"alpha\" for development versions.\n//   Use 0xA0 (LEVEL=0xA, SERIAL=0) for development versions.\n// - For stable releases, set the serial to 0.\n#define PYBIND11_VERSION_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA\n#define PYBIND11_VERSION_RELEASE_SERIAL 0\n// String version of (micro, release level, release serial), e.g.: 0a0, 0b1, 0rc1, 0\n#define PYBIND11_VERSION_PATCH 0a0\n/* -- end version constants -- */\n\n#if !defined(Py_PACK_FULL_VERSION)\n// Stable API since Python 3.14.0a4\n#    define Py_PACK_FULL_VERSION(X, Y, Z, LEVEL, SERIAL)                                          \\\n        ((((X) & 0xff) << 24) | (((Y) & 0xff) << 16) | (((Z) & 0xff) << 8)                        \\\n         | (((LEVEL) & 0xf) << 4) | (((SERIAL) & 0xf) << 0))\n#endif\n// Version as a single 4-byte hex number, e.g. 0x030C04B5 == 3.12.4b5.\n#define PYBIND11_VERSION_HEX                                                                      \\\n    Py_PACK_FULL_VERSION(PYBIND11_VERSION_MAJOR,                                                  \\\n                         PYBIND11_VERSION_MINOR,                                                  \\\n                         PYBIND11_VERSION_MICRO,                                                  \\\n                         PYBIND11_VERSION_RELEASE_LEVEL,                                          \\\n                         PYBIND11_VERSION_RELEASE_SERIAL)\n\n#include \"pybind11_namespace_macros.h\"\n\n#if !(defined(_MSC_VER) && __cplusplus == 199711L)\n#    if __cplusplus >= 201402L\n#        define PYBIND11_CPP14\n#        if __cplusplus >= 201703L\n#            define PYBIND11_CPP17\n#            if __cplusplus >= 202002L\n#                define PYBIND11_CPP20\n// Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.\n#            endif\n#        endif\n#    endif\n#elif defined(_MSC_VER) && __cplusplus == 199711L\n// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully\n// implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3\n// or newer.\n#    if _MSVC_LANG >= 201402L\n#        define PYBIND11_CPP14\n#        if _MSVC_LANG > 201402L\n#            define PYBIND11_CPP17\n#            if _MSVC_LANG >= 202002L\n#                define PYBIND11_CPP20\n#            endif\n#        endif\n#    endif\n#endif\n\n// These PYBIND11_HAS_... macros are consolidated in pybind11/detail/common.h\n// to simplify backward compatibility handling for users (e.g., via #ifdef checks):\n#define PYBIND11_HAS_TYPE_CASTER_STD_FUNCTION_SPECIALIZATIONS 1\n#define PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT 1\n#define PYBIND11_HAS_CPP_CONDUIT 1\n#define PYBIND11_HAS_NATIVE_ENUM 1\n\n#if defined(PYBIND11_CPP17) && defined(__has_include)\n#    if __has_include(<filesystem>)\n#        define PYBIND11_HAS_FILESYSTEM 1\n#    elif __has_include(<experimental/filesystem>)\n#        define PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM 1\n#    endif\n#endif\n\n#if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1920)) // See PR #5968\n#    define PYBIND11_STD_LAUNDER std::launder\n#    define PYBIND11_HAS_STD_LAUNDER 1\n#else\n#    define PYBIND11_STD_LAUNDER\n#    define PYBIND11_HAS_STD_LAUNDER 0\n#endif\n\n#if defined(PYBIND11_CPP20)\n#    define PYBIND11_CONSTINIT constinit\n#    define PYBIND11_DTOR_CONSTEXPR constexpr\n#else\n#    define PYBIND11_CONSTINIT\n#    define PYBIND11_DTOR_CONSTEXPR\n#endif\n\n#if defined(PYBIND11_CPP20) && defined(__has_include) && __has_include(<barrier>)\n#    define PYBIND11_HAS_STD_BARRIER 1\n#endif\n\n// Compiler version assertions\n#if defined(__INTEL_COMPILER)\n#    if __INTEL_COMPILER < 1800\n#        error pybind11 requires Intel C++ compiler v18 or newer\n#    elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)\n#        error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.\n#    endif\n/* The following pragma cannot be pop'ed:\n   https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */\n#    pragma warning disable 2196 // warning #2196: routine is both \"inline\" and \"noinline\"\n#elif defined(__clang__) && !defined(__apple_build_version__)\n#    if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)\n#        error pybind11 requires clang 3.3 or newer\n#    endif\n#elif defined(__clang__)\n// Apple changes clang version macros to its Xcode version; the first Xcode release based on\n// (upstream) clang 3.3 was Xcode 5:\n#    if __clang_major__ < 5\n#        error pybind11 requires Xcode/clang 5.0 or newer\n#    endif\n#elif defined(__GNUG__)\n#    if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)\n#        error pybind11 requires gcc 4.8 or newer\n#    endif\n#elif defined(_MSC_VER)\n#    if _MSC_VER < 1910\n#        error pybind11 2.10+ requires MSVC 2017 or newer\n#    endif\n#endif\n\n#if !defined(PYBIND11_EXPORT)\n#    if defined(WIN32) || defined(_WIN32)\n#        define PYBIND11_EXPORT __declspec(dllexport)\n#    else\n#        define PYBIND11_EXPORT __attribute__((visibility(\"default\")))\n#    endif\n#endif\n\n// For CUDA, GCC7, GCC8:\n// PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.\n// When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.\n// However, the measured shared-library size saving when using noinline are only\n// 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,\n// the default under pybind11/tests).\n#if !defined(PYBIND11_NOINLINE_FORCED)                                                            \\\n    && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))\n#    define PYBIND11_NOINLINE_DISABLED\n#endif\n\n// The PYBIND11_NOINLINE macro is for function DEFINITIONS.\n// In contrast, FORWARD DECLARATIONS should never use this macro:\n// https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions\n#if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.\n#    define PYBIND11_NOINLINE inline\n#elif defined(_MSC_VER)\n#    define PYBIND11_NOINLINE __declspec(noinline) inline\n#else\n#    define PYBIND11_NOINLINE __attribute__((noinline)) inline\n#endif\n\n#if defined(_MSC_VER)\n#    define PYBIND11_ALWAYS_INLINE __forceinline\n#elif defined(__GNUC__)\n#    define PYBIND11_ALWAYS_INLINE __attribute__((__always_inline__)) inline\n#else\n#    define PYBIND11_ALWAYS_INLINE inline\n#endif\n\n#if defined(__MINGW32__)\n// For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared\n// whether it is used or not\n#    define PYBIND11_DEPRECATED(reason)\n#elif defined(PYBIND11_CPP14)\n#    define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]\n#else\n#    define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))\n#endif\n\n#if defined(PYBIND11_CPP17)\n#    define PYBIND11_MAYBE_UNUSED [[maybe_unused]]\n#elif defined(_MSC_VER) && !defined(__clang__)\n#    define PYBIND11_MAYBE_UNUSED\n#else\n#    define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))\n#endif\n\n// https://en.cppreference.com/w/c/chrono/localtime\n#if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)\n#    define __STDC_WANT_LIB_EXT1__\n#endif\n\n#ifdef __has_include\n// std::optional (but including it in c++14 mode isn't allowed)\n#    if defined(PYBIND11_CPP17) && __has_include(<optional>)\n#        define PYBIND11_HAS_OPTIONAL 1\n#    endif\n// std::experimental::optional (but not allowed in c++11 mode)\n#    if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \\\n                                 !__has_include(<optional>))\n#        define PYBIND11_HAS_EXP_OPTIONAL 1\n#    endif\n// std::variant\n#    if defined(PYBIND11_CPP17) && __has_include(<variant>)\n#        define PYBIND11_HAS_VARIANT 1\n#    endif\n#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)\n#    define PYBIND11_HAS_OPTIONAL 1\n#    define PYBIND11_HAS_VARIANT 1\n#endif\n\n#if defined(PYBIND11_CPP17)                                                                       \\\n    && ((defined(__has_include) && __has_include(<string_view>)) || defined(_MSC_VER))\n#    define PYBIND11_HAS_STRING_VIEW 1\n#endif\n\n#if (defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)\n#    define PYBIND11_SIMPLE_GIL_MANAGEMENT\n#endif\n\n#include <cstddef>\n#include <cstring>\n#include <exception>\n#include <forward_list>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <typeindex>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#if defined(__has_include)\n#    if __has_include(<version>)\n#        include <version>\n#    endif\n#endif\n\n// For libc++, the exceptions should be exported,\n// otherwise, the exception translation would be incorrect.\n// IMPORTANT: This code block must stay BELOW the #include <exception> above (see PR #5390).\n#if !defined(PYBIND11_EXPORT_EXCEPTION)\n#    if defined(_LIBCPP_EXCEPTION)\n#        define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT\n#    else\n#        define PYBIND11_EXPORT_EXCEPTION\n#    endif\n#endif\n\n// Must be after including <version> or one of the other headers specified by the standard\n#if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L\n#    define PYBIND11_HAS_U8STRING 1\n#endif\n\n#if defined(PYBIND11_CPP20) && defined(__cpp_lib_span) && __cpp_lib_span >= 202002L\n#    define PYBIND11_HAS_SPAN 1\n#endif\n\n// See description of PR #4246:\n#if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG)                       \\\n    && !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)\n#    define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF\n#endif\n\n// Slightly faster code paths are available when PYBIND11_HAS_SUBINTERPRETER_SUPPORT is *not*\n// defined, so avoid defining it for implementations that do not support subinterpreters. However,\n// defining it unnecessarily is not expected to break anything.\n// This can be overridden by the user with -DPYBIND11_HAS_SUBINTERPRETER_SUPPORT=1 or 0\n#ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n#    if PY_VERSION_HEX >= 0x030C0000 && !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)\n#        define PYBIND11_HAS_SUBINTERPRETER_SUPPORT 1\n#    endif\n#else\n#    if PYBIND11_HAS_SUBINTERPRETER_SUPPORT == 0\n#        undef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n#    endif\n#endif\n\n// 3.13 Compatibility\n#if 0x030D0000 <= PY_VERSION_HEX\n#    define PYBIND11_TYPE_IS_TYPE_HINT \"typing.TypeIs\"\n#    define PYBIND11_CAPSULE_TYPE_TYPE_HINT \"types.CapsuleType\"\n#else\n#    define PYBIND11_TYPE_IS_TYPE_HINT \"typing_extensions.TypeIs\"\n#    define PYBIND11_CAPSULE_TYPE_TYPE_HINT \"typing_extensions.CapsuleType\"\n#endif\n\n// 3.12 Compatibility\n#if 0x030C0000 <= PY_VERSION_HEX\n#    define PYBIND11_BUFFER_TYPE_HINT \"collections.abc.Buffer\"\n#else\n#    define PYBIND11_BUFFER_TYPE_HINT \"typing_extensions.Buffer\"\n#endif\n\n// 3.11 Compatibility\n#if 0x030B0000 <= PY_VERSION_HEX\n#    define PYBIND11_NEVER_TYPE_HINT \"typing.Never\"\n#else\n#    define PYBIND11_NEVER_TYPE_HINT \"typing_extensions.Never\"\n#endif\n\n// 3.10 Compatibility\n#if 0x030A0000 <= PY_VERSION_HEX\n#    define PYBIND11_TYPE_GUARD_TYPE_HINT \"typing.TypeGuard\"\n#else\n#    define PYBIND11_TYPE_GUARD_TYPE_HINT \"typing_extensions.TypeGuard\"\n#endif\n\n// #define PYBIND11_STR_LEGACY_PERMISSIVE\n// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject\n//             (probably surprising and never documented, but this was the\n//             legacy behavior until and including v2.6.x). As a side-effect,\n//             pybind11::isinstance<str>() is true for both pybind11::str and\n//             pybind11::bytes.\n// If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and\n//               pybind11::isinstance<str>() is true only for pybind11::str.\n//               However, for Python 2 only (!), the pybind11::str caster\n//               implicitly decoded bytes to PyUnicodeObject. This was to ease\n//               the transition from the legacy behavior to the non-permissive\n//               behavior.\n\n/// Compatibility macros for Python 2 / Python 3 versions TODO: remove\n#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)\n#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check\n#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION\n#define PYBIND11_BYTES_CHECK PyBytes_Check\n#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString\n#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize\n#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize\n#define PYBIND11_BYTES_AS_STRING PyBytes_AsString\n#define PYBIND11_BYTES_SIZE PyBytes_Size\n#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)\n// In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,\n// while CPython only considers the existence of `nb_index`/`__index__`.\n#if !defined(PYPY_VERSION)\n#    define PYBIND11_INDEX_CHECK(o) PyIndex_Check(o)\n#else\n#    define PYBIND11_INDEX_CHECK(o) hasattr(o, \"__index__\")\n#endif\n#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)\n#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))\n#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))\n#define PYBIND11_BYTES_NAME \"bytes\"\n#define PYBIND11_STRING_NAME \"str\"\n#define PYBIND11_SLICE_OBJECT PyObject\n#define PYBIND11_FROM_STRING PyUnicode_FromString\n#define PYBIND11_STR_TYPE ::pybind11::str\n#define PYBIND11_BOOL_ATTR \"__bool__\"\n#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)\n#define PYBIND11_BUILTINS_MODULE \"builtins\"\n// Providing a separate declaration to make Clang's -Wmissing-prototypes happy.\n// See comment for PYBIND11_MODULE below for why this is marked \"maybe unused\".\n#define PYBIND11_PLUGIN_DECL(name)                                                                \\\n    extern \"C\" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name();\n#define PYBIND11_PLUGIN_IMPL(name)                                                                \\\n    PYBIND11_PLUGIN_DECL(name)                                                                    \\\n    extern \"C\" PYBIND11_EXPORT PyObject *PyInit_##name()\n\n#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code\n#define PYBIND11_STRINGIFY(x) #x\n#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)\n#define PYBIND11_CONCAT(first, second) first##second\n#define PYBIND11_ENSURE_INTERNALS_READY                                                           \\\n    {                                                                                             \\\n        pybind11::detail::get_internals_pp_manager().unref();                                     \\\n        pybind11::detail::get_internals();                                                        \\\n    }\n\n#if !defined(GRAALVM_PYTHON)\n#    define PYBIND11_PYCFUNCTION_GET_DOC(func) ((func)->m_ml->ml_doc)\n#    define PYBIND11_PYCFUNCTION_SET_DOC(func, doc)                                               \\\n        do {                                                                                      \\\n            (func)->m_ml->ml_doc = (doc);                                                         \\\n        } while (0)\n#else\n#    define PYBIND11_PYCFUNCTION_GET_DOC(func) (GraalPyCFunction_GetDoc((PyObject *) (func)))\n#    define PYBIND11_PYCFUNCTION_SET_DOC(func, doc)                                               \\\n        do {                                                                                      \\\n            GraalPyCFunction_SetDoc((PyObject *) (func), (doc));                                  \\\n        } while (0)\n#endif\n\n#define PYBIND11_CHECK_PYTHON_VERSION                                                             \\\n    {                                                                                             \\\n        const char *compiled_ver                                                                  \\\n            = PYBIND11_TOSTRING(PY_MAJOR_VERSION) \".\" PYBIND11_TOSTRING(PY_MINOR_VERSION);        \\\n        const char *runtime_ver = Py_GetVersion();                                                \\\n        size_t len = std::strlen(compiled_ver);                                                   \\\n        if (std::strncmp(runtime_ver, compiled_ver, len) != 0                                     \\\n            || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {                            \\\n            PyErr_Format(PyExc_ImportError,                                                       \\\n                         \"Python version mismatch: module was compiled for Python %s, \"           \\\n                         \"but the interpreter version is incompatible: %s.\",                      \\\n                         compiled_ver,                                                            \\\n                         runtime_ver);                                                            \\\n            return nullptr;                                                                       \\\n        }                                                                                         \\\n    }\n\n#define PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \\\n    catch (pybind11::error_already_set & e) {                                                     \\\n        pybind11::raise_from(e, PyExc_ImportError, \"initialization failed\");                      \\\n    }                                                                                             \\\n    catch (const std::exception &e) {                                                             \\\n        ::pybind11::set_error(PyExc_ImportError, e.what());                                       \\\n    }\n\n/** \\rst\n    ***Deprecated in favor of PYBIND11_MODULE***\n\n    This macro creates the entry point that will be invoked when the Python interpreter\n    imports a plugin library. Please create a `module_` in the function body and return\n    the pointer to its underlying Python object at the end.\n\n    .. code-block:: cpp\n\n        PYBIND11_PLUGIN(example) {\n            pybind11::module_ m(\"example\", \"pybind11 example plugin\");\n            /// Set up bindings here\n            return m.ptr();\n        }\n\\endrst */\n#define PYBIND11_PLUGIN(name)                                                                     \\\n    PYBIND11_DEPRECATED(\"PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE\")                     \\\n    static PyObject *pybind11_init();                                                             \\\n    PYBIND11_PLUGIN_IMPL(name) {                                                                  \\\n        PYBIND11_CHECK_PYTHON_VERSION                                                             \\\n        PYBIND11_ENSURE_INTERNALS_READY                                                           \\\n        try {                                                                                     \\\n            return pybind11_init();                                                               \\\n        }                                                                                         \\\n        PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \\\n        return nullptr;                                                                           \\\n    }                                                                                             \\\n    PyObject *pybind11_init()\n\n// this push is for the next several macros\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wgnu-zero-variadic-macro-arguments\")\n\n/**\nCreate a PyInit_ function for this module.\n\nNote that this is run once for each (sub-)interpreter the module is imported into, including\npossibly concurrently.  The PyModuleDef is allowed to be static, but the PyObject* resulting from\nPyModuleDef_Init should be treated like any other PyObject (so not shared across interpreters).\n */\n#define PYBIND11_MODULE_PYINIT(name, ...)                                                         \\\n    static int PYBIND11_CONCAT(pybind11_exec_, name)(PyObject *);                                 \\\n    PYBIND11_PLUGIN_IMPL(name) {                                                                  \\\n        PYBIND11_CHECK_PYTHON_VERSION                                                             \\\n        pybind11::detail::ensure_internals();                                                     \\\n        static ::pybind11::detail::slots_array mod_def_slots = ::pybind11::detail::init_slots(    \\\n            &PYBIND11_CONCAT(pybind11_exec_, name), ##__VA_ARGS__);                               \\\n        static PyModuleDef def{/* m_base */ PyModuleDef_HEAD_INIT,                                \\\n                               /* m_name */ PYBIND11_TOSTRING(name),                              \\\n                               /* m_doc */ nullptr,                                               \\\n                               /* m_size */ 0,                                                    \\\n                               /* m_methods */ nullptr,                                           \\\n                               /* m_slots */ mod_def_slots.data(),                                \\\n                               /* m_traverse */ nullptr,                                          \\\n                               /* m_clear */ nullptr,                                             \\\n                               /* m_free */ nullptr};                                             \\\n        return PyModuleDef_Init(&def);                                                            \\\n    }\n\n#define PYBIND11_MODULE_EXEC(name, variable)                                                      \\\n    static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &);                     \\\n    int PYBIND11_CONCAT(pybind11_exec_, name)(PyObject * pm) {                                    \\\n        try {                                                                                     \\\n            pybind11::detail::ensure_internals();                                                 \\\n            auto m = pybind11::reinterpret_borrow<::pybind11::module_>(pm);                       \\\n            if (!pybind11::detail::get_cached_module(m.attr(\"__spec__\").attr(\"name\"))) {          \\\n                PYBIND11_CONCAT(pybind11_init_, name)(m);                                         \\\n                pybind11::detail::cache_completed_module(m);                                      \\\n            }                                                                                     \\\n            return 0;                                                                             \\\n        }                                                                                         \\\n        PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \\\n        return -1;                                                                                \\\n    }                                                                                             \\\n    void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_                                \\\n                                               & variable) // NOLINT(bugprone-macro-parentheses)\n\n/** \\rst\n    This macro creates the entry point that will be invoked when the Python interpreter\n    imports an extension module. The module name is given as the first argument and it\n    should not be in quotes. The second macro argument defines a variable of type\n    ``py::module_`` which can be used to initialize the module.\n\n    The entry point is marked as \"maybe unused\" to aid dead-code detection analysis:\n    since the entry point is typically only looked up at runtime and not referenced\n    during translation, it would otherwise appear as unused (\"dead\") code.\n\n    .. code-block:: cpp\n\n        PYBIND11_MODULE(example, m) {\n            m.doc() = \"pybind11 example module\";\n\n            // Add bindings here\n            m.def(\"foo\", []() {\n                return \"Hello, World!\";\n            });\n        }\n\n    The third and subsequent macro arguments are optional (available since 2.13.0), and\n    can be used to mark the extension module as supporting various Python features.\n\n    - ``mod_gil_not_used()``\n    - ``multiple_interpreters::per_interpreter_gil()``\n    - ``multiple_interpreters::shared_gil()``\n    - ``multiple_interpreters::not_supported()``\n\n    .. code-block:: cpp\n\n        PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {\n            m.doc() = \"pybind11 example module safe to run without the GIL\";\n            m.def(\"foo\", []() {\n                return \"Hello, Free-threaded World!\";\n            });\n        }\n\n\\endrst */\n#define PYBIND11_MODULE(name, variable, ...)                                                      \\\n    PYBIND11_MODULE_PYINIT(name, ##__VA_ARGS__)                                                   \\\n    PYBIND11_MODULE_EXEC(name, variable)\n\n// pop gnu-zero-variadic-macro-arguments\nPYBIND11_WARNING_POP\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nusing ssize_t = Py_ssize_t;\nusing size_t = std::size_t;\n\ntemplate <typename IntType>\ninline ssize_t ssize_t_cast(const IntType &val) {\n    static_assert(sizeof(IntType) <= sizeof(ssize_t), \"Implicit narrowing is not permitted.\");\n    return static_cast<ssize_t>(val);\n}\n\n/// Approach used to cast a previously unknown C++ instance into a Python object\nenum class return_value_policy : uint8_t {\n    /** This is the default return value policy, which falls back to the policy\n        return_value_policy::take_ownership when the return value is a pointer.\n        Otherwise, it uses return_value::move or return_value::copy for rvalue\n        and lvalue references, respectively. See below for a description of what\n        all of these different policies do. */\n    automatic = 0,\n\n    /** As above, but use policy return_value_policy::reference when the return\n        value is a pointer. This is the default conversion policy for function\n        arguments when calling Python functions manually from C++ code (i.e. via\n        handle::operator()). You probably won't need to use this. */\n    automatic_reference,\n\n    /** Reference an existing object (i.e. do not create a new copy) and take\n        ownership. Python will call the destructor and delete operator when the\n        object's reference count reaches zero. Undefined behavior ensues when\n        the C++ side does the same.. */\n    take_ownership,\n\n    /** Create a new copy of the returned object, which will be owned by\n        Python. This policy is comparably safe because the lifetimes of the two\n        instances are decoupled. */\n    copy,\n\n    /** Use std::move to move the return value contents into a new instance\n        that will be owned by Python. This policy is comparably safe because the\n        lifetimes of the two instances (move source and destination) are\n        decoupled. */\n    move,\n\n    /** Reference an existing object, but do not take ownership. The C++ side\n        is responsible for managing the object's lifetime and deallocating it\n        when it is no longer used. Warning: undefined behavior will ensue when\n        the C++ side deletes an object that is still referenced and used by\n        Python. */\n    reference,\n\n    /** This policy only applies to methods and properties. It references the\n        object without taking ownership similar to the above\n        return_value_policy::reference policy. In contrast to that policy, the\n        function or property's implicit this argument (called the parent) is\n        considered to be the owner of the return value (the child).\n        pybind11 then couples the lifetime of the parent to the child via a\n        reference relationship that ensures that the parent cannot be garbage\n        collected while Python is still using the child. More advanced\n        variations of this scheme are also possible using combinations of\n        return_value_policy::reference and the keep_alive call policy */\n    reference_internal\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nstatic constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }\n\n// Returns the size as a multiple of sizeof(void *), rounded up.\nstatic constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }\n\n/**\n * The space to allocate for simple layout instance holders (see below) in multiple of the size of\n * a pointer (e.g.  2 means 16 bytes on 64-bit architectures).  The default is the minimum required\n * to holder either a std::unique_ptr or std::shared_ptr (which is almost always\n * sizeof(std::shared_ptr<T>)).\n */\nconstexpr size_t instance_simple_holder_in_ptrs() {\n    static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),\n                  \"pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs\");\n    return size_in_ptrs(sizeof(std::shared_ptr<int>));\n}\n\n// Forward declarations\nstruct type_info;\nstruct value_and_holder;\n\nstruct nonsimple_values_and_holders {\n    void **values_and_holders;\n    uint8_t *status;\n};\n\n/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')\nstruct instance {\n    PyObject_HEAD\n    /// Storage for pointers and holder; see simple_layout, below, for a description\n    union {\n        void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];\n        nonsimple_values_and_holders nonsimple;\n    };\n    /// Weak references\n    PyObject *weakrefs;\n    /// If true, the pointer is owned which means we're free to manage it with a holder.\n    bool owned : 1;\n    /**\n     * An instance has two possible value/holder layouts.\n     *\n     * Simple layout (when this flag is true), means the `simple_value_holder` is set with a\n     * pointer and the holder object governing that pointer, i.e. [val1*][holder].  This layout is\n     * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the\n     * type's holder will fit in the default space (which is large enough to hold either a\n     * std::unique_ptr or std::shared_ptr).\n     *\n     * Non-simple layout applies when using custom holders that require more space than\n     * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is\n     * used on the python side.  Non-simple layout allocates the required amount of memory to have\n     * multiple bound C++ classes as parents.  Under this layout, `nonsimple.values_and_holders` is\n     * set to a pointer to allocated space of the required space to hold a sequence of value\n     * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.\n     * [val1*][holder1][val2*][holder2]...[bb...]  where each [block] is rounded up to a multiple\n     * of `sizeof(void *)`.  `nonsimple.status` is, for convenience, a pointer to the beginning of\n     * the [bb...] block (but not independently allocated).\n     *\n     * Status bits indicate whether the associated holder is constructed (&\n     * status_holder_constructed) and whether the value pointer is registered (&\n     * status_instance_registered) in `registered_instances`.\n     */\n    bool simple_layout : 1;\n    /// For simple layout, tracks whether the holder has been constructed\n    bool simple_holder_constructed : 1;\n    /// For simple layout, tracks whether the instance is registered in `registered_instances`\n    bool simple_instance_registered : 1;\n    /// If true, get_internals().patients has an entry for this object\n    bool has_patients : 1;\n    /// If true, this Python object needs to be kept alive for the lifetime of the C++ value.\n    bool is_alias : 1;\n\n    /// Initializes all of the above type/values/holders data (but not the instance values\n    /// themselves)\n    void allocate_layout();\n\n    /// Destroys/deallocates all of the above\n    void deallocate_layout();\n\n    /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`\n    /// omitted).  Returns a default-constructed (with `.inst = nullptr`) object on failure if\n    /// `throw_if_missing` is false.\n    value_and_holder get_value_and_holder(const type_info *find_type = nullptr,\n                                          bool throw_if_missing = true);\n\n    /// Bit values for the non-simple status flags\n    static constexpr uint8_t status_holder_constructed = 1;\n    static constexpr uint8_t status_instance_registered = 2;\n};\n\nstatic_assert(std::is_standard_layout<instance>::value,\n              \"Internal error: `pybind11::detail::instance` is not standard layout!\");\n\n// Some older compilers (e.g. gcc 9.4.0) require\n//     static_assert(always_false<T>::value, \"...\");\n// instead of\n//     static_assert(false, \"...\");\n// to trigger the static_assert() in a template only if it is actually instantiated.\ntemplate <typename>\nstruct always_false : std::false_type {};\n\n/// from __cpp_future__ import (convenient aliases from C++14/17)\n#if defined(PYBIND11_CPP14)\nusing std::conditional_t;\nusing std::enable_if_t;\nusing std::remove_cv_t;\nusing std::remove_reference_t;\n#else\ntemplate <bool B, typename T = void>\nusing enable_if_t = typename std::enable_if<B, T>::type;\ntemplate <bool B, typename T, typename F>\nusing conditional_t = typename std::conditional<B, T, F>::type;\ntemplate <typename T>\nusing remove_cv_t = typename std::remove_cv<T>::type;\ntemplate <typename T>\nusing remove_reference_t = typename std::remove_reference<T>::type;\n#endif\n\n#if defined(PYBIND11_CPP20) && defined(__cpp_lib_remove_cvref)\nusing std::remove_cvref;\nusing std::remove_cvref_t;\n#else\ntemplate <class T>\nstruct remove_cvref {\n    using type = remove_cv_t<remove_reference_t<T>>;\n};\ntemplate <class T>\nusing remove_cvref_t = typename remove_cvref<T>::type;\n#endif\n\n/// Example usage: is_same_ignoring_cvref<T, PyObject *>::value\ntemplate <typename T, typename U>\nusing is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;\n\n/// Index sequences\n#if defined(PYBIND11_CPP14)\nusing std::index_sequence;\nusing std::make_index_sequence;\n#else\ntemplate <size_t...>\nstruct index_sequence {};\n// Comments about the algorithm below.\n//\n// Credit: This is based on an algorithm by taocpp here:\n//    https://github.com/taocpp/sequences/blob/main/include/tao/seq/make_integer_sequence.hpp\n// but significantly simplified.\n//\n// We build up a sequence S by repeatedly doubling its length and sometimes adding 1 to the end.\n// E.g. if the current S is 0...3, then we either go to 0...7 or 0...8 on the next pass.\n// The goal is to end with S = 0...N-1.\n// The key insight is that the times we need to add an additional digit to S correspond\n// exactly to the 1's in the binary representation of the number N.\n//\n// Invariants:\n// - digit is a power of 2\n// - N_digit_is_1 is whether N's binary representation has a 1 in that digit's position.\n// - end <= N\n// - S is 0...end-1.\n// - if digit > 0, end * digit * 2 <= N < (end+1) * digit * 2\n//\n// The process starts with digit > N, end = 0, and S is empty.\n// The process concludes with digit=0, in which case, end == N and S is 0...N-1.\n\ntemplate <size_t digit, bool N_digit_is_1, size_t N, size_t end, size_t... S> // N_digit_is_1=false\nstruct make_index_sequence_impl\n    : make_index_sequence_impl<digit / 2, (N & (digit / 2)) != 0, N, 2 * end, S..., (S + end)...> {\n};\ntemplate <size_t digit, size_t N, size_t end, size_t... S>\nstruct make_index_sequence_impl<digit, true, N, end, S...>\n    : make_index_sequence_impl<digit / 2,\n                               (N & (digit / 2)) != 0,\n                               N,\n                               2 * end + 1,\n                               S...,\n                               (S + end)...,\n                               2 * end> {};\ntemplate <size_t N, size_t end, size_t... S>\nstruct make_index_sequence_impl<0, false, N, end, S...> {\n    using type = index_sequence<S...>;\n};\nconstexpr size_t next_power_of_2(size_t N) { return N == 0 ? 1 : next_power_of_2(N >> 1) << 1; }\ntemplate <size_t N>\nusing make_index_sequence =\n    typename make_index_sequence_impl<next_power_of_2(N), false, N, 0>::type;\n#endif\n\n/// Make an index sequence of the indices of true arguments\ntemplate <typename ISeq, size_t, bool...>\nstruct select_indices_impl {\n    using type = ISeq;\n};\ntemplate <size_t... IPrev, size_t I, bool B, bool... Bs>\nstruct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>\n    : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,\n                          I + 1,\n                          Bs...> {};\ntemplate <bool... Bs>\nusing select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;\n\n/// Backports of std::bool_constant and std::negation to accommodate older compilers\ntemplate <bool B>\nusing bool_constant = std::integral_constant<bool, B>;\ntemplate <typename T>\nstruct negation : bool_constant<!T::value> {};\n\n// PGI/Intel cannot detect operator delete with the \"compatible\" void_t impl, so\n// using the new one (C++14 defect, so generally works on newer compilers, even\n// if not in C++17 mode)\n#if defined(__PGIC__) || defined(__INTEL_COMPILER)\ntemplate <typename...>\nusing void_t = void;\n#else\ntemplate <typename...>\nstruct void_t_impl {\n    using type = void;\n};\ntemplate <typename... Ts>\nusing void_t = typename void_t_impl<Ts...>::type;\n#endif\n\n/// Compile-time all/any/none of that check the boolean value of all template types\n#if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))\ntemplate <class... Ts>\nusing all_of = bool_constant<(Ts::value && ...)>;\ntemplate <class... Ts>\nusing any_of = bool_constant<(Ts::value || ...)>;\n#elif !defined(_MSC_VER)\ntemplate <bool...>\nstruct bools {};\ntemplate <class... Ts>\nusing all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;\ntemplate <class... Ts>\nusing any_of = negation<all_of<negation<Ts>...>>;\n#else\n// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit\n// at a slight loss of compilation efficiency).\ntemplate <class... Ts>\nusing all_of = std::conjunction<Ts...>;\ntemplate <class... Ts>\nusing any_of = std::disjunction<Ts...>;\n#endif\ntemplate <class... Ts>\nusing none_of = negation<any_of<Ts...>>;\n\ntemplate <class T, template <class> class... Predicates>\nusing satisfies_all_of = all_of<Predicates<T>...>;\ntemplate <class T, template <class> class... Predicates>\nusing satisfies_any_of = any_of<Predicates<T>...>;\ntemplate <class T, template <class> class... Predicates>\nusing satisfies_none_of = none_of<Predicates<T>...>;\n\n/// Strip the class from a method type\ntemplate <typename T>\nstruct remove_class {};\ntemplate <typename C, typename R, typename... A>\nstruct remove_class<R (C::*)(A...)> {\n    using type = R(A...);\n};\ntemplate <typename C, typename R, typename... A>\nstruct remove_class<R (C::*)(A...) const> {\n    using type = R(A...);\n};\n#ifdef __cpp_noexcept_function_type\ntemplate <typename C, typename R, typename... A>\nstruct remove_class<R (C::*)(A...) noexcept> {\n    using type = R(A...);\n};\ntemplate <typename C, typename R, typename... A>\nstruct remove_class<R (C::*)(A...) const noexcept> {\n    using type = R(A...);\n};\n#endif\n/// Helper template to strip away type modifiers\ntemplate <typename T>\nstruct intrinsic_type {\n    using type = T;\n};\ntemplate <typename T>\nstruct intrinsic_type<const T> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T>\nstruct intrinsic_type<T *> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T>\nstruct intrinsic_type<T &> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T>\nstruct intrinsic_type<T &&> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T, size_t N>\nstruct intrinsic_type<const T[N]> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T, size_t N>\nstruct intrinsic_type<T[N]> {\n    using type = typename intrinsic_type<T>::type;\n};\ntemplate <typename T>\nusing intrinsic_t = typename intrinsic_type<T>::type;\n\n/// Helper type to replace 'void' in some expressions\nstruct void_type {};\n\n/// Helper template which holds a list of types\ntemplate <typename...>\nstruct type_list {};\n\n/// Compile-time integer sum\n#ifdef __cpp_fold_expressions\ntemplate <typename... Ts>\nconstexpr size_t constexpr_sum(Ts... ns) {\n    return (0 + ... + size_t{ns});\n}\n#else\nconstexpr size_t constexpr_sum() { return 0; }\ntemplate <typename T, typename... Ts>\nconstexpr size_t constexpr_sum(T n, Ts... ns) {\n    return size_t{n} + constexpr_sum(ns...);\n}\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(constexpr_impl)\n/// Implementation details for constexpr functions\nconstexpr int first(int i) { return i; }\ntemplate <typename T, typename... Ts>\nconstexpr int first(int i, T v, Ts... vs) {\n    return v ? i : first(i + 1, vs...);\n}\n\nconstexpr int last(int /*i*/, int result) { return result; }\ntemplate <typename T, typename... Ts>\nconstexpr int last(int i, int result, T v, Ts... vs) {\n    return last(i + 1, v ? i : result, vs...);\n}\nPYBIND11_NAMESPACE_END(constexpr_impl)\n\n/// Return the index of the first type in Ts which satisfies Predicate<T>.\n/// Returns sizeof...(Ts) if none match.\ntemplate <template <typename> class Predicate, typename... Ts>\nconstexpr int constexpr_first() {\n    return constexpr_impl::first(0, Predicate<Ts>::value...);\n}\n\n/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.\ntemplate <template <typename> class Predicate, typename... Ts>\nconstexpr int constexpr_last() {\n    return constexpr_impl::last(0, -1, Predicate<Ts>::value...);\n}\n\n/// Return the Nth element from the parameter pack\ntemplate <size_t N, typename T, typename... Ts>\nstruct pack_element {\n    using type = typename pack_element<N - 1, Ts...>::type;\n};\ntemplate <typename T, typename... Ts>\nstruct pack_element<0, T, Ts...> {\n    using type = T;\n};\n\n/// Return the one and only type which matches the predicate, or Default if none match.\n/// If more than one type matches the predicate, fail at compile-time.\ntemplate <template <typename> class Predicate, typename Default, typename... Ts>\nstruct exactly_one {\n    static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);\n    static_assert(found <= 1, \"Found more than one type matching the predicate\");\n\n    static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;\n    using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;\n};\ntemplate <template <typename> class P, typename Default>\nstruct exactly_one<P, Default> {\n    using type = Default;\n};\n\ntemplate <template <typename> class Predicate, typename Default, typename... Ts>\nusing exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;\n\n/// Defer the evaluation of type T until types Us are instantiated\ntemplate <typename T, typename... /*Us*/>\nstruct deferred_type {\n    using type = T;\n};\ntemplate <typename T, typename... Us>\nusing deferred_t = typename deferred_type<T, Us...>::type;\n\n/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,\n/// unlike `std::is_base_of`)\ntemplate <typename Base, typename Derived>\nusing is_strict_base_of\n    = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;\n\n/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived\n/// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so\n/// we need to check `is_same` as well.\ntemplate <typename Base, typename Derived>\nusing is_accessible_base_of\n    = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)\n                    && std::is_convertible<Derived *, Base *>::value>;\n\ntemplate <template <typename...> class Base>\nstruct is_template_base_of_impl {\n    template <typename... Us>\n    static std::true_type check(Base<Us...> *);\n    static std::false_type check(...);\n};\n\n/// Check if a template is the base of a type. For example:\n/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything\ntemplate <template <typename...> class Base, typename T>\n// Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.\n// See also: https://github.com/pybind/pybind11/pull/3741\n#if !defined(_MSC_VER)\nusing is_template_base_of\n    = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));\n#else\nstruct is_template_base_of\n    : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)){};\n#endif\n\n/// Check if T is an instantiation of the template `Class`. For example:\n/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.\ntemplate <template <typename...> class Class, typename T>\nstruct is_instantiation : std::false_type {};\ntemplate <template <typename...> class Class, typename... Us>\nstruct is_instantiation<Class, Class<Us...>> : std::true_type {};\n\n/// Check if T is std::shared_ptr<U> where U can be anything\ntemplate <typename T>\nusing is_shared_ptr = is_instantiation<std::shared_ptr, T>;\n\n/// Check if T looks like an input iterator\ntemplate <typename T, typename = void>\nstruct is_input_iterator : std::false_type {};\ntemplate <typename T>\nstruct is_input_iterator<T,\n                         void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>\n    : std::true_type {};\n\ntemplate <typename T>\nusing is_function_pointer\n    = bool_constant<std::is_pointer<T>::value\n                    && std::is_function<typename std::remove_pointer<T>::type>::value>;\n\ntemplate <typename F>\nstruct strip_function_object {\n    // If you are encountering an\n    // 'error: name followed by \"::\" must be a class or namespace name'\n    // with the Intel compiler and a noexcept function here,\n    // try to use noexcept(true) instead of plain noexcept.\n    using type = typename remove_class<decltype(&F::operator())>::type;\n};\n\n// Extracts the function signature from a function, function pointer or lambda.\ntemplate <typename Function, typename F = remove_reference_t<Function>>\nusing function_signature_t = conditional_t<\n    std::is_function<F>::value,\n    F,\n    typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,\n                           std::remove_pointer<F>,\n                           strip_function_object<F>>::type>;\n\n/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member\n/// pointer.  Note that this can catch all sorts of other things, too; this is intended to be used\n/// in a place where passing a lambda makes sense.\ntemplate <typename T>\nusing is_lambda = satisfies_none_of<remove_reference_t<T>,\n                                    std::is_function,\n                                    std::is_pointer,\n                                    std::is_member_pointer>;\n\n// [workaround(intel)] Internal error on fold expression\n/// Apply a function over each element of a parameter pack\n#if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)\n// Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)\n#    define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)\n#else\nusing expand_side_effects = bool[];\n#    define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)                                                 \\\n        (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// C++ bindings of builtin Python exceptions\nclass PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {\npublic:\n    using std::runtime_error::runtime_error;\n    /// Set the error using the Python C API\n    virtual void set_error() const = 0;\n};\n\n#define PYBIND11_RUNTIME_EXCEPTION(name, type)                                                    \\\n    class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception {                             \\\n    public:                                                                                       \\\n        using builtin_exception::builtin_exception;                                               \\\n        name() : name(\"\") {}                                                                      \\\n        void set_error() const override { PyErr_SetString(type, what()); }                        \\\n    };\n\nPYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)\nPYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)\nPYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)\nPYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)\nPYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)\nPYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)\nPYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)\nPYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)\nPYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or\n                                                           /// handle::call fail due to a type\n                                                           /// casting error\nPYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally\n\n[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {\n    assert(!PyErr_Occurred());\n    throw std::runtime_error(reason);\n}\n[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {\n    assert(!PyErr_Occurred());\n    throw std::runtime_error(reason);\n}\n\ntemplate <typename T, typename SFINAE = void>\nstruct format_descriptor {};\n\ntemplate <typename T>\nstruct format_descriptor<\n    T,\n    detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {\n    static constexpr const char c = 'O';\n    static constexpr const char value[2] = {c, '\\0'};\n    static std::string format() { return std::string(1, c); }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n// Returns the index of the given type in the type char array below, and in the list in numpy.h\n// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;\n// complex float,double,long double.  Note that the long double types only participate when long\n// double is actually longer than double (it isn't under MSVC).\n// NB: not only the string below but also complex.h and numpy.h rely on this order.\ntemplate <typename T, typename SFINAE = void>\nstruct is_fmt_numeric {\n    static constexpr bool value = false;\n};\ntemplate <typename T>\nstruct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {\n    static constexpr bool value = true;\n    static constexpr int index\n        = std::is_same<T, bool>::value\n              ? 0\n              : 1\n                    + (std::is_integral<T>::value\n                           ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value\n                           : 8\n                                 + (std::is_same<T, double>::value        ? 1\n                                    : std::is_same<T, long double>::value ? 2\n                                                                          : 0));\n};\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename T>\nstruct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {\n    static constexpr const char c = \"?bBhHiIqQfdg\"[detail::is_fmt_numeric<T>::index];\n    static constexpr const char value[2] = {c, '\\0'};\n    static std::string format() { return std::string(1, c); }\n};\n\n#if !defined(PYBIND11_CPP17)\n\ntemplate <typename T>\nconstexpr const char\n    format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];\n\n#endif\n\n/// RAII wrapper that temporarily clears any Python error state\nstruct error_scope {\n    PyObject *type, *value, *trace;\n    error_scope() { PyErr_Fetch(&type, &value, &trace); }\n    error_scope(const error_scope &) = delete;\n    error_scope &operator=(const error_scope &) = delete;\n    ~error_scope() { PyErr_Restore(type, value, trace); }\n};\n\n/// Dummy destructor wrapper that can be used to expose classes with a private destructor\nstruct nodelete {\n    template <typename T>\n    void operator()(T *) {}\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <typename... Args>\nstruct overload_cast_impl {\n    template <typename Return>\n    constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {\n        return pf;\n    }\n\n    template <typename Return, typename Class>\n    constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept\n        -> decltype(pmf) {\n        return pmf;\n    }\n\n    template <typename Return, typename Class>\n    constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept\n        -> decltype(pmf) {\n        return pmf;\n    }\n};\nPYBIND11_NAMESPACE_END(detail)\n\n// overload_cast requires variable templates: C++14\n#if defined(PYBIND11_CPP14)\n#    define PYBIND11_OVERLOAD_CAST 1\n/// Syntax sugar for resolving overloaded function pointers:\n///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)\n///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)\ntemplate <typename... Args>\nstatic constexpr detail::overload_cast_impl<Args...> overload_cast{};\n#endif\n\n/// Const member function selector for overload_cast\n///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)\n///  - sweet:   overload_cast<Arg>(&Class::func, const_)\nstatic constexpr auto const_ = std::true_type{};\n\n#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:\ntemplate <typename... Args>\nstruct overload_cast {\n    static_assert(detail::deferred_t<std::false_type, Args...>::value,\n                  \"pybind11::overload_cast<...> requires compiling in C++14 mode\");\n};\n#endif // overload_cast\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from\n// any standard container (or C-style array) supporting std::begin/std::end, any singleton\n// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.\ntemplate <typename T>\nclass any_container {\n    std::vector<T> v;\n\npublic:\n    any_container() = default;\n\n    // Can construct from a pair of iterators\n    template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>\n    any_container(It first, It last) : v(first, last) {}\n\n    // Implicit conversion constructor from any arbitrary container type\n    // with values convertible to T\n    template <typename Container,\n              typename = enable_if_t<\n                  std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),\n                                      T>::value>>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}\n\n    // initializer_list's aren't deducible, so don't get matched by the above template;\n    // we need this to explicitly allow implicit conversion from one:\n    template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>\n    any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}\n\n    // Avoid copying if given an rvalue vector of the correct type.\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    any_container(std::vector<T> &&v) : v(std::move(v)) {}\n\n    // Moves the vector out of an rvalue any_container\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator std::vector<T> &&() && { return std::move(v); }\n\n    // Dereferencing obtains a reference to the underlying vector\n    std::vector<T> &operator*() { return v; }\n    const std::vector<T> &operator*() const { return v; }\n\n    // -> lets you call methods on the underlying vector\n    std::vector<T> *operator->() { return &v; }\n    const std::vector<T> *operator->() const { return &v; }\n};\n\n// Forward-declaration; see detail/class.h\nstd::string get_fully_qualified_tp_name(PyTypeObject *);\n\ntemplate <typename T>\ninline static std::shared_ptr<T>\ntry_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {\n// Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.\n// Use at your own risk!\n// See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular\n// the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.\n#if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)\n    return holder_value_ptr->weak_from_this().lock();\n#else\n    try {\n        return holder_value_ptr->shared_from_this();\n    } catch (const std::bad_weak_ptr &) {\n        return nullptr;\n    }\n#endif\n}\n\n// For silencing \"unused\" compiler warnings in special situations.\ntemplate <typename... Args>\n#if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017\nconstexpr\n#endif\n    inline void silence_unused_warnings(Args &&...) {\n}\n\n// MSVC warning C4100: Unreferenced formal parameter\n#if defined(_MSC_VER) && _MSC_VER <= 1916\n#    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)                                         \\\n        detail::silence_unused_warnings(__VA_ARGS__)\n#else\n#    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)\n#endif\n\n// GCC -Wunused-but-set-parameter  All GCC versions (as of July 2021).\n#if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)\n#    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)                       \\\n        detail::silence_unused_warnings(__VA_ARGS__)\n#else\n#    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)\n#endif\n\n#if defined(__clang__)                                                                            \\\n    && (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point    \\\n                                            available. */                                         \\\n        || (__clang_major__ >= 7                                                                  \\\n            && __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */   \\\n    )\n#    define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING\n// Example:\n// tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite\n// being returned by name [-Werror,-Wreturn-std-move]\n//     m.def(\"args_function\", [](py::args args) -> py::tuple { return args; });\n//                                                                    ^~~~\n// test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying\n//     m.def(\"args_function\", [](py::args args) -> py::tuple { return args; });\n//                                                                    ^~~~\n//                                                                    std::move(args)\n#endif\n\n// Pybind offers detailed error messages by default for all builts that are debug (through the\n// negation of NDEBUG). This can also be manually enabled by users, for any builds, through\n// defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those\n// who are writing (as opposed to merely using) libraries that use pybind11.\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)\n#    define PYBIND11_DETAILED_ERROR_MESSAGES\n#endif\n\n// CPython 3.11+ provides Py_TPFLAGS_MANAGED_DICT, but PyPy3.11 does not, see PR #5508.\n#if PY_VERSION_HEX < 0x030B0000 || defined(PYPY_VERSION)\n#    define PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/cpp_conduit.h",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#pragma once\n\n#include <pybind11/pytypes.h>\n\n#include \"common.h\"\n#include \"internals.h\"\n\n#include <typeinfo>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Forward declaration needed here: Refactoring opportunity.\nextern \"C\" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *);\n\ninline bool type_is_managed_by_our_internals(PyTypeObject *type_obj) {\n#if defined(PYPY_VERSION)\n    auto &internals = get_internals();\n    return bool(internals.registered_types_py.find(type_obj)\n                != internals.registered_types_py.end());\n#else\n    return (type_obj->tp_new == pybind11_object_new);\n#endif\n}\n\ninline bool is_instance_method_of_type(PyTypeObject *type_obj, PyObject *attr_name) {\n    PyObject *descr = _PyType_Lookup(type_obj, attr_name);\n    return ((descr != nullptr) && PyInstanceMethod_Check(descr));\n}\n\ninline object try_get_cpp_conduit_method(PyObject *obj) {\n    if (PyType_Check(obj)) {\n        return object();\n    }\n    PyTypeObject *type_obj = Py_TYPE(obj);\n    str attr_name(\"_pybind11_conduit_v1_\");\n    bool assumed_to_be_callable = false;\n    if (type_is_managed_by_our_internals(type_obj)) {\n        if (!is_instance_method_of_type(type_obj, attr_name.ptr())) {\n            return object();\n        }\n        assumed_to_be_callable = true;\n    }\n    PyObject *method = PyObject_GetAttr(obj, attr_name.ptr());\n    if (method == nullptr) {\n        PyErr_Clear();\n        return object();\n    }\n    if (!assumed_to_be_callable && PyCallable_Check(method) == 0) {\n        Py_DECREF(method);\n        return object();\n    }\n    return reinterpret_steal<object>(method);\n}\n\ninline void *try_raw_pointer_ephemeral_from_cpp_conduit(handle src,\n                                                        const std::type_info *cpp_type_info) {\n    object method = try_get_cpp_conduit_method(src.ptr());\n    if (method) {\n        capsule cpp_type_info_capsule(const_cast<void *>(static_cast<const void *>(cpp_type_info)),\n                                      typeid(std::type_info).name());\n        object cpp_conduit = method(bytes(PYBIND11_PLATFORM_ABI_ID),\n                                    cpp_type_info_capsule,\n                                    bytes(\"raw_pointer_ephemeral\"));\n        if (isinstance<capsule>(cpp_conduit)) {\n            return reinterpret_borrow<capsule>(cpp_conduit).get_pointer();\n        }\n    }\n    return nullptr;\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/descr.h",
    "content": "/*\n    pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n#if !defined(_MSC_VER)\n#    define PYBIND11_DESCR_CONSTEXPR static constexpr\n#else\n#    define PYBIND11_DESCR_CONSTEXPR const\n#endif\n\n/* Concatenate type signatures at compile time */\ntemplate <size_t N, typename... Ts>\nstruct descr {\n    char text[N + 1]{'\\0'};\n\n    constexpr descr() = default;\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}\n\n    template <size_t... Is>\n    constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\\0'} {}\n\n    template <typename... Chars>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\\0'} {}\n\n    static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {\n        return {{&typeid(Ts)..., nullptr}};\n    }\n};\n\ntemplate <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>\nconstexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,\n                                                   const descr<N2, Ts2...> &b,\n                                                   index_sequence<Is1...>,\n                                                   index_sequence<Is2...>) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);\n    return {a.text[Is1]..., b.text[Is2]...};\n}\n\ntemplate <size_t N1, size_t N2, typename... Ts1, typename... Ts2>\nconstexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,\n                                                   const descr<N2, Ts2...> &b) {\n    return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());\n}\n\ntemplate <size_t N>\nconstexpr descr<N - 1> const_name(char const (&text)[N]) {\n    return descr<N - 1>(text);\n}\nconstexpr descr<0> const_name(char const (&)[1]) { return {}; }\n\ntemplate <size_t Rem, size_t... Digits>\nstruct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};\ntemplate <size_t... Digits>\nstruct int_to_str<0, Digits...> {\n    // WARNING: This only works with C++17 or higher.\n    static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);\n};\n\n// Ternary description (like std::conditional)\ntemplate <bool B, size_t N1, size_t N2>\nconstexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {\n    return const_name(text1);\n}\ntemplate <bool B, size_t N1, size_t N2>\nconstexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {\n    return const_name(text2);\n}\n\ntemplate <bool B, typename T1, typename T2>\nconstexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {\n    return d;\n}\ntemplate <bool B, typename T1, typename T2>\nconstexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {\n    return d;\n}\n\ntemplate <size_t Size>\nauto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {\n    return int_to_str<Size / 10, Size % 10>::digits;\n}\n\ntemplate <typename Type>\nconstexpr descr<1, Type> const_name() {\n    return {'%'};\n}\n\n// Use a different name based on whether the parameter is used as input or output\ntemplate <size_t N1, size_t N2>\nconstexpr descr<N1 + N2 + 1> io_name(char const (&text1)[N1], char const (&text2)[N2]) {\n    return const_name(\"@\") + const_name(text1) + const_name(\"@\") + const_name(text2)\n           + const_name(\"@\");\n}\n\n// Ternary description for io_name (like the numeric type_caster)\ntemplate <bool B, size_t N1, size_t N2, size_t N3, size_t N4>\nconstexpr enable_if_t<B, descr<N1 + N2 + 1>>\nio_name(char const (&text1)[N1], char const (&text2)[N2], char const (&)[N3], char const (&)[N4]) {\n    return io_name(text1, text2);\n}\n\ntemplate <bool B, size_t N1, size_t N2, size_t N3, size_t N4>\nconstexpr enable_if_t<!B, descr<N3 + N4 + 1>>\nio_name(char const (&)[N1], char const (&)[N2], char const (&text3)[N3], char const (&text4)[N4]) {\n    return io_name(text3, text4);\n}\n\n// If \"_\" is defined as a macro, py::detail::_ cannot be provided.\n// It is therefore best to use py::detail::const_name universally.\n// This block is for backward compatibility only.\n// (The const_name code is repeated to avoid introducing a \"_\" #define ourselves.)\n#ifndef _\n#    define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY\ntemplate <size_t N>\nconstexpr descr<N - 1> _(char const (&text)[N]) {\n    return const_name<N>(text);\n}\ntemplate <bool B, size_t N1, size_t N2>\nconstexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {\n    return const_name<B, N1, N2>(text1, text2);\n}\ntemplate <bool B, size_t N1, size_t N2>\nconstexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {\n    return const_name<B, N1, N2>(text1, text2);\n}\ntemplate <bool B, typename T1, typename T2>\nconstexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {\n    return const_name<B, T1, T2>(d1, d2);\n}\ntemplate <bool B, typename T1, typename T2>\nconstexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {\n    return const_name<B, T1, T2>(d1, d2);\n}\n\ntemplate <size_t Size>\nauto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {\n    return const_name<Size>();\n}\ntemplate <typename Type>\nconstexpr descr<1, Type> _() {\n    return const_name<Type>();\n}\n#endif // #ifndef _\n\nconstexpr descr<0> concat() { return {}; }\nconstexpr descr<0> union_concat() { return {}; }\n\ntemplate <size_t N, typename... Ts>\nconstexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {\n    return descr;\n}\n\ntemplate <size_t N, typename... Ts>\nconstexpr descr<N, Ts...> union_concat(const descr<N, Ts...> &descr) {\n    return descr;\n}\n\ntemplate <size_t N1, size_t N2, typename... Ts1, typename... Ts2>\nconstexpr descr<N1 + N2 + 3, Ts1..., Ts2...> operator|(const descr<N1, Ts1...> &a,\n                                                       const descr<N2, Ts2...> &b) {\n    return a + const_name(\" | \") + b;\n}\n\n#ifdef __cpp_fold_expressions\ntemplate <size_t N1, size_t N2, typename... Ts1, typename... Ts2>\nconstexpr descr<N1 + N2 + 2, Ts1..., Ts2...> operator,(const descr<N1, Ts1...> &a,\n                                                       const descr<N2, Ts2...> &b) {\n    return a + const_name(\", \") + b;\n}\n\ntemplate <size_t N, typename... Ts, typename... Args>\nconstexpr auto concat(const descr<N, Ts...> &d, const Args &...args) {\n    return (d, ..., args);\n}\n\ntemplate <size_t N, typename... Ts, typename... Args>\nconstexpr auto union_concat(const descr<N, Ts...> &d, const Args &...args) {\n    return (d | ... | args);\n}\n\n#else\ntemplate <size_t N, typename... Ts, typename... Args>\nconstexpr auto concat(const descr<N, Ts...> &d, const Args &...args)\n    -> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {\n    return d + const_name(\", \") + concat(args...);\n}\n\ntemplate <size_t N, typename... Ts, typename... Args>\nconstexpr auto union_concat(const descr<N, Ts...> &d, const Args &...args)\n    -> decltype(std::declval<descr<N + 3, Ts...>>() + union_concat(args...)) {\n    return d + const_name(\" | \") + union_concat(args...);\n}\n\n#endif\n\ntemplate <size_t N, typename... Ts>\nconstexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {\n    return const_name(\"{\") + descr + const_name(\"}\");\n}\n\ntemplate <size_t N, typename... Ts>\nconstexpr descr<N + 4, Ts...> arg_descr(const descr<N, Ts...> &descr) {\n    return const_name(\"@^\") + descr + const_name(\"@!\");\n}\n\ntemplate <size_t N, typename... Ts>\nconstexpr descr<N + 4, Ts...> return_descr(const descr<N, Ts...> &descr) {\n    return const_name(\"@$\") + descr + const_name(\"@!\");\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"common.h\"\n\n#include <type_traits>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename To, typename From, typename SFINAE = void>\nstruct dynamic_raw_ptr_cast_is_possible : std::false_type {};\n\ntemplate <typename To, typename From>\nstruct dynamic_raw_ptr_cast_is_possible<\n    To,\n    From,\n    detail::enable_if_t<!std::is_same<To, void>::value && std::is_polymorphic<From>::value>>\n    : std::true_type {};\n\ntemplate <typename To,\n          typename From,\n          detail::enable_if_t<!dynamic_raw_ptr_cast_is_possible<To, From>::value, int> = 0>\nTo *dynamic_raw_ptr_cast_if_possible(From * /*ptr*/) {\n    return nullptr;\n}\n\ntemplate <typename To,\n          typename From,\n          detail::enable_if_t<dynamic_raw_ptr_cast_is_possible<To, From>::value, int> = 0>\nTo *dynamic_raw_ptr_cast_if_possible(From *ptr) {\n    return dynamic_cast<To *>(ptr);\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/exception_translation.h",
    "content": "/*\n    pybind11/detail/exception_translation.h: means to translate C++ exceptions to Python exceptions\n\n    Copyright (c) 2024 The Pybind Development Team.\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"common.h\"\n#include \"internals.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Apply all the extensions translators from a list\n// Return true if one of the translators completed without raising an exception\n// itself. Return of false indicates that if there are other translators\n// available, they should be tried.\ninline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {\n    auto last_exception = std::current_exception();\n\n    for (auto &translator : translators) {\n        try {\n            translator(last_exception);\n            return true;\n        } catch (...) {\n            last_exception = std::current_exception();\n        }\n    }\n    return false;\n}\n\ninline void try_translate_exceptions() {\n    /* When an exception is caught, give each registered exception\n        translator a chance to translate it to a Python exception. First\n        all module-local translators will be tried in reverse order of\n        registration. If none of the module-locale translators handle\n        the exception (or there are no module-locale translators) then\n        the global translators will be tried, also in reverse order of\n        registration.\n\n        A translator may choose to do one of the following:\n\n        - catch the exception and call py::set_error()\n            to set a standard (or custom) Python exception, or\n        - do nothing and let the exception fall through to the next translator, or\n        - delegate translation to the next translator by throwing a new type of exception.\n        */\n\n    bool handled = with_exception_translators(\n        [&](std::forward_list<ExceptionTranslator> &exception_translators,\n            std::forward_list<ExceptionTranslator> &local_exception_translators) {\n            if (detail::apply_exception_translators(local_exception_translators)) {\n                return true;\n            }\n            if (detail::apply_exception_translators(exception_translators)) {\n                return true;\n            }\n            return false;\n        });\n\n    if (!handled) {\n        set_error(PyExc_SystemError, \"Exception escaped from default exception translator!\");\n    }\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/function_record_pyobject.h",
    "content": "// Copyright (c) 2024-2025 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n// For background see the description of PR google/pybind11clif#30099.\n\n#pragma once\n\n#include <pybind11/attr.h>\n#include <pybind11/conduit/pybind11_platform_abi_id.h>\n#include <pybind11/pytypes.h>\n\n#include \"common.h\"\n\n#include <cstring>\n#include <utility>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nstruct function_record_PyObject {\n    PyObject_HEAD\n    function_record *cpp_func_rec;\n};\n\nPYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)\n\nPyObject *tp_new_impl(PyTypeObject *type, PyObject *args, PyObject *kwds);\nPyObject *tp_alloc_impl(PyTypeObject *type, Py_ssize_t nitems);\nint tp_init_impl(PyObject *self, PyObject *args, PyObject *kwds);\nvoid tp_dealloc_impl(PyObject *self);\nvoid tp_free_impl(void *self);\n\nstatic PyObject *reduce_ex_impl(PyObject *self, PyObject *, PyObject *);\n\nstatic PyMethodDef tp_methods_impl[]\n    = {{\"__reduce_ex__\",\n        // reduce_ex_impl is a PyCFunctionWithKeywords, but PyMethodDef\n        // requires a PyCFunction. The cast through void* is safe and\n        // idiomatic with METH_KEYWORDS, and it successfully sidesteps\n        // unhelpful compiler warnings.\n        // NOLINTNEXTLINE(bugprone-casting-through-void)\n        reinterpret_cast<PyCFunction>(reinterpret_cast<void *>(reduce_ex_impl)),\n        METH_VARARGS | METH_KEYWORDS,\n        nullptr},\n       {nullptr, nullptr, 0, nullptr}};\n\n// Python 3.12+ emits a DeprecationWarning for heap types whose tp_name does\n// not contain a dot ('.') and that lack a __module__ attribute. For pybind11's\n// internal function_record type, we do not have an actual module object to\n// attach, so we cannot use PyType_FromModuleAndSpec (introduced in Python 3.9)\n// to set __module__ automatically.\n//\n// As a workaround, we define a \"qualified\" type name that includes a dummy\n// module name (PYBIND11_DUMMY_MODULE_NAME). This is non‑idiomatic but avoids\n// the deprecation warning, and results in reprs like\n//\n//     <class 'pybind11_builtins.pybind11_detail_function_record_...'>\n//\n// even though no real pybind11_builtins module exists. If pybind11 gains an\n// actual module object in the future, this code should switch to\n// PyType_FromModuleAndSpec for Python 3.9+ and drop the dummy module\n// workaround.\n//\n// Note that this name is versioned.\n#define PYBIND11_DETAIL_FUNCTION_RECORD_TP_PLAINNAME                                              \\\n    \"pybind11_detail_function_record_\" PYBIND11_DETAIL_FUNCTION_RECORD_ABI_ID                     \\\n    \"_\" PYBIND11_PLATFORM_ABI_ID\nconstexpr char tp_plainname_impl[] = PYBIND11_DETAIL_FUNCTION_RECORD_TP_PLAINNAME;\nconstexpr char tp_qualname_impl[]\n    = PYBIND11_DUMMY_MODULE_NAME \".\" PYBIND11_DETAIL_FUNCTION_RECORD_TP_PLAINNAME;\n\nPYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)\n\nstatic PyType_Slot function_record_PyType_Slots[] = {\n    {Py_tp_dealloc,\n     reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_dealloc_impl)},\n    {Py_tp_methods,\n     reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_methods_impl)},\n    {Py_tp_init, reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_init_impl)},\n    {Py_tp_alloc, reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_alloc_impl)},\n    {Py_tp_new, reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_new_impl)},\n    {Py_tp_free, reinterpret_cast<void *>(function_record_PyTypeObject_methods::tp_free_impl)},\n    {0, nullptr}};\n\nstatic PyType_Spec function_record_PyType_Spec\n    = {function_record_PyTypeObject_methods::tp_qualname_impl,\n       sizeof(function_record_PyObject),\n       0,\n       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE,\n       function_record_PyType_Slots};\n\ninline PyTypeObject *get_function_record_PyTypeObject() {\n    PYBIND11_LOCK_INTERNALS(get_internals());\n    PyTypeObject *&py_type_obj = detail::get_local_internals().function_record_py_type;\n    if (!py_type_obj) {\n        PyObject *py_obj = PyType_FromSpec(&function_record_PyType_Spec);\n        if (py_obj == nullptr) {\n            throw error_already_set();\n        }\n        py_type_obj = reinterpret_cast<PyTypeObject *>(py_obj);\n    }\n    return py_type_obj;\n}\n\ninline bool is_function_record_PyObject(PyObject *obj) {\n    if (PyType_Check(obj) != 0) {\n        return false;\n    }\n    PyTypeObject *obj_type = Py_TYPE(obj);\n\n    PyTypeObject *frtype = get_function_record_PyTypeObject();\n\n    // Fast path (pointer comparison).\n    if (obj_type == frtype) {\n        return true;\n    }\n    // This works across extension modules. Note that tp_name is versioned.\n    if (strcmp(obj_type->tp_name, function_record_PyTypeObject_methods::tp_qualname_impl) == 0\n        || strcmp(obj_type->tp_name, function_record_PyTypeObject_methods::tp_plainname_impl)\n               == 0) {\n        return true;\n    }\n    return false;\n}\n\ninline function_record *function_record_ptr_from_PyObject(PyObject *obj) {\n    if (is_function_record_PyObject(obj)) {\n        return (reinterpret_cast<detail::function_record_PyObject *>(obj))->cpp_func_rec;\n    }\n    return nullptr;\n}\n\ninline object function_record_PyObject_New() {\n    auto *py_func_rec = PyObject_New(function_record_PyObject, get_function_record_PyTypeObject());\n    if (py_func_rec == nullptr) {\n        throw error_already_set();\n    }\n    py_func_rec->cpp_func_rec = nullptr; // For clarity/purity. Redundant in practice.\n    return reinterpret_steal<object>(reinterpret_cast<PyObject *>(py_func_rec));\n}\n\nPYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)\n\n// Guard against accidents & oversights, in particular when porting to future Python versions.\ninline PyObject *tp_new_impl(PyTypeObject *, PyObject *, PyObject *) {\n    pybind11_fail(\"UNEXPECTED CALL OF function_record_PyTypeObject_methods::tp_new_impl\");\n    // return nullptr; // Unreachable.\n}\n\ninline PyObject *tp_alloc_impl(PyTypeObject *, Py_ssize_t) {\n    pybind11_fail(\"UNEXPECTED CALL OF function_record_PyTypeObject_methods::tp_alloc_impl\");\n    // return nullptr; // Unreachable.\n}\n\ninline int tp_init_impl(PyObject *, PyObject *, PyObject *) {\n    pybind11_fail(\"UNEXPECTED CALL OF function_record_PyTypeObject_methods::tp_init_impl\");\n    // return -1; // Unreachable.\n}\n\ninline void tp_free_impl(void *) {\n    pybind11_fail(\"UNEXPECTED CALL OF function_record_PyTypeObject_methods::tp_free_impl\");\n}\n\ninline PyObject *reduce_ex_impl(PyObject *self, PyObject *, PyObject *) {\n    // Deliberately ignoring the arguments for simplicity (expected is `protocol: int`).\n    const function_record *rec = function_record_ptr_from_PyObject(self);\n    if (rec == nullptr) {\n        pybind11_fail(\n            \"FATAL: function_record_PyTypeObject reduce_ex_impl(): cannot obtain cpp_func_rec.\");\n    }\n    if (rec->name != nullptr && rec->name[0] != '\\0' && rec->scope\n        && PyModule_Check(rec->scope.ptr()) != 0) {\n        object scope_module = get_scope_module(rec->scope);\n        if (scope_module) {\n            auto builtins = reinterpret_borrow<dict>(PyEval_GetBuiltins());\n            auto builtins_eval = builtins[\"eval\"];\n            auto reconstruct_args = make_tuple(str(\"__import__('importlib').import_module('\")\n                                               + scope_module + str(\"')\"));\n            return make_tuple(std::move(builtins_eval), std::move(reconstruct_args))\n                .release()\n                .ptr();\n        }\n    }\n    set_error(PyExc_RuntimeError, repr(self) + str(\" is not pickleable.\"));\n    return nullptr;\n}\n\nPYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/function_ref.h",
    "content": "/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n//===- llvm/ADT/STLFunctionalExtras.h - Extras for <functional> -*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains a header-only class template that provides functionality\n// similar to std::function but with non-owning semantics. It is a template-only\n// implementation that requires no additional library linking.\n//\n//===----------------------------------------------------------------------===//\n\n/// An efficient, type-erasing, non-owning reference to a callable. This is\n/// intended for use as the type of a function parameter that is not used\n/// after the function in question returns.\n///\n/// This class does not own the callable, so it is not in general safe to store\n/// a FunctionRef.\n\n// pybind11: modified again from executorch::runtime::FunctionRef\n// - renamed back to function_ref\n// - use pybind11 enable_if_t, remove_cvref_t, and remove_reference_t\n// - lint suppressions\n\n// torch::executor: modified from llvm::function_ref\n// - renamed to FunctionRef\n// - removed LLVM_GSL_POINTER and LLVM_LIFETIME_BOUND macro uses\n// - use namespaced internal::remove_cvref_t\n\n#pragma once\n\n#include <pybind11/detail/common.h>\n\n#include <cstdint>\n#include <type_traits>\n#include <utility>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n//===----------------------------------------------------------------------===//\n//     Features from C++20\n//===----------------------------------------------------------------------===//\n\ntemplate <typename Fn>\nclass function_ref;\n\ntemplate <typename Ret, typename... Params>\nclass function_ref<Ret(Params...)> {\n    Ret (*callback)(intptr_t callable, Params... params) = nullptr;\n    intptr_t callable;\n\n    template <typename Callable>\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    static Ret callback_fn(intptr_t callable, Params... params) {\n        // NOLINTNEXTLINE(performance-no-int-to-ptr)\n        return (*reinterpret_cast<Callable *>(callable))(std::forward<Params>(params)...);\n    }\n\npublic:\n    function_ref() = default;\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    function_ref(std::nullptr_t) {}\n\n    template <typename Callable>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    function_ref(\n        Callable &&callable,\n        // This is not the copy-constructor.\n        enable_if_t<!std::is_same<remove_cvref_t<Callable>, function_ref>::value> * = nullptr,\n        // Functor must be callable and return a suitable type.\n        enable_if_t<\n            std::is_void<Ret>::value\n            || std::is_convertible<decltype(std::declval<Callable>()(std::declval<Params>()...)),\n                                   Ret>::value> * = nullptr)\n        : callback(callback_fn<remove_reference_t<Callable>>),\n          callable(reinterpret_cast<intptr_t>(&callable)) {}\n\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    Ret operator()(Params... params) const {\n        return callback(callable, std::forward<Params>(params)...);\n    }\n\n    explicit operator bool() const { return callback; }\n\n    bool operator==(const function_ref<Ret(Params...)> &Other) const {\n        return callable == Other.callable;\n    }\n};\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/holder_caster_foreign_helpers.h",
    "content": "/*\n    pybind11/detail/holder_caster_foreign_helpers.h: Logic to implement\n    set_foreign_holder() in copyable_ and movable_holder_caster.\n\n    Copyright (c) 2025 Hudson River Trading LLC <opensource@hudson-trading.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/gil.h>\n\n#include \"common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nstruct holder_caster_foreign_helpers {\n    struct py_deleter {\n        void operator()(const void *) const noexcept {\n            // Don't run the deleter if the interpreter has been shut down\n            if (Py_IsInitialized() == 0) {\n                return;\n            }\n            gil_scoped_acquire guard;\n            Py_DECREF(o);\n        }\n\n        PyObject *o;\n    };\n\n    template <typename type>\n    static auto set_via_shared_from_this(type *value, std::shared_ptr<type> *holder_out)\n        -> decltype(value->shared_from_this(), bool()) {\n        // object derives from enable_shared_from_this;\n        // try to reuse an existing shared_ptr if one is known\n        if (auto existing = try_get_shared_from_this(value)) {\n            *holder_out = std::static_pointer_cast<type>(existing);\n            return true;\n        }\n        return false;\n    }\n\n    template <typename type>\n    static bool set_via_shared_from_this(void *, std::shared_ptr<type> *) {\n        return false;\n    }\n\n    template <typename type>\n    static bool set_foreign_holder(handle src, type *value, std::shared_ptr<type> *holder_out) {\n        // We only support using std::shared_ptr<T> for foreign T, and\n        // it's done by creating a new shared_ptr control block that\n        // owns a reference to the original Python object.\n        if (value == nullptr) {\n            *holder_out = {};\n            return true;\n        }\n        if (set_via_shared_from_this(value, holder_out)) {\n            return true;\n        }\n        *holder_out = std::shared_ptr<type>(value, py_deleter{src.inc_ref().ptr()});\n        return true;\n    }\n\n    template <typename type>\n    static bool\n    set_foreign_holder(handle src, const type *value, std::shared_ptr<const type> *holder_out) {\n        std::shared_ptr<type> holder_mut;\n        if (set_foreign_holder(src, const_cast<type *>(value), &holder_mut)) {\n            *holder_out = holder_mut;\n            return true;\n        }\n        return false;\n    }\n\n    template <typename type>\n    static bool set_foreign_holder(handle, type *, ...) {\n        throw cast_error(\"Unable to cast foreign type to held instance -- \"\n                         \"only std::shared_ptr<T> is supported in this case\");\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/init.h",
    "content": "/*\n    pybind11/detail/init.h: init factory function implementation and support code.\n\n    Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"class.h\"\n#include \"using_smart_holder.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <>\nclass type_caster<value_and_holder> {\npublic:\n    bool load(handle h, bool) {\n        value = reinterpret_cast<value_and_holder *>(h.ptr());\n        return true;\n    }\n\n    template <typename>\n    using cast_op_type = value_and_holder &;\n    explicit operator value_and_holder &() { return *value; }\n    static constexpr auto name = const_name<value_and_holder>();\n\nprivate:\n    value_and_holder *value = nullptr;\n};\n\nPYBIND11_NAMESPACE_BEGIN(initimpl)\n\ninline void no_nullptr(const void *ptr) {\n    if (!ptr) {\n        throw type_error(\"pybind11::init(): factory function returned nullptr\");\n    }\n}\n\n// Implementing functions for all forms of py::init<...> and py::init(...)\ntemplate <typename Class>\nusing Cpp = typename Class::type;\ntemplate <typename Class>\nusing Alias = typename Class::type_alias;\ntemplate <typename Class>\nusing Holder = typename Class::holder_type;\n\ntemplate <typename Class>\nusing is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;\n\n// Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.\ntemplate <typename Class, enable_if_t<Class::has_alias, int> = 0>\nbool is_alias(Cpp<Class> *ptr) {\n    return dynamic_cast<Alias<Class> *>(ptr) != nullptr;\n}\n// Failing fallback version of the above for a no-alias class (always returns false)\ntemplate <typename /*Class*/>\nconstexpr bool is_alias(const void *) {\n    return false;\n}\n\n// Constructs and returns a new object; if the given arguments don't map to a constructor, we fall\n// back to brace aggregate initialization so that for aggregate initialization can be used with\n// py::init, e.g.  `py::init<int, int>` to initialize a `struct T { int a; int b; }`.  For\n// non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually\n// works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).\ntemplate <typename Class,\n          typename... Args,\n          detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>\ninline Class *construct_or_initialize(Args &&...args) {\n    return new Class(std::forward<Args>(args)...);\n}\ntemplate <typename Class,\n          typename... Args,\n          detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>\ninline Class *construct_or_initialize(Args &&...args) {\n    return new Class{std::forward<Args>(args)...};\n}\n\n// Attempts to constructs an alias using a `Alias(Cpp &&)` constructor.  This allows types with\n// an alias to provide only a single Cpp factory function as long as the Alias can be\n// constructed from an rvalue reference of the base Cpp type.  This means that Alias classes\n// can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to\n// inherit all the base class constructors.\ntemplate <typename Class>\nvoid construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,\n                              value_and_holder &v_h,\n                              Cpp<Class> &&base) {\n    v_h.value_ptr() = new Alias<Class>(std::move(base));\n}\ntemplate <typename Class>\n[[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,\n                                           value_and_holder &,\n                                           Cpp<Class> &&) {\n    throw type_error(\"pybind11::init(): unable to convert returned instance to required \"\n                     \"alias class: no `Alias<Class>(Class &&)` constructor available\");\n}\n\n// Error-generating fallback for factories that don't match one of the below construction\n// mechanisms.\ntemplate <typename Class>\nvoid construct(...) {\n    static_assert(!std::is_same<Class, Class>::value /* always false */,\n                  \"pybind11::init(): init function must return a compatible pointer, \"\n                  \"holder, or value\");\n}\n\n// Pointer return v1: the factory function returns a class pointer for a registered class.\n// If we don't need an alias (because this class doesn't have one, or because the final type is\n// inherited on the Python side) we can simply take over ownership.  Otherwise we need to try to\n// construct an Alias from the returned base instance.\ntemplate <typename Class>\nvoid construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);\n    no_nullptr(ptr);\n    if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {\n        // We're going to try to construct an alias by moving the cpp type.  Whether or not\n        // that succeeds, we still need to destroy the original cpp pointer (either the\n        // moved away leftover, if the alias construction works, or the value itself if we\n        // throw an error), but we can't just call `delete ptr`: it might have a special\n        // deleter, or might be shared_from_this.  So we construct a holder around it as if\n        // it was a normal instance, then steal the holder away into a local variable; thus\n        // the holder and destruction happens when we leave the C++ scope, and the holder\n        // class gets to handle the destruction however it likes.\n        v_h.value_ptr() = ptr;\n        v_h.set_instance_registered(true); // Trick to prevent init_instance from registering it\n        // DANGER ZONE BEGIN: exceptions will leave v_h in an invalid state.\n        v_h.type->init_instance(v_h.inst, nullptr);                        // Set up the holder\n        Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder\n        v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null\n        v_h.set_instance_registered(false);\n        // DANGER ZONE END.\n\n        construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));\n    } else {\n        // Otherwise the type isn't inherited, so we don't need an Alias\n        v_h.value_ptr() = ptr;\n    }\n}\n\n// Pointer return v2: a factory that always returns an alias instance ptr.  We simply take over\n// ownership of the pointer.\ntemplate <typename Class, enable_if_t<Class::has_alias, int> = 0>\nvoid construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {\n    no_nullptr(alias_ptr);\n    v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);\n}\n\n// Holder return: copy its pointer, and move or copy the returned holder into the new instance's\n// holder.  This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a\n// derived type (through those holder's implicit conversion from derived class holder\n// constructors).\ntemplate <typename Class, detail::enable_if_t<!is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);\n    auto *ptr = holder_helper<Holder<Class>>::get(holder);\n    no_nullptr(ptr);\n    // If we need an alias, check that the held pointer is actually an alias instance\n    if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {\n        throw type_error(\"pybind11::init(): construction failed: returned holder-wrapped instance \"\n                         \"is not an alias instance\");\n    }\n\n    // Cast away constness to store in void* storage.\n    // The value_and_holder storage is fundamentally untyped (void**), so we lose\n    // const-correctness here by design. The const qualifier will be restored\n    // when the pointer is later retrieved and cast back to the original type.\n    // This explicit const_cast makes the const-removal clearly visible.\n    v_h.value_ptr() = const_cast<void *>(static_cast<const void *>(ptr));\n    v_h.type->init_instance(v_h.inst, &holder);\n}\n\n// return-by-value version 1: returning a cpp class by value.  If the class has an alias and an\n// alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct\n// the alias from the base when needed (i.e. because of Python-side inheritance).  When we don't\n// need it, we simply move-construct the cpp value into a new instance.\ntemplate <typename Class>\nvoid construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);\n    static_assert(is_move_constructible<Cpp<Class>>::value,\n                  \"pybind11::init() return-by-value factory function requires a movable class\");\n    if (Class::has_alias && need_alias) {\n        construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));\n    } else {\n        v_h.value_ptr() = new Cpp<Class>(std::move(result));\n    }\n}\n\n// return-by-value version 2: returning a value of the alias type itself.  We move-construct an\n// Alias instance (even if no the python-side inheritance is involved).  The is intended for\n// cases where Alias initialization is always desired.\ntemplate <typename Class>\nvoid construct(value_and_holder &v_h, Alias<Class> &&result, bool) {\n    static_assert(\n        is_move_constructible<Alias<Class>>::value,\n        \"pybind11::init() return-by-alias-value factory function requires a movable alias class\");\n    v_h.value_ptr() = new Alias<Class>(std::move(result));\n}\n\ntemplate <typename T, typename D>\nsmart_holder init_smart_holder_from_unique_ptr(std::unique_ptr<T, D> &&unq_ptr,\n                                               bool void_cast_raw_ptr) {\n    void *void_ptr = void_cast_raw_ptr ? static_cast<void *>(unq_ptr.get()) : nullptr;\n    return smart_holder::from_unique_ptr(std::move(unq_ptr), void_ptr);\n}\n\ntemplate <typename Class,\n          typename D = std::default_delete<Cpp<Class>>,\n          detail::enable_if_t<is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h, std::unique_ptr<Cpp<Class>, D> &&unq_ptr, bool need_alias) {\n    PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);\n    auto *ptr = unq_ptr.get();\n    no_nullptr(ptr);\n    if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {\n        throw type_error(\"pybind11::init(): construction failed: returned std::unique_ptr pointee \"\n                         \"is not an alias instance\");\n    }\n    // Here and below: if the new object is a trampoline, the shared_from_this mechanism needs\n    // to be prevented from accessing the smart_holder vptr, because it does not keep the\n    // trampoline Python object alive. For types that don't inherit from enable_shared_from_this\n    // it does not matter if void_cast_raw_ptr is true or false, therefore it's not necessary\n    // to also inspect the type.\n    auto smhldr = init_smart_holder_from_unique_ptr(\n        std::move(unq_ptr), /*void_cast_raw_ptr*/ Class::has_alias && is_alias<Class>(ptr));\n    v_h.value_ptr() = ptr;\n    v_h.type->init_instance(v_h.inst, &smhldr);\n}\n\ntemplate <typename Class,\n          typename D = std::default_delete<Alias<Class>>,\n          detail::enable_if_t<is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h,\n               std::unique_ptr<Alias<Class>, D> &&unq_ptr,\n               bool /*need_alias*/) {\n    auto *ptr = unq_ptr.get();\n    no_nullptr(ptr);\n    auto smhldr\n        = init_smart_holder_from_unique_ptr(std::move(unq_ptr), /*void_cast_raw_ptr*/ true);\n    v_h.value_ptr() = ptr;\n    v_h.type->init_instance(v_h.inst, &smhldr);\n}\n\ntemplate <typename PtrType, typename Class>\nvoid construct_from_shared_ptr(value_and_holder &v_h,\n                               std::shared_ptr<PtrType> &&shd_ptr,\n                               bool need_alias) {\n    static_assert(std::is_same<PtrType, Cpp<Class>>::value\n                      || std::is_same<PtrType, const Cpp<Class>>::value,\n                  \"Expected (const) Cpp<Class> as shared_ptr pointee\");\n    auto *ptr = shd_ptr.get();\n    no_nullptr(ptr);\n    if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {\n        throw type_error(\"pybind11::init(): construction failed: returned std::shared_ptr pointee \"\n                         \"is not an alias instance\");\n    }\n    // Cast to non-const if needed, consistent with internal design\n    auto smhldr\n        = smart_holder::from_shared_ptr(std::const_pointer_cast<Cpp<Class>>(std::move(shd_ptr)));\n    v_h.value_ptr() = const_cast<Cpp<Class> *>(ptr);\n    v_h.type->init_instance(v_h.inst, &smhldr);\n}\n\ntemplate <typename Class, detail::enable_if_t<is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h, std::shared_ptr<Cpp<Class>> &&shd_ptr, bool need_alias) {\n    construct_from_shared_ptr<Cpp<Class>, Class>(v_h, std::move(shd_ptr), need_alias);\n}\n\ntemplate <typename Class, detail::enable_if_t<is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h,\n               std::shared_ptr<const Cpp<Class>> &&shd_ptr,\n               bool need_alias) {\n    construct_from_shared_ptr<const Cpp<Class>, Class>(v_h, std::move(shd_ptr), need_alias);\n}\n\ntemplate <typename Class, detail::enable_if_t<is_smart_holder<Holder<Class>>::value, int> = 0>\nvoid construct(value_and_holder &v_h,\n               std::shared_ptr<Alias<Class>> &&shd_ptr,\n               bool /*need_alias*/) {\n    auto *ptr = shd_ptr.get();\n    no_nullptr(ptr);\n    auto smhldr = smart_holder::from_shared_ptr(shd_ptr);\n    v_h.value_ptr() = ptr;\n    v_h.type->init_instance(v_h.inst, &smhldr);\n}\n\n// Implementing class for py::init<...>()\ntemplate <typename... Args>\nstruct constructor {\n    template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>\n    static void execute(Class &cl, const Extra &...extra) {\n        cl.def(\n            \"__init__\",\n            [](value_and_holder &v_h,\n               Args... args) { // NOLINT(performance-unnecessary-value-param)\n                v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n\n    template <\n        typename Class,\n        typename... Extra,\n        enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value, int>\n        = 0>\n    static void execute(Class &cl, const Extra &...extra) {\n        cl.def(\n            \"__init__\",\n            [](value_and_holder &v_h, Args... args) {\n                if (Py_TYPE(v_h.inst) == v_h.type->type) {\n                    v_h.value_ptr()\n                        = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);\n                } else {\n                    v_h.value_ptr()\n                        = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);\n                }\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n\n    template <\n        typename Class,\n        typename... Extra,\n        enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value, int>\n        = 0>\n    static void execute(Class &cl, const Extra &...extra) {\n        cl.def(\n            \"__init__\",\n            [](value_and_holder &v_h, Args... args) {\n                v_h.value_ptr()\n                    = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n};\n\n// Implementing class for py::init_alias<...>()\ntemplate <typename... Args>\nstruct alias_constructor {\n    template <\n        typename Class,\n        typename... Extra,\n        enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int>\n        = 0>\n    static void execute(Class &cl, const Extra &...extra) {\n        cl.def(\n            \"__init__\",\n            [](value_and_holder &v_h, Args... args) {\n                v_h.value_ptr()\n                    = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n};\n\n// Implementation class for py::init(Func) and py::init(Func, AliasFunc)\ntemplate <typename CFunc,\n          typename AFunc = void_type (*)(),\n          typename = function_signature_t<CFunc>,\n          typename = function_signature_t<AFunc>>\nstruct factory;\n\n// Specialization for py::init(Func)\ntemplate <typename Func, typename Return, typename... Args>\nstruct factory<Func, void_type (*)(), Return(Args...)> {\n    remove_reference_t<Func> class_factory;\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    factory(Func &&f) : class_factory(std::forward<Func>(f)) {}\n\n    // The given class either has no alias or has no separate alias factory;\n    // this always constructs the class itself.  If the class is registered with an alias\n    // type and an alias instance is needed (i.e. because the final type is a Python class\n    // inheriting from the C++ type) the returned value needs to either already be an alias\n    // instance, or the alias needs to be constructible from a `Class &&` argument.\n    template <typename Class, typename... Extra>\n    void execute(Class &cl, const Extra &...extra) && {\n#if defined(PYBIND11_CPP14)\n        cl.def(\n            \"__init__\",\n            [func = std::move(class_factory)]\n#else\n        auto &func = class_factory;\n        cl.def(\n            \"__init__\",\n            [func]\n#endif\n            (value_and_holder &v_h, Args... args) {\n                construct<Class>(\n                    v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n};\n\n// Specialization for py::init(Func, AliasFunc)\ntemplate <typename CFunc,\n          typename AFunc,\n          typename CReturn,\n          typename... CArgs,\n          typename AReturn,\n          typename... AArgs>\nstruct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {\n    static_assert(sizeof...(CArgs) == sizeof...(AArgs),\n                  \"pybind11::init(class_factory, alias_factory): class and alias factories \"\n                  \"must have identical argument signatures\");\n    static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,\n                  \"pybind11::init(class_factory, alias_factory): class and alias factories \"\n                  \"must have identical argument signatures\");\n\n    remove_reference_t<CFunc> class_factory;\n    remove_reference_t<AFunc> alias_factory;\n\n    factory(CFunc &&c, AFunc &&a)\n        : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}\n\n    // The class factory is called when the `self` type passed to `__init__` is the direct\n    // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.\n    template <typename Class, typename... Extra>\n    void execute(Class &cl, const Extra &...extra) && {\n        static_assert(Class::has_alias,\n                      \"The two-argument version of `py::init()` can \"\n                      \"only be used if the class has an alias\");\n#if defined(PYBIND11_CPP14)\n        cl.def(\n            \"__init__\",\n            [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]\n#else\n        auto &class_func = class_factory;\n        auto &alias_func = alias_factory;\n        cl.def(\n            \"__init__\",\n            [class_func, alias_func]\n#endif\n            (value_and_holder &v_h, CArgs... args) {\n                if (Py_TYPE(v_h.inst) == v_h.type->type) {\n                    // If the instance type equals the registered type we don't have inheritance,\n                    // so don't need the alias and can construct using the class function:\n                    construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);\n                } else {\n                    construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);\n                }\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n};\n\n/// Set just the C++ state. Same as `__init__`.\ntemplate <typename Class, typename T>\nvoid setstate(value_and_holder &v_h, T &&result, bool need_alias) {\n    construct<Class>(v_h, std::forward<T>(result), need_alias);\n}\n\n/// Set both the C++ and Python states\ntemplate <typename Class,\n          typename T,\n          typename O,\n          enable_if_t<std::is_convertible<O, handle>::value, int> = 0>\nvoid setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {\n    construct<Class>(v_h, std::move(result.first), need_alias);\n    auto d = handle(result.second);\n    if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {\n        // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.\n        // See PR #2972 for details.\n        return;\n    }\n    // Our tests never run into an unset dict, but being careful here for now (see #5658)\n    auto dict = getattr(reinterpret_cast<PyObject *>(v_h.inst), \"__dict__\", none());\n    if (dict.is_none()) {\n        setattr(reinterpret_cast<PyObject *>(v_h.inst), \"__dict__\", d);\n    } else {\n        // Keep the original object dict and just update it\n        if (PyDict_Update(dict.ptr(), d.ptr()) < 0) {\n            throw error_already_set();\n        }\n    }\n}\n\n/// Implementation for py::pickle(GetState, SetState)\ntemplate <typename Get,\n          typename Set,\n          typename = function_signature_t<Get>,\n          typename = function_signature_t<Set>>\nstruct pickle_factory;\n\ntemplate <typename Get,\n          typename Set,\n          typename RetState,\n          typename Self,\n          typename NewInstance,\n          typename ArgState>\nstruct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {\n    using Ret = intrinsic_t<RetState>;\n    using Arg = intrinsic_t<ArgState>;\n\n    // Subclasses are now allowed for support between type hint and generic versions of types\n    // (e.g.) typing::List <--> list\n    static_assert(std::is_same<Ret, Arg>::value || std::is_base_of<Ret, Arg>::value\n                      || std::is_base_of<Arg, Ret>::value,\n                  \"The type returned by `__getstate__` must be the same or subclass of the \"\n                  \"argument accepted by `__setstate__`\");\n\n    remove_reference_t<Get> get;\n    remove_reference_t<Set> set;\n\n    pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}\n\n    template <typename Class, typename... Extra>\n    void execute(Class &cl, const Extra &...extra) && {\n        cl.def(\"__getstate__\", std::move(get), pos_only());\n\n#if defined(PYBIND11_CPP14)\n        cl.def(\n            \"__setstate__\",\n            [func = std::move(set)]\n#else\n        auto &func = set;\n        cl.def(\n            \"__setstate__\",\n            [func]\n#endif\n            (value_and_holder &v_h, ArgState state) {\n                setstate<Class>(\n                    v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);\n            },\n            is_new_style_constructor(),\n            extra...);\n    }\n};\n\nPYBIND11_NAMESPACE_END(initimpl)\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/internals.h",
    "content": "/*\n    pybind11/detail/internals.h: Internal data structure and related functions\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/conduit/pybind11_platform_abi_id.h>\n#include <pybind11/gil_simple.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/trampoline_self_life_support.h>\n\n#include \"common.h\"\n#include \"struct_smart_holder.h\"\n\n#include <atomic>\n#include <cstdint>\n#include <exception>\n#include <limits>\n#include <mutex>\n#include <thread>\n\n/// Tracks the `internals` and `type_info` ABI version independent of the main library version.\n///\n/// Some portions of the code use an ABI that is conditional depending on this\n/// version number.  That allows ABI-breaking changes to be \"pre-implemented\".\n/// Once the default version number is incremented, the conditional logic that\n/// no longer applies can be removed.  Additionally, users that need not\n/// maintain ABI compatibility can increase the version number in order to take\n/// advantage of any functionality/efficiency improvements that depend on the\n/// newer ABI.\n///\n/// WARNING: If you choose to manually increase the ABI version, note that\n/// pybind11 may not be tested as thoroughly with a non-default ABI version, and\n/// further ABI-incompatible changes may be made before the ABI is officially\n/// changed to the new version.\n#ifndef PYBIND11_INTERNALS_VERSION\n#    define PYBIND11_INTERNALS_VERSION 12\n#endif\n\n#if PYBIND11_INTERNALS_VERSION < 12\n#    error \"PYBIND11_INTERNALS_VERSION 12 is the minimum for all platforms for pybind11 v3.1.0\"\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nusing ExceptionTranslator = void (*)(std::exception_ptr);\n\n// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new\n// Thread Specific Storage (TSS) API.\n// Avoid unnecessary allocation of `Py_tss_t`, since we cannot use\n// `Py_LIMITED_API` anyway.\n#define PYBIND11_TLS_KEY_REF Py_tss_t &\n#if defined(__clang__)\n#    define PYBIND11_TLS_KEY_INIT(var)                                                            \\\n        _Pragma(\"clang diagnostic push\")                                         /**/             \\\n            _Pragma(\"clang diagnostic ignored \\\"-Wmissing-field-initializers\\\"\") /**/             \\\n            Py_tss_t var                                                                          \\\n            = Py_tss_NEEDS_INIT;                                                                  \\\n        _Pragma(\"clang diagnostic pop\")\n#elif defined(__GNUC__) && !defined(__INTEL_COMPILER)\n#    define PYBIND11_TLS_KEY_INIT(var)                                                            \\\n        _Pragma(\"GCC diagnostic push\")                                         /**/               \\\n            _Pragma(\"GCC diagnostic ignored \\\"-Wmissing-field-initializers\\\"\") /**/               \\\n            Py_tss_t var                                                                          \\\n            = Py_tss_NEEDS_INIT;                                                                  \\\n        _Pragma(\"GCC diagnostic pop\")\n#else\n#    define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;\n#endif\n#define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)\n#define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))\n#define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))\n#define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)\n#define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))\n\n/// A smart-pointer-like wrapper around a thread-specific value. get/set of the pointer applies to\n/// the current thread only.\ntemplate <typename T>\nclass thread_specific_storage {\npublic:\n    thread_specific_storage() {\n        // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)\n        if (!PYBIND11_TLS_KEY_CREATE(key_)) {\n            pybind11_fail(\n                \"thread_specific_storage constructor: could not initialize the TSS key!\");\n        }\n    }\n\n    ~thread_specific_storage() {\n        // This destructor is often called *after* Py_Finalize(). That *SHOULD BE* fine on most\n        // platforms. The following details what happens when PyThread_tss_free is called in\n        // CPython. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does\n        // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.\n        // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).\n        // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*\n        // that the `key` be allocated with the CPython allocator (as it is by\n        // PyThread_tss_create).\n        // However, in GraalPy (as of v24.2 or older), TSS is implemented by Java and this call\n        // requires a living Python interpreter.\n#ifdef GRAALVM_PYTHON\n        if (Py_IsInitialized() == 0 || _Py_IsFinalizing() != 0) {\n            return;\n        }\n#endif\n        PYBIND11_TLS_FREE(key_);\n    }\n\n    thread_specific_storage(thread_specific_storage const &) = delete;\n    thread_specific_storage(thread_specific_storage &&) = delete;\n    thread_specific_storage &operator=(thread_specific_storage const &) = delete;\n    thread_specific_storage &operator=(thread_specific_storage &&) = delete;\n\n    T *get() const { return reinterpret_cast<T *>(PYBIND11_TLS_GET_VALUE(key_)); }\n\n    T &operator*() const { return *get(); }\n    explicit operator T *() const { return get(); }\n    explicit operator bool() const { return get() != nullptr; }\n\n    void set(T *val) { PYBIND11_TLS_REPLACE_VALUE(key_, reinterpret_cast<void *>(val)); }\n    void reset(T *p = nullptr) { set(p); }\n    thread_specific_storage &operator=(T *pval) {\n        set(pval);\n        return *this;\n    }\n\nprivate:\n    PYBIND11_TLS_KEY_INIT(mutable key_)\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// This does NOT actually exist as a module.\n#define PYBIND11_DUMMY_MODULE_NAME \"pybind11_builtins\"\n\n// Forward declarations\ninline PyTypeObject *make_static_property_type();\ninline PyTypeObject *make_default_metaclass();\ninline PyObject *make_object_base_type(PyTypeObject *metaclass);\ninline void translate_exception(std::exception_ptr p);\n\ninline PyThreadState *get_thread_state_unchecked() {\n#if defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)\n    return PyThreadState_GET();\n#elif PY_VERSION_HEX < 0x030D0000\n    return _PyThreadState_UncheckedGet();\n#else\n    return PyThreadState_GetUnchecked();\n#endif\n}\n\ninline PyInterpreterState *get_interpreter_state_unchecked() {\n    auto *tstate = get_thread_state_unchecked();\n    return tstate ? tstate->interp : nullptr;\n}\n\ninline object get_python_state_dict() {\n    object state_dict;\n#if defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)\n    state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());\n#else\n    auto *istate = get_interpreter_state_unchecked();\n    if (istate) {\n        state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));\n    }\n#endif\n    if (!state_dict) {\n        raise_from(PyExc_SystemError, \"pybind11::detail::get_python_state_dict() FAILED\");\n        throw error_already_set();\n    }\n    return state_dict;\n}\n\n// Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly\n// other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module\n// even when `A` is the same, non-hidden-visibility type (e.g. from a common include).  Under\n// libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,\n// which works.  If not under a known-good stl, provide our own name-based hash and equality\n// functions that use the type name.\n#if !defined(_LIBCPP_VERSION)\ninline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }\nusing type_hash = std::hash<std::type_index>;\nusing type_equal_to = std::equal_to<std::type_index>;\n#else\ninline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {\n    return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;\n}\n\nstruct type_hash {\n    size_t operator()(const std::type_index &t) const noexcept {\n        size_t hash = 5381;\n        const char *ptr = t.name();\n        while (auto c = static_cast<unsigned char>(*ptr++)) {\n            hash = (hash * 33) ^ c;\n        }\n        return hash;\n    }\n};\n\nstruct type_equal_to {\n    bool operator()(const std::type_index &lhs, const std::type_index &rhs) const noexcept {\n        return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;\n    }\n};\n#endif\n\n// For now, we don't bother adding a fancy hash for pointers and just\n// let the standard library use the identity hash function if that's\n// what it wants to do (e.g., as in libstdc++).\ntemplate <typename value_type>\nusing fast_type_map = std::unordered_map<const std::type_info *, value_type>;\n\ntemplate <typename value_type>\nusing type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;\n\nstruct override_hash {\n    size_t operator()(const std::pair<const PyObject *, const char *> &v) const noexcept {\n        size_t value = std::hash<const void *>()(v.first);\n        value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);\n        return value;\n    }\n};\n\nusing instance_map = std::unordered_multimap<const void *, instance *>;\n\n#ifdef Py_GIL_DISABLED\n// Wrapper around PyMutex to provide BasicLockable semantics\nclass pymutex {\n    friend class pycritical_section;\n    PyMutex mutex;\n\npublic:\n    pymutex() : mutex({}) {}\n    void lock() { PyMutex_Lock(&mutex); }\n    void unlock() { PyMutex_Unlock(&mutex); }\n};\n\nclass pycritical_section {\n    pymutex &mutex;\n#    if PY_VERSION_HEX >= 0x030E00C1 // 3.14.0rc1\n    PyCriticalSection cs;\n#    endif\n\npublic:\n    explicit pycritical_section(pymutex &m) : mutex(m) {\n        // PyCriticalSection_BeginMutex was added in Python 3.15.0a1 and backported to 3.14.0rc1\n#    if PY_VERSION_HEX >= 0x030E00C1 // 3.14.0rc1\n        PyCriticalSection_BeginMutex(&cs, &mutex.mutex);\n#    else\n        // Fall back to direct mutex locking for older free-threaded Python versions\n        mutex.lock();\n#    endif\n    }\n    ~pycritical_section() {\n#    if PY_VERSION_HEX >= 0x030E00C1 // 3.14.0rc1\n        PyCriticalSection_End(&cs);\n#    else\n        mutex.unlock();\n#    endif\n    }\n\n    // Non-copyable and non-movable to prevent double-unlock\n    pycritical_section(const pycritical_section &) = delete;\n    pycritical_section &operator=(const pycritical_section &) = delete;\n    pycritical_section(pycritical_section &&) = delete;\n    pycritical_section &operator=(pycritical_section &&) = delete;\n};\n\n// Instance map shards are used to reduce mutex contention in free-threaded Python.\nstruct instance_map_shard {\n    instance_map registered_instances;\n    pymutex mutex;\n    // alignas(64) would be better, but causes compile errors in macOS before 10.14 (see #5200)\n    char padding[64 - (sizeof(instance_map) + sizeof(pymutex)) % 64];\n};\n\nstatic_assert(sizeof(instance_map_shard) % 64 == 0,\n              \"instance_map_shard size is not a multiple of 64 bytes\");\n\ninline uint64_t round_up_to_next_pow2(uint64_t x) {\n    // Round-up to the next power of two.\n    // See https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2\n    x--;\n    x |= (x >> 1);\n    x |= (x >> 2);\n    x |= (x >> 4);\n    x |= (x >> 8);\n    x |= (x >> 16);\n    x |= (x >> 32);\n    x++;\n    return x;\n}\n#endif\n\nclass loader_life_support;\n\n/// Internal data structure used to track registered instances and types.\n/// Whenever binary incompatible changes are made to this structure,\n/// `PYBIND11_INTERNALS_VERSION` must be incremented.\nstruct internals {\n#ifdef Py_GIL_DISABLED\n    pymutex mutex;\n    pymutex exception_translator_mutex;\n#endif\n#if PYBIND11_INTERNALS_VERSION >= 12\n    // non-normative but fast \"hint\" for registered_types_cpp. Meant\n    // to be used as the first level of a two-level lookup: successful\n    // lookups are correct, but unsuccessful lookups need to try\n    // registered_types_cpp and then backfill this map if they find\n    // anything.\n    fast_type_map<type_info *> registered_types_cpp_fast;\n#endif\n\n    // std::type_index -> pybind11's type information\n    type_map<type_info *> registered_types_cpp;\n    // PyTypeObject* -> base type_info(s)\n    std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;\n#ifdef Py_GIL_DISABLED\n    std::unique_ptr<instance_map_shard[]> instance_shards; // void * -> instance*\n    size_t instance_shards_mask = 0;\n#else\n    instance_map registered_instances; // void * -> instance*\n#endif\n    std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>\n        inactive_override_cache;\n    type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;\n    std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;\n    std::forward_list<ExceptionTranslator> registered_exception_translators;\n    std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across\n                                                         // extensions\n    std::forward_list<std::string> static_strings;       // Stores the std::strings backing\n                                                         // detail::c_str()\n    PyTypeObject *static_property_type = nullptr;\n    PyTypeObject *default_metaclass = nullptr;\n    PyObject *instance_base = nullptr;\n    // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:\n    thread_specific_storage<PyThreadState> tstate;\n#if PYBIND11_INTERNALS_VERSION <= 11\n    thread_specific_storage<loader_life_support> loader_life_support_tls; // OBSOLETE (PR #5830)\n#endif\n    // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:\n    PyInterpreterState *istate = nullptr;\n\n    type_map<PyObject *> native_enum_type_map;\n\n    internals()\n        : static_property_type(make_static_property_type()),\n          default_metaclass(make_default_metaclass()), istate(get_interpreter_state_unchecked()) {\n        tstate.set(nullptr); // See PR #5870\n        registered_exception_translators.push_front(&translate_exception);\n#ifdef Py_GIL_DISABLED\n        // Scale proportional to the number of cores. 2x is a heuristic to reduce contention.\n        // Make sure the number isn't unreasonable by limiting it to 16 bits (65K)\n        auto num_shards = static_cast<std::uint16_t>(\n            std::min<std::size_t>(round_up_to_next_pow2(2 * std::thread::hardware_concurrency()),\n                                  std::numeric_limits<std::uint16_t>::max()));\n        if (num_shards == 0) {\n            num_shards = 1;\n        }\n        instance_shards.reset(new instance_map_shard[num_shards]);\n        instance_shards_mask = num_shards - 1;\n#endif\n    }\n    internals(const internals &other) = delete;\n    internals(internals &&other) = delete;\n    internals &operator=(const internals &other) = delete;\n    internals &operator=(internals &&other) = delete;\n    ~internals() = default;\n};\n\n// the internals struct (above) is shared between all the modules. local_internals are only\n// for a single module. Any changes made to internals may require an update to\n// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,\n// restricted to a single module. Whether a module has local internals or not should not\n// impact any other modules, because the only things accessing the local internals is the\n// module that contains them.\nstruct local_internals {\n    // It should be safe to use fast_type_map here because this entire\n    // data structure is scoped to our single module, and thus a single\n    // DSO and single instance of type_info for any particular type.\n    fast_type_map<type_info *> registered_types_cpp;\n\n    std::forward_list<ExceptionTranslator> registered_exception_translators;\n    PyTypeObject *function_record_py_type = nullptr;\n};\n\nenum class holder_enum_t : uint8_t {\n    undefined,\n    std_unique_ptr, // Default, lacking interop with std::shared_ptr.\n    std_shared_ptr, // Lacking interop with std::unique_ptr.\n    smart_holder,   // Full std::unique_ptr / std::shared_ptr interop.\n    custom_holder,\n};\n\n/// Additional type information which does not fit into the PyTypeObject.\n/// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.\nstruct type_info {\n    PyTypeObject *type;\n    const std::type_info *cpptype;\n    size_t type_size, type_align, holder_size_in_ptrs;\n    void *(*operator_new)(size_t);\n    void (*init_instance)(instance *, const void *);\n    void (*dealloc)(value_and_holder &v_h);\n\n    // Cross-DSO-safe function pointers, to sidestep cross-DSO RTTI issues\n    // on platforms like macOS (see PR #5728 for details):\n    memory::get_guarded_delete_fn get_memory_guarded_delete = memory::get_guarded_delete;\n    get_trampoline_self_life_support_fn get_trampoline_self_life_support = nullptr;\n\n    std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;\n    std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;\n    std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;\n    buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;\n    void *get_buffer_data = nullptr;\n    void *(*module_local_load)(PyObject *, const type_info *) = nullptr;\n    holder_enum_t holder_enum_v = holder_enum_t::undefined;\n\n#if PYBIND11_INTERNALS_VERSION >= 12\n    // When a type appears in multiple DSOs,\n    // internals::registered_types_cpp_fast will have multiple distinct\n    // keys (the std::type_info from each DSO) mapped to the same\n    // detail::type_info*. We need to keep track of these aliases so that we clean\n    // them up when our type is deallocated. A linked list is appropriate\n    // because it is expected to be 1) usually empty and 2)\n    // when it's not empty, usually very small. See also `struct\n    // nb_alias_chain` added in\n    // https://github.com/wjakob/nanobind/commit/b515b1f7f2f4ecc0357818e6201c94a9f4cbfdc2\n    std::forward_list<const std::type_info *> alias_chain;\n#endif\n\n    /* A simple type never occurs as a (direct or indirect) parent\n     * of a class that makes use of multiple inheritance.\n     * A type can be simple even if it has non-simple ancestors as long as it has no descendants.\n     */\n    bool simple_type : 1;\n    /* True if there is no multiple inheritance in this type's inheritance tree */\n    bool simple_ancestors : 1;\n    /* true if this is a type registered with py::module_local */\n    bool module_local : 1;\n};\n\n/// Information stored in a capsule on py::native_enum() types. Since we don't\n/// create a type_info record for native enums, we must store here any\n/// information we will need about the enum at runtime.\n///\n/// If you make backward-incompatible changes to this structure, you must\n/// change the `attribute_name()` so that native enums from older version of\n/// pybind11 don't have their records reinterpreted. Better would be to keep\n/// the changes backward-compatible (i.e., only add new fields at the end)\n/// and detect/indicate their presence using the currently-unused `version`.\nstruct native_enum_record {\n    const std::type_info *cpptype;\n    uint32_t size_bytes;\n    bool is_signed;\n    const uint8_t version = 1;\n\n    static const char *attribute_name() { return \"__pybind11_native_enum__\"; }\n};\n\n#define PYBIND11_INTERNALS_ID                                                                     \\\n    \"__pybind11_internals_v\" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION)                        \\\n        PYBIND11_COMPILER_TYPE_LEADING_UNDERSCORE PYBIND11_PLATFORM_ABI_ID \"__\"\n\n#define PYBIND11_MODULE_LOCAL_ID                                                                  \\\n    \"__pybind11_module_local_v\" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION)                     \\\n        PYBIND11_COMPILER_TYPE_LEADING_UNDERSCORE PYBIND11_PLATFORM_ABI_ID \"__\"\n\n/// We use this to figure out if there are or have been multiple subinterpreters active at any\n/// point. This must never go from true to false while any interpreter may be running in any\n/// thread!\ninline std::atomic_bool &has_seen_non_main_interpreter() {\n    static std::atomic_bool multi(false);\n    return multi;\n}\n\ntemplate <class T,\n          enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>\nbool handle_nested_exception(const T &exc, const std::exception_ptr &p) {\n    std::exception_ptr nested = exc.nested_ptr();\n    if (nested != nullptr && nested != p) {\n        translate_exception(nested);\n        return true;\n    }\n    return false;\n}\n\ntemplate <class T,\n          enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>\nbool handle_nested_exception(const T &exc, const std::exception_ptr &p) {\n    if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {\n        return handle_nested_exception(*nep, p);\n    }\n    return false;\n}\n\ninline bool raise_err(PyObject *exc_type, const char *msg) {\n    if (PyErr_Occurred()) {\n        raise_from(exc_type, msg);\n        return true;\n    }\n    set_error(exc_type, msg);\n    return false;\n}\n\ninline void translate_exception(std::exception_ptr p) {\n    if (!p) {\n        return;\n    }\n    try {\n        std::rethrow_exception(p);\n    } catch (error_already_set &e) {\n        handle_nested_exception(e, p);\n        e.restore();\n        return;\n    } catch (const builtin_exception &e) {\n        // Could not use template since it's an abstract class.\n        if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {\n            handle_nested_exception(*nep, p);\n        }\n        e.set_error();\n        return;\n    } catch (const std::bad_alloc &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_MemoryError, e.what());\n        return;\n    } catch (const std::domain_error &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_ValueError, e.what());\n        return;\n    } catch (const std::invalid_argument &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_ValueError, e.what());\n        return;\n    } catch (const std::length_error &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_ValueError, e.what());\n        return;\n    } catch (const std::out_of_range &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_IndexError, e.what());\n        return;\n    } catch (const std::range_error &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_ValueError, e.what());\n        return;\n    } catch (const std::overflow_error &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_OverflowError, e.what());\n        return;\n    } catch (const std::exception &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_RuntimeError, e.what());\n        return;\n    } catch (const std::nested_exception &e) {\n        handle_nested_exception(e, p);\n        raise_err(PyExc_RuntimeError, \"Caught an unknown nested exception!\");\n        return;\n    } catch (...) {\n        raise_err(PyExc_RuntimeError, \"Caught an unknown exception!\");\n        return;\n    }\n}\n\n#if !defined(__GLIBCXX__)\ninline void translate_local_exception(std::exception_ptr p) {\n    try {\n        if (p) {\n            std::rethrow_exception(p);\n        }\n    } catch (error_already_set &e) {\n        e.restore();\n        return;\n    } catch (const builtin_exception &e) {\n        e.set_error();\n        return;\n    }\n}\n#endif\n\n// Sentinel value for the `dtor` parameter of `atomic_get_or_create_in_state_dict`.\n// Indicates no destructor was explicitly provided (distinct from nullptr, which means \"leak\").\n#define PYBIND11_DTOR_USE_DELETE (reinterpret_cast<void (*)(PyObject *)>(1))\n\n// Get or create per-storage capsule in the current interpreter's state dict.\n//   - The storage is interpreter-dependent: different interpreters will have different storage.\n//     This is important when using multiple-interpreters, to avoid sharing unshareable objects\n//     between interpreters.\n//   - There is one storage per `key` in an interpreter and it is accessible between all extensions\n//     in the same interpreter.\n//   - The life span of the storage is tied to the interpreter: it will be kept alive until the\n//     interpreter shuts down.\n//\n// Use test-and-set pattern with `PyDict_SetDefault` for thread-safe concurrent access.\n// WARNING: There can be multiple threads creating the storage at the same time, while only one\n//          will succeed in inserting its capsule into the dict. Therefore, the deleter will be\n//          used to clean up the storage of the unused capsules.\n//\n// Returns: pair of (pointer to storage, bool indicating if newly created).\n//          The bool follows std::map::insert convention: true = created, false = existed.\n// `dtor`: optional destructor called when the interpreter shuts down.\n//   - If not provided: the storage will be deleted using `delete`.\n//   - If nullptr: the storage will be leaked (useful for singletons that outlive the interpreter).\n//   - If a function: that function will be called with the capsule object.\ntemplate <typename Payload>\nstd::pair<Payload *, bool> atomic_get_or_create_in_state_dict(const char *key,\n                                                              void (*dtor)(PyObject *)\n                                                              = PYBIND11_DTOR_USE_DELETE) {\n    error_scope err_scope; // preserve any existing Python error states\n\n    auto state_dict = reinterpret_borrow<dict>(get_python_state_dict());\n    PyObject *capsule_obj = nullptr;\n    bool created = false;\n\n    // Try to get existing storage (fast path).\n    capsule_obj = dict_getitemstring(state_dict.ptr(), key);\n    if (capsule_obj == nullptr) {\n        if (PyErr_Occurred()) {\n            throw error_already_set();\n        }\n        // Storage doesn't exist yet, create a new one.\n        // Use unique_ptr for exception safety: if capsule creation throws, the storage is\n        // automatically deleted.\n        auto storage_ptr = std::unique_ptr<Payload>(new Payload{});\n        auto new_capsule\n            = capsule(storage_ptr.get(),\n                      // The destructor will be called when the capsule is GC'ed.\n                      //  If the insert below fails (entry already in the dict), then this\n                      //  destructor will be called on the newly created capsule at the end of this\n                      //  function, and we want to just release this memory.\n                      /*destructor=*/[](void *v) { delete static_cast<Payload *>(v); });\n        // At this point, the capsule object is created successfully.\n        // Release the unique_ptr and let the capsule object own the storage to avoid double-free.\n        (void) storage_ptr.release();\n\n        // Use `PyDict_SetDefault` for atomic test-and-set:\n        //   - If key doesn't exist, inserts our capsule and returns it.\n        //   - If key exists (another thread inserted first), returns the existing value.\n        // This is thread-safe because `PyDict_SetDefault` will hold a lock on the dict.\n        //\n        // NOTE: Here we use `PyDict_SetDefault` instead of `PyDict_SetDefaultRef` because the\n        //       capsule is kept alive until interpreter shutdown, so we do not need to handle\n        //       incref and decref here.\n        capsule_obj = dict_setdefaultstring(state_dict.ptr(), key, new_capsule.ptr());\n        if (capsule_obj == nullptr) {\n            throw error_already_set();\n        }\n        created = (capsule_obj == new_capsule.ptr());\n        // - If key already existed, our `new_capsule` is not inserted, it will be destructed when\n        //   going out of scope here, and will call the destructor set above.\n        // - Otherwise, our `new_capsule` is now in the dict, and it owns the storage and the state\n        //   dict will incref it.  We need to set the caller's destructor on it, which will be\n        //   called when the interpreter shuts down.\n        if (created && dtor != PYBIND11_DTOR_USE_DELETE) {\n            if (PyCapsule_SetDestructor(capsule_obj, dtor) < 0) {\n                throw error_already_set();\n            }\n        }\n    }\n\n    // Get the storage pointer from the capsule.\n    void *raw_ptr = PyCapsule_GetPointer(capsule_obj, /*name=*/nullptr);\n    if (!raw_ptr) {\n        raise_from(PyExc_SystemError,\n                   \"pybind11::detail::atomic_get_or_create_in_state_dict() FAILED\");\n        throw error_already_set();\n    }\n    return std::pair<Payload *, bool>(static_cast<Payload *>(raw_ptr), created);\n}\n\n#undef PYBIND11_DTOR_USE_DELETE\n\ntemplate <typename InternalsType>\nclass internals_pp_manager {\npublic:\n    using on_fetch_function = void(InternalsType *);\n\n    static internals_pp_manager &get_instance(char const *id, on_fetch_function *on_fetch) {\n        static internals_pp_manager instance(id, on_fetch);\n        return instance;\n    }\n\n    /// Get the current pointer-to-pointer, allocating it if it does not already exist.  May\n    /// acquire the GIL. Will never return nullptr.\n    std::unique_ptr<InternalsType> *get_pp() {\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n        if (has_seen_non_main_interpreter()) {\n            // Whenever the interpreter changes on the current thread we need to invalidate the\n            // internals_pp so that it can be pulled from the interpreter's state dict.  That is\n            // slow, so we use the current PyThreadState to check if it is necessary.\n            auto *tstate = get_thread_state_unchecked();\n            if (!tstate || tstate->interp != last_istate_tls()) {\n                gil_scoped_acquire_simple gil;\n                if (!tstate) {\n                    tstate = get_thread_state_unchecked();\n                }\n                last_istate_tls() = tstate->interp;\n                internals_p_tls() = get_or_create_pp_in_state_dict();\n            }\n            return internals_p_tls();\n        }\n#endif\n        if (!internals_singleton_pp_) {\n            gil_scoped_acquire_simple gil;\n            internals_singleton_pp_ = get_or_create_pp_in_state_dict();\n        }\n        return internals_singleton_pp_;\n    }\n\n    /// Drop all the references we're currently holding.\n    void unref() {\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n        if (has_seen_non_main_interpreter()) {\n            last_istate_tls() = nullptr;\n            internals_p_tls() = nullptr;\n            return;\n        }\n#endif\n        internals_singleton_pp_ = nullptr;\n    }\n\n    void destroy() {\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n        if (has_seen_non_main_interpreter()) {\n            auto *tstate = get_thread_state_unchecked();\n            // this could be called without an active interpreter, just use what was cached\n            if (!tstate || tstate->interp == last_istate_tls()) {\n                auto tpp = internals_p_tls();\n                {\n                    std::lock_guard<std::mutex> lock(pp_set_mutex_);\n                    pps_have_created_content_.erase(tpp); // untrack deleted pp\n                }\n                delete tpp; // may call back into Python\n            }\n            unref();\n            return;\n        }\n#endif\n        {\n            std::lock_guard<std::mutex> lock(pp_set_mutex_);\n            pps_have_created_content_.erase(internals_singleton_pp_); // untrack deleted pp\n        }\n        delete internals_singleton_pp_; // may call back into Python\n        unref();\n    }\n\n    void create_pp_content_once(std::unique_ptr<InternalsType> *const pp) {\n        // Assume the GIL is held here. May call back into Python. We cannot hold the lock with our\n        // mutex here. So there may be multiple threads creating the content at the same time. Only\n        // one will install its content to pp below. Others will be freed when going out of scope.\n        auto tmp = std::unique_ptr<InternalsType>(new InternalsType());\n\n        {\n            // Lock scope must not include Python calls, which may require the GIL and cause\n            // deadlocks.\n            std::lock_guard<std::mutex> lock(pp_set_mutex_);\n\n            if (*pp) {\n                // Already created in another thread.\n                return;\n            }\n\n            // At this point, pp->get() is nullptr.\n            // The content is either not yet created, or was previously destroyed via pp->reset().\n\n            // Detect re-creation of internals after destruction during interpreter shutdown.\n            // If pybind11 code (e.g., tp_traverse/tp_clear calling py::cast) runs after internals\n            // have been destroyed, a new empty internals would be created, causing type lookup\n            // failures. See also get_or_create_pp_in_state_dict() comments.\n            if (pps_have_created_content_.find(pp) != pps_have_created_content_.end()) {\n                pybind11_fail(\n                    \"pybind11::detail::internals_pp_manager::create_pp_content_once() \"\n                    \"FAILED: reentrant call detected while fetching pybind11 internals!\");\n            }\n\n            // Each interpreter can only create its internals once.\n            pps_have_created_content_.insert(pp);\n            // Install the created content.\n            pp->swap(tmp);\n        }\n    }\n\nprivate:\n    internals_pp_manager(char const *id, on_fetch_function *on_fetch)\n        : holder_id_(id), on_fetch_(on_fetch) {}\n\n    std::unique_ptr<InternalsType> *get_or_create_pp_in_state_dict() {\n        // The `unique_ptr<InternalsType>` is intentionally leaked on interpreter shutdown.\n        // Once an instance is created, it will never be deleted until the process exits (compare\n        // to interpreter shutdown in multiple-interpreter scenarios).\n        // We cannot guarantee the destruction order of capsules in the interpreter state dict on\n        // interpreter shutdown, so deleting internals too early could cause undefined behavior\n        // when other pybind11 objects access `get_internals()` during finalization (which would\n        // recreate empty internals). See also create_pp_content_once() above.\n        // See https://github.com/pybind/pybind11/pull/5958#discussion_r2717645230.\n        auto result = atomic_get_or_create_in_state_dict<std::unique_ptr<InternalsType>>(\n            holder_id_, /*dtor=*/nullptr /* leak the capsule content */);\n        auto *pp = result.first;\n        bool created = result.second;\n        // Only call on_fetch_ when fetching existing internals, not when creating new ones.\n        if (!created && on_fetch_ && pp) {\n            on_fetch_(pp->get());\n        }\n        return pp;\n    }\n\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n    static PyInterpreterState *&last_istate_tls() {\n        static thread_local PyInterpreterState *last_istate = nullptr;\n        return last_istate;\n    }\n\n    static std::unique_ptr<InternalsType> *&internals_p_tls() {\n        static thread_local std::unique_ptr<InternalsType> *internals_p = nullptr;\n        return internals_p;\n    }\n#endif\n\n    char const *holder_id_ = nullptr;\n    on_fetch_function *on_fetch_ = nullptr;\n    // Pointer-to-pointer to the singleton internals for the first seen interpreter (may not be the\n    // main interpreter)\n    std::unique_ptr<InternalsType> *internals_singleton_pp_ = nullptr;\n\n    // Track pointer-to-pointers whose internals have been created, to detect re-entrancy.\n    // Use instance member over static due to singleton pattern of this class.\n    std::unordered_set<std::unique_ptr<InternalsType> *> pps_have_created_content_;\n    std::mutex pp_set_mutex_;\n};\n\n// If We loaded the internals through `state_dict`, our `error_already_set`\n// and `builtin_exception` may be different local classes than the ones set up in the\n// initial exception translator, below, so add another for our local exception classes.\n//\n// libstdc++ doesn't require this (types there are identified only by name)\n// libc++ with CPython doesn't require this (types are explicitly exported)\n// libc++ with PyPy still need it, awaiting further investigation\n#if !defined(__GLIBCXX__)\ninline void check_internals_local_exception_translator(internals *internals_ptr) {\n    if (internals_ptr) {\n        for (auto et : internals_ptr->registered_exception_translators) {\n            if (et == &translate_local_exception) {\n                return;\n            }\n        }\n        internals_ptr->registered_exception_translators.push_front(&translate_local_exception);\n    }\n}\n#endif\n\ninline internals_pp_manager<internals> &get_internals_pp_manager() {\n#if defined(__GLIBCXX__)\n#    define ON_FETCH_FN nullptr\n#else\n#    define ON_FETCH_FN &check_internals_local_exception_translator\n#endif\n    return internals_pp_manager<internals>::get_instance(PYBIND11_INTERNALS_ID, ON_FETCH_FN);\n#undef ON_FETCH_FN\n}\n\n/// Return a reference to the current `internals` data\nPYBIND11_NOINLINE internals &get_internals() {\n    auto &ppmgr = get_internals_pp_manager();\n    auto &internals_ptr = *ppmgr.get_pp();\n    if (!internals_ptr) {\n        // Slow path, something needs fetched from the state dict or created\n        gil_scoped_acquire_simple gil;\n        error_scope err_scope;\n\n        ppmgr.create_pp_content_once(&internals_ptr);\n\n        if (!internals_ptr->instance_base) {\n            // This calls get_internals, so cannot be called from within the internals constructor\n            // called above because internals_ptr must be set before get_internals is called again\n            internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);\n        }\n    }\n    return *internals_ptr;\n}\n\n/// Return the PyObject* for the internals capsule (borrowed reference).\n/// Returns nullptr if the capsule doesn't exist yet.\ninline PyObject *get_internals_capsule() {\n    auto state_dict = reinterpret_borrow<dict>(get_python_state_dict());\n    return dict_getitemstring(state_dict.ptr(), PYBIND11_INTERNALS_ID);\n}\n\n/// Return the key used for local_internals in the state dict.\n/// This function ensures a consistent key is used across all call sites within the same\n/// compilation unit. The key includes the address of a static variable to make it unique per\n/// module (DSO), matching the behavior of get_local_internals_pp_manager().\ninline const std::string &get_local_internals_key() {\n    static const std::string key\n        = PYBIND11_MODULE_LOCAL_ID + std::to_string(reinterpret_cast<uintptr_t>(&key));\n    return key;\n}\n\n/// Return the PyObject* for the local_internals capsule (borrowed reference).\n/// Returns nullptr if the capsule doesn't exist yet.\ninline PyObject *get_local_internals_capsule() {\n    const auto &key = get_local_internals_key();\n    auto state_dict = reinterpret_borrow<dict>(get_python_state_dict());\n    return dict_getitemstring(state_dict.ptr(), key.c_str());\n}\n\ninline void ensure_internals() {\n    pybind11::detail::get_internals_pp_manager().unref();\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n    if (PyInterpreterState_Get() != PyInterpreterState_Main()) {\n        has_seen_non_main_interpreter() = true;\n    }\n#endif\n    pybind11::detail::get_internals();\n}\n\ninline internals_pp_manager<local_internals> &get_local_internals_pp_manager() {\n    // Use the address of a static variable as part of the key, so that the value is uniquely tied\n    // to where the module is loaded in memory\n    return internals_pp_manager<local_internals>::get_instance(get_local_internals_key().c_str(),\n                                                               nullptr);\n}\n\n/// Works like `get_internals`, but for things which are locally registered.\ninline local_internals &get_local_internals() {\n    auto &ppmgr = get_local_internals_pp_manager();\n    auto &internals_ptr = *ppmgr.get_pp();\n    if (!internals_ptr) {\n        gil_scoped_acquire_simple gil;\n        error_scope err_scope;\n\n        ppmgr.create_pp_content_once(&internals_ptr);\n    }\n    return *internals_ptr;\n}\n\n#ifdef Py_GIL_DISABLED\n#    define PYBIND11_LOCK_INTERNALS(internals) pycritical_section lock((internals).mutex)\n#else\n#    define PYBIND11_LOCK_INTERNALS(internals)\n#endif\n\ntemplate <typename F>\ninline auto with_internals(const F &cb) -> decltype(cb(get_internals())) {\n    auto &internals = get_internals();\n    PYBIND11_LOCK_INTERNALS(internals);\n    return cb(internals);\n}\n\ntemplate <typename F>\ninline void with_internals_if_internals(const F &cb) {\n    auto &ppmgr = get_internals_pp_manager();\n    auto &internals_ptr = *ppmgr.get_pp();\n    if (internals_ptr) {\n        auto &internals = *internals_ptr;\n        PYBIND11_LOCK_INTERNALS(internals);\n        cb(internals);\n    }\n}\n\ntemplate <typename F>\ninline auto with_exception_translators(const F &cb)\n    -> decltype(cb(get_internals().registered_exception_translators,\n                   get_local_internals().registered_exception_translators)) {\n    auto &internals = get_internals();\n#ifdef Py_GIL_DISABLED\n    pycritical_section lock((internals).exception_translator_mutex);\n#endif\n    auto &local_internals = get_local_internals();\n    return cb(internals.registered_exception_translators,\n              local_internals.registered_exception_translators);\n}\n\ninline std::uint64_t mix64(std::uint64_t z) {\n    // David Stafford's variant 13 of the MurmurHash3 finalizer popularized\n    // by the SplitMix PRNG.\n    // https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html\n    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;\n    z = (z ^ (z >> 27)) * 0x94d049bb133111eb;\n    return z ^ (z >> 31);\n}\n\ntemplate <typename F>\ninline auto with_instance_map(const void *ptr, const F &cb)\n    -> decltype(cb(std::declval<instance_map &>())) {\n    auto &internals = get_internals();\n\n#ifdef Py_GIL_DISABLED\n    // Hash address to compute shard, but ignore low bits. We'd like allocations\n    // from the same thread/core to map to the same shard and allocations from\n    // other threads/cores to map to other shards. Using the high bits is a good\n    // heuristic because memory allocators often have a per-thread\n    // arena/superblock/segment from which smaller allocations are served.\n    auto addr = reinterpret_cast<std::uintptr_t>(ptr);\n    auto hash = mix64(static_cast<std::uint64_t>(addr >> 20));\n    auto idx = static_cast<size_t>(hash & internals.instance_shards_mask);\n\n    auto &shard = internals.instance_shards[idx];\n    std::unique_lock<pymutex> lock(shard.mutex);\n    return cb(shard.registered_instances);\n#else\n    (void) ptr;\n    return cb(internals.registered_instances);\n#endif\n}\n\n// Returns the number of registered instances for testing purposes.  The result may not be\n// consistent if other threads are registering or unregistering instances concurrently.\ninline size_t num_registered_instances() {\n    auto &internals = get_internals();\n#ifdef Py_GIL_DISABLED\n    size_t count = 0;\n    for (size_t i = 0; i <= internals.instance_shards_mask; ++i) {\n        auto &shard = internals.instance_shards[i];\n        std::unique_lock<pymutex> lock(shard.mutex);\n        count += shard.registered_instances.size();\n    }\n    return count;\n#else\n    return internals.registered_instances.size();\n#endif\n}\n\n/// Constructs a std::string with the given arguments, stores it in `internals`, and returns its\n/// `c_str()`.  Such strings objects have a long storage duration -- the internal strings are only\n/// cleared when the program exits or after interpreter shutdown (when embedding), and so are\n/// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).\ntemplate <typename... Args>\nconst char *c_str(Args &&...args) {\n    // GCC 4.8 doesn't like parameter unpack within lambda capture, so use\n    // PYBIND11_LOCK_INTERNALS.\n    auto &internals = get_internals();\n    PYBIND11_LOCK_INTERNALS(internals);\n    auto &strings = internals.static_strings;\n    strings.emplace_front(std::forward<Args>(args)...);\n    return strings.front().c_str();\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Returns a named pointer that is shared among all extension modules (using the same\n/// pybind11 version) running in the current interpreter. Names starting with underscores\n/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.\nPYBIND11_NOINLINE void *get_shared_data(const std::string &name) {\n    return detail::with_internals([&](detail::internals &internals) {\n        auto it = internals.shared_data.find(name);\n        return it != internals.shared_data.end() ? it->second : nullptr;\n    });\n}\n\n/// Set the shared data that can be later recovered by `get_shared_data()`.\nPYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {\n    return detail::with_internals([&](detail::internals &internals) {\n        internals.shared_data[name] = data;\n        return data;\n    });\n}\n\n/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if\n/// such entry exists. Otherwise, a new object of default-constructible type `T` is\n/// added to the shared data under the given name and a reference to it is returned.\ntemplate <typename T>\nT &get_or_create_shared_data(const std::string &name) {\n    return *detail::with_internals([&](detail::internals &internals) {\n        auto it = internals.shared_data.find(name);\n        T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);\n        if (!ptr) {\n            ptr = new T();\n            internals.shared_data[name] = ptr;\n        }\n        return ptr;\n    });\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/native_enum_data.h",
    "content": "// Copyright (c) 2022-2025 The pybind Community.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"../pytypes.h\"\n#include \"common.h\"\n#include \"internals.h\"\n\n#include <cassert>\n#include <sstream>\n#include <string>\n#include <typeindex>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// This is a separate function only to enable easy unit testing.\ninline std::string\nnative_enum_missing_finalize_error_message(const std::string &enum_name_encoded) {\n    return \"pybind11::native_enum<...>(\\\"\" + enum_name_encoded + \"\\\", ...): MISSING .finalize()\";\n}\n\n// Internals for pybind11::native_enum; one native_enum_data object exists\n// inside each pybind11::native_enum and lives only for the duration of the\n// native_enum binding statement.\nclass native_enum_data {\npublic:\n    native_enum_data(handle parent_scope_,\n                     const char *enum_name,\n                     const char *native_type_name,\n                     const char *class_doc,\n                     const native_enum_record &enum_record_)\n        : enum_name_encoded{enum_name}, native_type_name_encoded{native_type_name},\n          enum_type_index{*enum_record_.cpptype},\n          parent_scope(reinterpret_borrow<object>(parent_scope_)), enum_name{enum_name},\n          native_type_name{native_type_name}, class_doc(class_doc), export_values_flag{false},\n          finalize_needed{false} {\n        // Create the enum record capsule. It will be installed on the enum\n        // type object during finalize(). Its destructor removes the enum\n        // mapping from our internals, so that we won't try to convert to an\n        // enum type that's been destroyed.\n        enum_record = capsule(\n            new native_enum_record{enum_record_},\n            native_enum_record::attribute_name(),\n            +[](void *record_) {\n                auto *record = static_cast<native_enum_record *>(record_);\n                with_internals([&](internals &internals) {\n                    internals.native_enum_type_map.erase(*record->cpptype);\n                });\n                delete record;\n            });\n    }\n\n    void finalize();\n\n    native_enum_data(const native_enum_data &) = delete;\n    native_enum_data &operator=(const native_enum_data &) = delete;\n\n#if !defined(NDEBUG)\n    // This dtor cannot easily be unit tested because it terminates the process.\n    ~native_enum_data() {\n        if (finalize_needed) {\n            pybind11_fail(native_enum_missing_finalize_error_message(enum_name_encoded));\n        }\n    }\n#endif\n\nprotected:\n    void disarm_finalize_check(const char *error_context) {\n        if (!finalize_needed) {\n            pybind11_fail(\"pybind11::native_enum<...>(\\\"\" + enum_name_encoded\n                          + \"\\\"): \" + error_context);\n        }\n        finalize_needed = false;\n    }\n\n    void arm_finalize_check() {\n        assert(!finalize_needed); // Catch redundant calls.\n        finalize_needed = true;\n    }\n\n    std::string enum_name_encoded;\n    std::string native_type_name_encoded;\n    std::type_index enum_type_index;\n\nprivate:\n    object parent_scope;\n    str enum_name;\n    str native_type_name;\n    std::string class_doc;\n    capsule enum_record;\n\nprotected:\n    list members;\n    list member_docs;\n    bool export_values_flag : 1; // Attention: It is best to keep the bools together.\n\nprivate:\n    bool finalize_needed : 1;\n};\n\ninline handle\nglobal_internals_native_enum_type_map_get_item(const std::type_index &enum_type_index) {\n    return with_internals([&](internals &internals) {\n        auto found = internals.native_enum_type_map.find(enum_type_index);\n        if (found != internals.native_enum_type_map.end()) {\n            return handle(found->second);\n        }\n        return handle();\n    });\n}\n\ninline bool\nglobal_internals_native_enum_type_map_contains(const std::type_index &enum_type_index) {\n    return with_internals([&](internals &internals) {\n        return internals.native_enum_type_map.count(enum_type_index) != 0;\n    });\n}\n\ninline object import_or_getattr(const std::string &fully_qualified_name,\n                                const std::string &append_to_exception_message) {\n    std::istringstream stream(fully_qualified_name);\n    std::string part;\n\n    if (!std::getline(stream, part, '.') || part.empty()) {\n        std::string msg = \"Invalid fully-qualified name `\";\n        msg += fully_qualified_name;\n        msg += \"`\";\n        msg += append_to_exception_message;\n        throw value_error(msg);\n    }\n\n    auto curr_scope = reinterpret_steal<object>(PyImport_ImportModule(part.c_str()));\n    if (!curr_scope) {\n        std::string msg = \"Failed to import top-level module `\";\n        msg += part;\n        msg += \"`\";\n        msg += append_to_exception_message;\n        raise_from(PyExc_ImportError, msg.c_str());\n        throw error_already_set();\n    }\n\n    // Now recursively getattr or import remaining parts\n    std::string curr_path = part;\n    while (std::getline(stream, part, '.')) {\n        if (part.empty()) {\n            std::string msg = \"Invalid fully-qualified name `\";\n            msg += fully_qualified_name;\n            msg += \"`\";\n            msg += append_to_exception_message;\n            throw value_error(msg);\n        }\n        std::string next_path = curr_path;\n        next_path += \".\";\n        next_path += part;\n        auto next_scope\n            = reinterpret_steal<object>(PyObject_GetAttrString(curr_scope.ptr(), part.c_str()));\n        if (!next_scope) {\n            error_fetch_and_normalize stored_getattr_error(\"getattr\");\n            // Try importing the next level\n            next_scope = reinterpret_steal<object>(PyImport_ImportModule(next_path.c_str()));\n            if (!next_scope) {\n                error_fetch_and_normalize stored_import_error(\"import\");\n                std::string msg = \"Failed to import or getattr `\";\n                msg += part;\n                msg += \"` from `\";\n                msg += curr_path;\n                msg += \"`\";\n                msg += append_to_exception_message;\n                msg += \"\\n-------- getattr exception --------\\n\";\n                msg += stored_getattr_error.error_string();\n                msg += \"\\n-------- import exception --------\\n\";\n                msg += stored_import_error.error_string();\n                throw import_error(msg.c_str());\n            }\n        }\n        curr_scope = next_scope;\n        curr_path = next_path;\n    }\n    return curr_scope;\n}\n\ninline void native_enum_data::finalize() {\n    disarm_finalize_check(\"DOUBLE finalize\");\n    if (hasattr(parent_scope, enum_name)) {\n        pybind11_fail(\"pybind11::native_enum<...>(\\\"\" + enum_name_encoded\n                      + \"\\\"): an object with that name is already defined\");\n    }\n    auto py_enum_type = import_or_getattr(native_type_name, \" (native_type_name)\");\n    auto py_enum = py_enum_type(enum_name, members);\n    object module_name = get_module_name_if_available(parent_scope);\n    if (module_name) {\n        py_enum.attr(\"__module__\") = module_name;\n    }\n    if (hasattr(parent_scope, \"__qualname__\")) {\n        const auto parent_qualname = parent_scope.attr(\"__qualname__\").cast<std::string>();\n        py_enum.attr(\"__qualname__\") = str(parent_qualname + \".\" + enum_name.cast<std::string>());\n    }\n    parent_scope.attr(enum_name) = py_enum;\n    if (export_values_flag) {\n        for (auto member : members) {\n            auto member_name = member[int_(0)];\n            if (hasattr(parent_scope, member_name)) {\n                pybind11_fail(\"pybind11::native_enum<...>(\\\"\" + enum_name_encoded + \"\\\").value(\\\"\"\n                              + member_name.cast<std::string>()\n                              + \"\\\"): an object with that name is already defined\");\n            }\n            parent_scope.attr(member_name) = py_enum[member_name];\n        }\n    }\n    if (!class_doc.empty()) {\n        py_enum.attr(\"__doc__\") = class_doc.c_str();\n    }\n    for (auto doc : member_docs) {\n        py_enum[doc[int_(0)]].attr(\"__doc__\") = doc[int_(1)];\n    }\n\n    py_enum.attr(native_enum_record::attribute_name()) = enum_record;\n    with_internals([&](internals &internals) {\n        internals.native_enum_type_map[enum_type_index] = py_enum.ptr();\n    });\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/pybind11_namespace_macros.h",
    "content": "// Copyright (c) 2016-2025 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n// PLEASE DO NOT ADD ANY INCLUDES HERE\n\n// Define some generic pybind11 helper macros for warning management.\n//\n// Note that compiler-specific push/pop pairs are baked into the\n// PYBIND11_NAMESPACE_BEGIN/PYBIND11_NAMESPACE_END pair of macros. Therefore manual\n// PYBIND11_WARNING_PUSH/PYBIND11_WARNING_POP are usually only needed in `#include` sections.\n//\n// If you find you need to suppress a warning, please try to make the suppression as local as\n// possible using these macros. Please also be sure to push/pop with the pybind11 macros. Please\n// only use compiler specifics if you need to check specific versions, e.g. Apple Clang vs. vanilla\n// Clang.\n#if defined(__INTEL_COMPILER)\n#    define PYBIND11_COMPILER_INTEL\n#    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)\n#    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning push)\n#    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning pop)\n#elif defined(__clang__)\n#    define PYBIND11_COMPILER_CLANG\n#    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)\n#    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(clang diagnostic push)\n#    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(clang diagnostic pop)\n#elif defined(__GNUC__)\n#    define PYBIND11_COMPILER_GCC\n#    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)\n#    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(GCC diagnostic push)\n#    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(GCC diagnostic pop)\n#elif defined(_MSC_VER) // Must be after the clang branch because clang-cl also defines _MSC_VER\n#    define PYBIND11_COMPILER_MSVC\n#    define PYBIND11_PRAGMA(...) __pragma(__VA_ARGS__)\n#    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning(push))\n#    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning(pop))\n#endif\n\n#ifdef PYBIND11_COMPILER_MSVC\n#    define PYBIND11_WARNING_DISABLE_MSVC(name) PYBIND11_PRAGMA(warning(disable : name))\n#else\n#    define PYBIND11_WARNING_DISABLE_MSVC(name)\n#endif\n\n#ifdef PYBIND11_COMPILER_CLANG\n#    define PYBIND11_WARNING_DISABLE_CLANG(name) PYBIND11_PRAGMA(clang diagnostic ignored name)\n#else\n#    define PYBIND11_WARNING_DISABLE_CLANG(name)\n#endif\n\n#ifdef PYBIND11_COMPILER_GCC\n#    define PYBIND11_WARNING_DISABLE_GCC(name) PYBIND11_PRAGMA(GCC diagnostic ignored name)\n#else\n#    define PYBIND11_WARNING_DISABLE_GCC(name)\n#endif\n\n#ifdef PYBIND11_COMPILER_INTEL\n#    define PYBIND11_WARNING_DISABLE_INTEL(name) PYBIND11_PRAGMA(warning disable name)\n#else\n#    define PYBIND11_WARNING_DISABLE_INTEL(name)\n#endif\n\n#define PYBIND11_NAMESPACE_BEGIN(name)                                                            \\\n    namespace name {                                                                              \\\n    PYBIND11_WARNING_PUSH\n\n#define PYBIND11_NAMESPACE_END(name)                                                              \\\n    PYBIND11_WARNING_POP                                                                          \\\n    }\n\n// Robust support for some features and loading modules compiled against different pybind versions\n// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute\n// on the main `pybind11` namespace.\n#if !defined(PYBIND11_NAMESPACE)\n#    if defined(__GNUG__) && !defined(_WIN32)\n#        define PYBIND11_NAMESPACE pybind11 __attribute__((visibility(\"hidden\")))\n#    else\n#        define PYBIND11_NAMESPACE pybind11\n#    endif\n#endif\n"
  },
  {
    "path": "include/pybind11/detail/struct_smart_holder.h",
    "content": "// Copyright (c) 2020-2024 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n/* Proof-of-Concept for smart pointer interoperability.\n\nHigh-level aspects:\n\n* Support all `unique_ptr`, `shared_ptr` interops that are feasible.\n\n* Cleanly and clearly report all interops that are infeasible.\n\n* Meant to fit into a `PyObject`, as a holder for C++ objects.\n\n* Support a system design that makes it impossible to trigger\n  C++ Undefined Behavior, especially from Python.\n\n* Support a system design with clean runtime inheritance casting. From this\n  it follows that the `smart_holder` needs to be type-erased (`void*`).\n\n* Handling of RTTI for the type-erased held pointer is NOT implemented here.\n  It is the responsibility of the caller to ensure that `static_cast<T *>`\n  is well-formed when calling `as_*` member functions. Inheritance casting\n  needs to be handled in a different layer (similar to the code organization\n  in boost/python/object/inheritance.hpp).\n\nDetails:\n\n* The \"root holder\" chosen here is a `shared_ptr<void>` (named `vptr` in this\n  implementation). This choice is practically inevitable because `shared_ptr`\n  has only very limited support for inspecting and accessing its deleter.\n\n* If created from a raw pointer, or a `unique_ptr` without a custom deleter,\n  `vptr` always uses a custom deleter, to support `unique_ptr`-like disowning.\n  The custom deleters could be extended to included life-time management for\n  external objects (e.g. `PyObject`).\n\n* If created from an external `shared_ptr`, or a `unique_ptr` with a custom\n  deleter, including life-time management for external objects is infeasible.\n\n* By choice, the smart_holder is movable but not copyable, to keep the design\n  simple, and to guard against accidental copying overhead.\n\n* The `void_cast_raw_ptr` option is needed to make the `smart_holder` `vptr`\n  member invisible to the `shared_from_this` mechanism, in case the lifetime\n  of a `PyObject` is tied to the pointee.\n*/\n\n#pragma once\n\n#include \"pybind11_namespace_macros.h\"\n\n#include <cstring>\n#include <functional>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(memory)\n\n// Default fallback.\nstatic constexpr bool type_has_shared_from_this(...) { return false; }\n\n// This overload uses SFINAE to skip enable_shared_from_this checks when the\n// base is inaccessible (e.g. private inheritance).\ntemplate <typename T>\nstatic auto type_has_shared_from_this(const T *ptr)\n    -> decltype(static_cast<const std::enable_shared_from_this<T> *>(ptr), true) {\n    return true;\n}\n\n// Inaccessible base → substitution failure → fallback overload selected\ntemplate <typename T>\nstatic constexpr bool type_has_shared_from_this(const void *) {\n    return false;\n}\n\nstruct guarded_delete {\n    // NOTE: PYBIND11_INTERNALS_VERSION needs to be bumped if changes are made to this struct.\n    std::weak_ptr<void> released_ptr;    // Trick to keep the smart_holder memory footprint small.\n    std::function<void(void *)> del_fun; // Rare case.\n    void (*del_ptr)(void *);             // Common case.\n    bool use_del_fun;\n    bool armed_flag;\n    guarded_delete(std::function<void(void *)> &&del_fun, bool armed_flag)\n        : del_fun{std::move(del_fun)}, del_ptr{nullptr}, use_del_fun{true},\n          armed_flag{armed_flag} {}\n    guarded_delete(void (*del_ptr)(void *), bool armed_flag)\n        : del_ptr{del_ptr}, use_del_fun{false}, armed_flag{armed_flag} {}\n    void operator()(void *raw_ptr) const {\n        if (armed_flag) {\n            if (use_del_fun) {\n                del_fun(raw_ptr);\n            } else {\n                del_ptr(raw_ptr);\n            }\n        }\n    }\n};\n\ninline guarded_delete *get_guarded_delete(const std::shared_ptr<void> &ptr) {\n    return std::get_deleter<guarded_delete>(ptr);\n}\n\nusing get_guarded_delete_fn = guarded_delete *(*) (const std::shared_ptr<void> &);\n\ntemplate <typename T, typename std::enable_if<std::is_destructible<T>::value, int>::type = 0>\ninline void std_default_delete_if_destructible(void *raw_ptr) {\n    std::default_delete<T>{}(static_cast<T *>(raw_ptr));\n}\n\ntemplate <typename T, typename std::enable_if<!std::is_destructible<T>::value, int>::type = 0>\ninline void std_default_delete_if_destructible(void *) {\n    // This noop operator is needed to avoid a compilation error (for `delete raw_ptr;`), but\n    // throwing an exception from a destructor will std::terminate the process. Therefore the\n    // runtime check for lifetime-management correctness is implemented elsewhere (in\n    // ensure_pointee_is_destructible()).\n}\n\ntemplate <typename T>\nguarded_delete make_guarded_std_default_delete(bool armed_flag) {\n    return guarded_delete(std_default_delete_if_destructible<T>, armed_flag);\n}\n\ntemplate <typename T, typename D>\nstruct custom_deleter {\n    // NOTE: PYBIND11_INTERNALS_VERSION needs to be bumped if changes are made to this struct.\n    D deleter;\n    explicit custom_deleter(D &&deleter) : deleter{std::forward<D>(deleter)} {}\n    void operator()(void *raw_ptr) { deleter(static_cast<T *>(raw_ptr)); }\n};\n\ntemplate <typename T, typename D>\nguarded_delete make_guarded_custom_deleter(D &&uqp_del, bool armed_flag) {\n    return guarded_delete(\n        std::function<void(void *)>(custom_deleter<T, D>(std::forward<D>(uqp_del))), armed_flag);\n}\n\ntemplate <typename T, typename D>\nconstexpr bool uqp_del_is_std_default_delete() {\n    return std::is_same<D, std::default_delete<T>>::value\n           || std::is_same<D, std::default_delete<T const>>::value;\n}\n\ninline bool type_info_equal_across_dso_boundaries(const std::type_info &a,\n                                                  const std::type_info &b) {\n    // RTTI pointer comparison may fail across DSOs (e.g., macOS libc++).\n    // Fallback to name comparison, which is generally safe and ABI-stable enough for our use.\n    return a == b || std::strcmp(a.name(), b.name()) == 0;\n}\n\nstruct smart_holder {\n    // NOTE: PYBIND11_INTERNALS_VERSION needs to be bumped if changes are made to this struct.\n    const std::type_info *rtti_uqp_del = nullptr;\n    std::shared_ptr<void> vptr;\n    bool vptr_is_using_noop_deleter : 1;\n    bool vptr_is_using_std_default_delete : 1;\n    bool vptr_is_external_shared_ptr : 1;\n    bool is_populated : 1;\n    bool is_disowned : 1;\n\n    // Design choice: smart_holder is movable but not copyable.\n    smart_holder(smart_holder &&) = default;\n    smart_holder(const smart_holder &) = delete;\n    smart_holder &operator=(smart_holder &&) = delete;\n    smart_holder &operator=(const smart_holder &) = delete;\n\n    smart_holder()\n        : vptr_is_using_noop_deleter{false}, vptr_is_using_std_default_delete{false},\n          vptr_is_external_shared_ptr{false}, is_populated{false}, is_disowned{false} {}\n\n    bool has_pointee() const { return vptr != nullptr; }\n\n    template <typename T>\n    static void ensure_pointee_is_destructible(const char *context) {\n        if (!std::is_destructible<T>::value) {\n            throw std::invalid_argument(std::string(\"Pointee is not destructible (\") + context\n                                        + \").\");\n        }\n    }\n\n    void ensure_is_populated(const char *context) const {\n        if (!is_populated) {\n            throw std::runtime_error(std::string(\"Unpopulated holder (\") + context + \").\");\n        }\n    }\n    void ensure_is_not_disowned(const char *context) const {\n        if (is_disowned) {\n            throw std::runtime_error(std::string(\"Holder was disowned already (\") + context\n                                     + \").\");\n        }\n    }\n\n    void ensure_vptr_is_using_std_default_delete(const char *context) const {\n        if (vptr_is_external_shared_ptr) {\n            throw std::invalid_argument(std::string(\"Cannot disown external shared_ptr (\")\n                                        + context + \").\");\n        }\n        if (vptr_is_using_noop_deleter) {\n            throw std::invalid_argument(std::string(\"Cannot disown non-owning holder (\") + context\n                                        + \").\");\n        }\n        if (!vptr_is_using_std_default_delete) {\n            throw std::invalid_argument(std::string(\"Cannot disown custom deleter (\") + context\n                                        + \").\");\n        }\n    }\n\n    template <typename T, typename D>\n    void ensure_compatible_uqp_del(const char *context) const {\n        if (!rtti_uqp_del) {\n            if (!uqp_del_is_std_default_delete<T, D>()) {\n                throw std::invalid_argument(std::string(\"Missing unique_ptr deleter (\") + context\n                                            + \").\");\n            }\n            ensure_vptr_is_using_std_default_delete(context);\n            return;\n        }\n        if (uqp_del_is_std_default_delete<T, D>() && vptr_is_using_std_default_delete) {\n            return;\n        }\n        if (!type_info_equal_across_dso_boundaries(typeid(D), *rtti_uqp_del)) {\n            throw std::invalid_argument(std::string(\"Incompatible unique_ptr deleter (\") + context\n                                        + \").\");\n        }\n    }\n\n    void ensure_has_pointee(const char *context) const {\n        if (!has_pointee()) {\n            throw std::invalid_argument(std::string(\"Disowned holder (\") + context + \").\");\n        }\n    }\n\n    void ensure_use_count_1(const char *context) const {\n        if (vptr == nullptr) {\n            throw std::invalid_argument(std::string(\"Cannot disown nullptr (\") + context + \").\");\n        }\n        // In multithreaded environments accessing use_count can lead to\n        // race conditions, but in the context of Python it is a bug (elsewhere)\n        // if the Global Interpreter Lock (GIL) is not being held when this code\n        // is reached.\n        // PYBIND11:REMINDER: This may need to be protected by a mutex in free-threaded Python.\n        if (vptr.use_count() != 1) {\n            throw std::invalid_argument(std::string(\"Cannot disown use_count != 1 (\") + context\n                                        + \").\");\n        }\n    }\n\n    void reset_vptr_deleter_armed_flag(const get_guarded_delete_fn ggd_fn, bool armed_flag) const {\n        auto *gd = ggd_fn(vptr);\n        if (gd == nullptr) {\n            throw std::runtime_error(\n                \"smart_holder::reset_vptr_deleter_armed_flag() called in an invalid context.\");\n        }\n        gd->armed_flag = armed_flag;\n    }\n\n    // Caller is responsible for precondition: ensure_compatible_uqp_del<T, D>() must succeed.\n    template <typename T, typename D>\n    std::unique_ptr<D> extract_deleter(const char *context,\n                                       const get_guarded_delete_fn ggd_fn) const {\n        auto *gd = ggd_fn(vptr);\n        if (gd && gd->use_del_fun) {\n            const auto &custom_deleter_ptr = gd->del_fun.template target<custom_deleter<T, D>>();\n            if (custom_deleter_ptr == nullptr) {\n                throw std::runtime_error(\n                    std::string(\"smart_holder::extract_deleter() precondition failure (\") + context\n                    + \").\");\n            }\n            static_assert(std::is_copy_constructible<D>::value,\n                          \"Required for compatibility with smart_holder functionality.\");\n            return std::unique_ptr<D>(new D(custom_deleter_ptr->deleter));\n        }\n        return nullptr;\n    }\n\n    static smart_holder from_raw_ptr_unowned(void *raw_ptr) {\n        smart_holder hld;\n        hld.vptr.reset(raw_ptr, [](void *) {});\n        hld.vptr_is_using_noop_deleter = true;\n        hld.is_populated = true;\n        return hld;\n    }\n\n    template <typename T>\n    T *as_raw_ptr_unowned() const {\n        return static_cast<T *>(vptr.get());\n    }\n\n    template <typename T>\n    static smart_holder from_raw_ptr_take_ownership(T *raw_ptr, bool void_cast_raw_ptr = false) {\n        ensure_pointee_is_destructible<T>(\"from_raw_ptr_take_ownership\");\n        smart_holder hld;\n        auto gd = make_guarded_std_default_delete<T>(true);\n        if (void_cast_raw_ptr) {\n            hld.vptr.reset(static_cast<void *>(raw_ptr), std::move(gd));\n        } else {\n            hld.vptr.reset(raw_ptr, std::move(gd));\n        }\n        hld.vptr_is_using_std_default_delete = true;\n        hld.is_populated = true;\n        return hld;\n    }\n\n    // Caller is responsible for ensuring the complex preconditions\n    // (see `smart_holder_type_caster_support::load_helper`).\n    void disown(const get_guarded_delete_fn ggd_fn) {\n        reset_vptr_deleter_armed_flag(ggd_fn, false);\n        is_disowned = true;\n    }\n\n    // Caller is responsible for ensuring the complex preconditions\n    // (see `smart_holder_type_caster_support::load_helper`).\n    void reclaim_disowned(const get_guarded_delete_fn ggd_fn) {\n        reset_vptr_deleter_armed_flag(ggd_fn, true);\n        is_disowned = false;\n    }\n\n    // Caller is responsible for ensuring the complex preconditions\n    // (see `smart_holder_type_caster_support::load_helper`).\n    void release_disowned() { vptr.reset(); }\n\n    void ensure_can_release_ownership(const char *context = \"ensure_can_release_ownership\") const {\n        ensure_is_not_disowned(context);\n        ensure_vptr_is_using_std_default_delete(context);\n        ensure_use_count_1(context);\n    }\n\n    // Caller is responsible for ensuring the complex preconditions\n    // (see `smart_holder_type_caster_support::load_helper`).\n    void release_ownership(const get_guarded_delete_fn ggd_fn) {\n        reset_vptr_deleter_armed_flag(ggd_fn, false);\n        release_disowned();\n    }\n\n    template <typename T, typename D>\n    static smart_holder from_unique_ptr(std::unique_ptr<T, D> &&unq_ptr,\n                                        void *mi_subobject_ptr = nullptr) {\n        smart_holder hld;\n        hld.rtti_uqp_del = &typeid(D);\n        hld.vptr_is_using_std_default_delete = uqp_del_is_std_default_delete<T, D>();\n\n        // Build the owning control block on the *real object start* (T*).\n        guarded_delete gd\n            = hld.vptr_is_using_std_default_delete\n                  ? make_guarded_std_default_delete<T>(true)\n                  : make_guarded_custom_deleter<T, D>(std::move(unq_ptr.get_deleter()), true);\n        // Critical: construct owner with pointer we intend to delete\n        std::shared_ptr<T> owner(unq_ptr.get(), std::move(gd));\n        // Relinquish ownership only after successful construction of owner\n        (void) unq_ptr.release();\n\n        // Publish either the MI/VI subobject pointer (if provided) or the full object.\n        // Why this is needed:\n        //   * The `owner` shared_ptr must always manage the true object start (T*).\n        //     That ensures the deleter is invoked on a valid object header, so the\n        //     virtual destructor can dispatch safely (critical on MSVC with virtual\n        //     inheritance, where base subobjects are not at offset 0).\n        //   * However, pybind11 needs to *register* and expose the subobject pointer\n        //     appropriate for the type being bound.\n        //     This pointer may differ from the T* object start under multiple/virtual\n        //     inheritance.\n        // This is achieved by using an aliasing shared_ptr<void>:\n        //   - `owner` retains lifetime of the actual T* object start for deletion.\n        //   - `vptr` points at the adjusted subobject (mi_subobject_ptr), giving\n        //     Python the correct identity/registration address.\n        // If no subobject pointer is passed, we simply publish the full object.\n        if (mi_subobject_ptr) {\n            hld.vptr = std::shared_ptr<void>(owner, mi_subobject_ptr);\n        } else {\n            hld.vptr = std::static_pointer_cast<void>(owner);\n        }\n\n        hld.is_populated = true;\n        return hld;\n    }\n\n    template <typename T>\n    static smart_holder from_shared_ptr(const std::shared_ptr<T> &shd_ptr) {\n        smart_holder hld;\n        hld.vptr = std::static_pointer_cast<void>(shd_ptr);\n        hld.vptr_is_external_shared_ptr = true;\n        hld.is_populated = true;\n        return hld;\n    }\n\n    template <typename T>\n    std::shared_ptr<T> as_shared_ptr() const {\n        return std::static_pointer_cast<T>(vptr);\n    }\n};\n\nPYBIND11_NAMESPACE_END(memory)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/type_caster_base.h",
    "content": "/*\n    pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/gil.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/trampoline_self_life_support.h>\n\n#include \"common.h\"\n#include \"cpp_conduit.h\"\n#include \"descr.h\"\n#include \"dynamic_raw_ptr_cast_if_possible.h\"\n#include \"internals.h\"\n#include \"typeid.h\"\n#include \"using_smart_holder.h\"\n#include \"value_and_holder.h\"\n\n#include <cstdint>\n#include <cstring>\n#include <iterator>\n#include <new>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <typeindex>\n#include <typeinfo>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/// A life support system for temporary objects created by `type_caster::load()`.\n/// Adding a patient will keep it alive up until the enclosing function returns.\nclass loader_life_support {\nprivate:\n    // Thread-local top-of-stack for loader_life_support frames (linked via parent).\n    // Observation: loader_life_support needs to be thread-local,\n    // but we don't need to go to extra effort to keep it\n    // per-interpreter (i.e., by putting it in internals) since\n    // individual function calls are already isolated to a single\n    // interpreter, even though they could potentially call into a\n    // different interpreter later in the same call chain.  This\n    // saves a significant cost per function call spent in\n    // loader_life_support destruction.\n    // Note for future C++17 simplification:\n    // inline static thread_local loader_life_support *tls_current_frame = nullptr;\n    static loader_life_support *&tls_current_frame() {\n        static thread_local loader_life_support *frame_ptr = nullptr;\n        return frame_ptr;\n    }\n\n    loader_life_support *parent = nullptr;\n    std::unordered_set<PyObject *> keep_alive;\n\npublic:\n    /// A new patient frame is created when a function is entered\n    loader_life_support() {\n        auto &frame = tls_current_frame();\n        parent = frame;\n        frame = this;\n    }\n\n    /// ... and destroyed after it returns\n    ~loader_life_support() {\n        auto &frame = tls_current_frame();\n        if (frame != this) {\n            pybind11_fail(\"loader_life_support: internal error\");\n        }\n        frame = parent;\n        for (auto *item : keep_alive) {\n            Py_DECREF(item);\n        }\n    }\n\n    /// This can only be used inside a pybind11-bound function, either by `argument_loader`\n    /// at argument preparation time or by `py::cast()` at execution time.\n    PYBIND11_NOINLINE static void add_patient(handle h) {\n        loader_life_support *frame = tls_current_frame();\n        if (!frame) {\n            // NOTE: It would be nice to include the stack frames here, as this indicates\n            // use of pybind11::cast<> outside the normal call framework, finding such\n            // a location is challenging. Developers could consider printing out\n            // stack frame addresses here using something like __builtin_frame_address(0)\n            throw cast_error(\"When called outside a bound function, py::cast() cannot \"\n                             \"do Python -> C++ conversions which require the creation \"\n                             \"of temporary values\");\n        }\n\n        if (frame->keep_alive.insert(h.ptr()).second) {\n            Py_INCREF(h.ptr());\n        }\n    }\n};\n\n// Gets the cache entry for the given type, creating it if necessary.  The return value is the pair\n// returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was\n// just created.\ninline std::pair<decltype(internals::registered_types_py)::iterator, bool>\nall_type_info_get_cache(PyTypeObject *type);\n\n// Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.\ninline void all_type_info_add_base_most_derived_first(std::vector<type_info *> &bases,\n                                                      type_info *addl_base) {\n    for (auto it = bases.begin(); it != bases.end(); it++) {\n        type_info *existing_base = *it;\n        if (PyType_IsSubtype(addl_base->type, existing_base->type) != 0) {\n            bases.insert(it, addl_base);\n            return;\n        }\n    }\n    bases.push_back(addl_base);\n}\n\n// Populates a just-created cache entry.\nPYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {\n    assert(bases.empty());\n    std::vector<PyTypeObject *> check;\n    for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {\n        check.push_back(reinterpret_cast<PyTypeObject *>(parent.ptr()));\n    }\n    auto const &type_dict = get_internals().registered_types_py;\n    for (size_t i = 0; i < check.size(); i++) {\n        auto *type = check[i];\n        // Ignore Python2 old-style class super type:\n        if (!PyType_Check((PyObject *) type)) {\n            continue;\n        }\n\n        // Check `type` in the current set of registered python types:\n        auto it = type_dict.find(type);\n        if (it != type_dict.end()) {\n            // We found a cache entry for it, so it's either pybind-registered or has pre-computed\n            // pybind bases, but we have to make sure we haven't already seen the type(s) before:\n            // we want to follow Python/virtual C++ rules that there should only be one instance of\n            // a common base.\n            for (auto *tinfo : it->second) {\n                // NB: Could use a second set here, rather than doing a linear search, but since\n                // having a large number of immediate pybind11-registered types seems fairly\n                // unlikely, that probably isn't worthwhile.\n                bool found = false;\n                for (auto *known : bases) {\n                    if (known == tinfo) {\n                        found = true;\n                        break;\n                    }\n                }\n                if (!found) {\n                    all_type_info_add_base_most_derived_first(bases, tinfo);\n                }\n            }\n        } else if (type->tp_bases) {\n            // It's some python type, so keep follow its bases classes to look for one or more\n            // registered types\n            if (i + 1 == check.size()) {\n                // When we're at the end, we can pop off the current element to avoid growing\n                // `check` when adding just one base (which is typical--i.e. when there is no\n                // multiple inheritance)\n                check.pop_back();\n                i--;\n            }\n            for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {\n                check.push_back(reinterpret_cast<PyTypeObject *>(parent.ptr()));\n            }\n        }\n    }\n}\n\n/**\n * Extracts vector of type_info pointers of pybind-registered roots of the given Python type.  Will\n * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side\n * derived class that uses single inheritance.  Will contain as many types as required for a Python\n * class that uses multiple inheritance to inherit (directly or indirectly) from multiple\n * pybind-registered classes.  Will be empty if neither the type nor any base classes are\n * pybind-registered.\n *\n * The value is cached for the lifetime of the Python type.\n */\ninline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {\n    return all_type_info_get_cache(type).first->second;\n}\n\n/**\n * Gets a single pybind11 type info for a python type.  Returns nullptr if neither the type nor any\n * ancestors are pybind11-registered.  Throws an exception if there are multiple bases--use\n * `all_type_info` instead if you want to support multiple bases.\n */\nPYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {\n    const auto &bases = all_type_info(type);\n    if (bases.empty()) {\n        return nullptr;\n    }\n    if (bases.size() > 1) {\n        pybind11_fail(\n            \"pybind11::detail::get_type_info: type has multiple pybind11-registered bases\");\n    }\n    return bases.front();\n}\n\ninline detail::type_info *get_local_type_info_lock_held(const std::type_info &tp) {\n    const auto &locals = get_local_internals().registered_types_cpp;\n    auto it = locals.find(&tp);\n    if (it != locals.end()) {\n        return it->second;\n    }\n    return nullptr;\n}\n\ninline detail::type_info *get_local_type_info(const std::type_info &tp) {\n    // NB: internals and local_internals share a single mutex\n    PYBIND11_LOCK_INTERNALS(get_internals());\n    return get_local_type_info_lock_held(tp);\n}\n\ninline detail::type_info *get_global_type_info_lock_held(const std::type_info &tp) {\n    // This is a two-level lookup. Hopefully we find the type info in\n    // registered_types_cpp_fast, but if not we try\n    // registered_types_cpp and fill registered_types_cpp_fast for\n    // next time.\n    detail::type_info *type_info = nullptr;\n    auto &internals = get_internals();\n#if PYBIND11_INTERNALS_VERSION >= 12\n    auto &fast_types = internals.registered_types_cpp_fast;\n#endif\n    auto &types = internals.registered_types_cpp;\n#if PYBIND11_INTERNALS_VERSION >= 12\n    auto fast_it = fast_types.find(&tp);\n    if (fast_it != fast_types.end()) {\n#    ifndef NDEBUG\n        auto types_it = types.find(std::type_index(tp));\n        assert(types_it != types.end());\n        assert(types_it->second == fast_it->second);\n#    endif\n        return fast_it->second;\n    }\n#endif // PYBIND11_INTERNALS_VERSION >= 12\n\n    auto it = types.find(std::type_index(tp));\n    if (it != types.end()) {\n#if PYBIND11_INTERNALS_VERSION >= 12\n        // We found the type in the slow map but not the fast one, so\n        // some other DSO added it (otherwise it would be in the fast\n        // map under &tp) and therefore we must be an alias. Record\n        // that.\n        it->second->alias_chain.push_front(&tp);\n        fast_types.emplace(&tp, it->second);\n#endif\n        type_info = it->second;\n    }\n    return type_info;\n}\n\ninline detail::type_info *get_global_type_info(const std::type_info &tp) {\n    PYBIND11_LOCK_INTERNALS(get_internals());\n    return get_global_type_info_lock_held(tp);\n}\n\n/// Return the type info for a given C++ type; on lookup failure can either throw or return\n/// nullptr.\nPYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_info &tp,\n                                                   bool throw_if_missing = false) {\n    PYBIND11_LOCK_INTERNALS(get_internals());\n    if (auto *ltype = get_local_type_info_lock_held(tp)) {\n        return ltype;\n    }\n    if (auto *gtype = get_global_type_info_lock_held(tp)) {\n        return gtype;\n    }\n\n    if (throw_if_missing) {\n        std::string tname = tp.name();\n        detail::clean_type_id(tname);\n        pybind11_fail(\"pybind11::detail::get_type_info: unable to find type info for \\\"\"\n                      + std::move(tname) + '\"');\n    }\n    return nullptr;\n}\n\nPYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {\n    detail::type_info *type_info = get_type_info(tp, throw_if_missing);\n    return handle(type_info ? (reinterpret_cast<PyObject *>(type_info->type)) : nullptr);\n}\n\ninline bool try_incref(PyObject *obj) {\n    // Tries to increment the reference count of an object if it's not zero.\n#if defined(Py_GIL_DISABLED) && PY_VERSION_HEX >= 0x030E00A4\n    return PyUnstable_TryIncRef(obj);\n#elif defined(Py_GIL_DISABLED)\n    // See\n    // https://github.com/python/cpython/blob/d05140f9f77d7dfc753dd1e5ac3a5962aaa03eff/Include/internal/pycore_object.h#L761\n    uint32_t local = _Py_atomic_load_uint32_relaxed(&obj->ob_ref_local);\n    local += 1;\n    if (local == 0) {\n        // immortal\n        return true;\n    }\n    if (_Py_IsOwnedByCurrentThread(obj)) {\n        _Py_atomic_store_uint32_relaxed(&obj->ob_ref_local, local);\n#    ifdef Py_REF_DEBUG\n        _Py_INCREF_IncRefTotal();\n#    endif\n        return true;\n    }\n    Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared);\n    for (;;) {\n        // If the shared refcount is zero and the object is either merged\n        // or may not have weak references, then we cannot incref it.\n        if (shared == 0 || shared == _Py_REF_MERGED) {\n            return false;\n        }\n\n        if (_Py_atomic_compare_exchange_ssize(\n                &obj->ob_ref_shared, &shared, shared + (1 << _Py_REF_SHARED_SHIFT))) {\n#    ifdef Py_REF_DEBUG\n            _Py_INCREF_IncRefTotal();\n#    endif\n            return true;\n        }\n    }\n#else\n    assert(Py_REFCNT(obj) > 0);\n    Py_INCREF(obj);\n    return true;\n#endif\n}\n\n// Searches the inheritance graph for a registered Python instance, using all_type_info().\nPYBIND11_NOINLINE handle find_registered_python_instance(void *src,\n                                                         const detail::type_info *tinfo) {\n    return with_instance_map(src, [&](instance_map &instances) {\n        auto it_instances = instances.equal_range(src);\n        for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {\n            for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {\n                if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {\n                    auto *wrapper = reinterpret_cast<PyObject *>(it_i->second);\n                    if (try_incref(wrapper)) {\n                        return handle(wrapper);\n                    }\n                }\n            }\n        }\n        return handle();\n    });\n}\n\n// Container for accessing and iterating over an instance's values/holders\nstruct values_and_holders {\nprivate:\n    instance *inst;\n    using type_vec = std::vector<detail::type_info *>;\n    const type_vec &tinfo;\n\npublic:\n    explicit values_and_holders(instance *inst)\n        : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}\n\n    explicit values_and_holders(PyObject *obj)\n        : inst{nullptr}, tinfo(all_type_info(Py_TYPE(obj))) {\n        if (!tinfo.empty()) {\n            inst = reinterpret_cast<instance *>(obj);\n        }\n    }\n\n    struct iterator {\n    private:\n        instance *inst = nullptr;\n        const type_vec *types = nullptr;\n        value_and_holder curr;\n        friend struct values_and_holders;\n        iterator(instance *inst, const type_vec *tinfo) : inst{inst}, types{tinfo} {\n            if (inst != nullptr) {\n                assert(!types->empty());\n                curr = value_and_holder(\n                    inst /* instance */,\n                    (*types)[0] /* type info */,\n                    0, /* vpos: (non-simple types only): the first vptr comes first */\n                    0 /* index */);\n            }\n        }\n        // Past-the-end iterator:\n        explicit iterator(size_t end) : curr(end) {}\n\n    public:\n        bool operator==(const iterator &other) const { return curr.index == other.curr.index; }\n        bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }\n        iterator &operator++() {\n            if (!inst->simple_layout) {\n                curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;\n            }\n            ++curr.index;\n            curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;\n            return *this;\n        }\n        value_and_holder &operator*() { return curr; }\n        value_and_holder *operator->() { return &curr; }\n    };\n\n    iterator begin() { return iterator(inst, &tinfo); }\n    iterator end() { return iterator(tinfo.size()); }\n\n    iterator find(const type_info *find_type) {\n        auto it = begin(), endit = end();\n        while (it != endit && it->type != find_type) {\n            ++it;\n        }\n        return it;\n    }\n\n    size_t size() { return tinfo.size(); }\n\n    // Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.\n    bool is_redundant_value_and_holder(const value_and_holder &vh) {\n        for (size_t i = 0; i < vh.index; i++) {\n            if (PyType_IsSubtype(tinfo[i]->type, tinfo[vh.index]->type) != 0) {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\n/**\n * Extracts C++ value and holder pointer references from an instance (which may contain multiple\n * values/holders for python-side multiple inheritance) that match the given type.  Throws an error\n * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance.  If\n * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,\n * regardless of type (and the resulting .type will be nullptr).\n *\n * The returned object should be short-lived: in particular, it must not outlive the called-upon\n * instance.\n */\nPYBIND11_NOINLINE value_and_holder\ninstance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,\n                               bool throw_if_missing /*= true in common.h*/) {\n    // Optimize common case:\n    if (!find_type || Py_TYPE(this) == find_type->type) {\n        return value_and_holder(this, find_type, 0, 0);\n    }\n\n    detail::values_and_holders vhs(this);\n    auto it = vhs.find(find_type);\n    if (it != vhs.end()) {\n        return *it;\n    }\n\n    if (!throw_if_missing) {\n        return value_and_holder();\n    }\n\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n    pybind11_fail(\"pybind11::detail::instance::get_value_and_holder: `\"\n                  + get_fully_qualified_tp_name(find_type->type)\n                  + \"' is not a pybind11 base of the given `\"\n                  + get_fully_qualified_tp_name(Py_TYPE(this)) + \"' instance\");\n#else\n    pybind11_fail(\n        \"pybind11::detail::instance::get_value_and_holder: \"\n        \"type is not a pybind11 base of the given instance \"\n        \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)\");\n#endif\n}\n\nPYBIND11_NOINLINE void instance::allocate_layout() {\n    const auto &tinfo = all_type_info(Py_TYPE(this));\n\n    const size_t n_types = tinfo.size();\n\n    if (n_types == 0) {\n        pybind11_fail(\n            \"instance allocation failed: new instance has no pybind11-registered base types\");\n    }\n\n    simple_layout\n        = n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();\n\n    // Simple path: no python-side multiple inheritance, and a small-enough holder\n    if (simple_layout) {\n        simple_value_holder[0] = nullptr;\n        simple_holder_constructed = false;\n        simple_instance_registered = false;\n    } else { // multiple base types or a too-large holder\n        // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,\n        // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool\n        // values that tracks whether each associated holder has been initialized.  Each [block] is\n        // padded, if necessary, to an integer multiple of sizeof(void *).\n        size_t space = 0;\n        for (auto *t : tinfo) {\n            space += 1;                      // value pointer\n            space += t->holder_size_in_ptrs; // holder instance\n        }\n        size_t flags_at = space;\n        space += size_in_ptrs(n_types); // status bytes (holder_constructed and\n                                        // instance_registered)\n\n        // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,\n        // in particular, need to be 0).  Use Python's memory allocation\n        // functions: Python is using pymalloc, which is designed to be\n        // efficient for small allocations like the one we're doing here;\n        // for larger allocations they are just wrappers around malloc.\n        // TODO: is this still true for pure Python 3.6?\n        nonsimple.values_and_holders = static_cast<void **>(PyMem_Calloc(space, sizeof(void *)));\n        if (!nonsimple.values_and_holders) {\n            throw std::bad_alloc();\n        }\n        nonsimple.status\n            = reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);\n    }\n    owned = true;\n}\n\n// NOLINTNEXTLINE(readability-make-member-function-const)\nPYBIND11_NOINLINE void instance::deallocate_layout() {\n    if (!simple_layout) {\n        PyMem_Free(reinterpret_cast<void *>(nonsimple.values_and_holders));\n    }\n}\n\nPYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {\n    handle type = detail::get_type_handle(tp, false);\n    if (!type) {\n        return false;\n    }\n    return isinstance(obj, type);\n}\n\nPYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {\n    return with_instance_map(ptr, [&](instance_map &instances) {\n        auto range = instances.equal_range(ptr);\n        for (auto it = range.first; it != range.second; ++it) {\n            for (const auto &vh : values_and_holders(it->second)) {\n                if (vh.type == type) {\n                    return handle(reinterpret_cast<PyObject *>(it->second));\n                }\n            }\n        }\n        return handle();\n    });\n}\n\n// Information about how type_caster_generic::cast() can obtain its source object\nstruct cast_sources {\n    // A type-erased pointer and the type it points to\n    struct raw_source {\n        const void *cppobj;\n        const std::type_info *cpptype;\n    };\n\n    // A C++ pointer and the Python type info we will convert it to;\n    // we expect that cppobj points to something of type tinfo->cpptype\n    struct resolved_source {\n        const void *cppobj;\n        const type_info *tinfo;\n    };\n\n    // Use the given pointer with its compile-time type, possibly downcast\n    // via polymorphic_type_hook()\n    template <typename itype>\n    explicit cast_sources(const itype *ptr);\n\n    // Use the given pointer and type\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cast_sources(const raw_source &orig) : original(orig) { result = resolve(); }\n\n    // Use the given object and pybind11 type info. NB: if tinfo is null,\n    // this does not provide enough information to use a foreign type or\n    // to render a useful error message\n    cast_sources(const void *obj, const detail::type_info *tinfo)\n        : original{obj, tinfo ? tinfo->cpptype : nullptr}, result{obj, tinfo} {}\n\n    // The object passed to cast(), with its static type.\n    // original.type must not be null if resolve() will be called.\n    // original.obj may be null if we're converting nullptr to a Python None\n    raw_source original;\n\n    // A more-derived version of `original` provided by a\n    // polymorphic_type_hook. downcast.type may be null if this is not\n    // a relevant concept for the current cast.\n    raw_source downcast{};\n\n    // The source to use for this cast, and the corresponding pybind11\n    // type_info. If the type_info is null, then pybind11 doesn't know\n    // about this type.\n    resolved_source result;\n\n    // Returns true if the cast will use a pybind11 type that uses\n    // a smart holder.\n    bool creates_smart_holder() const {\n        return result.tinfo != nullptr\n               && result.tinfo->holder_enum_v == detail::holder_enum_t::smart_holder;\n    }\n\nprivate:\n    resolved_source resolve() {\n        if (downcast.cpptype) {\n            if (same_type(*original.cpptype, *downcast.cpptype)) {\n                downcast.cpptype = nullptr;\n            } else if (const auto *tpi = get_type_info(*downcast.cpptype)) {\n                return {downcast.cppobj, tpi};\n            }\n        }\n        if (const auto *tpi = get_type_info(*original.cpptype)) {\n            return {original.cppobj, tpi};\n        }\n        return {nullptr, nullptr};\n    }\n};\n\n// Forward declarations\nvoid keep_alive_impl(handle nurse, handle patient);\ninline PyObject *make_new_instance(PyTypeObject *type);\n\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_GCC(\"-Wredundant-decls\")\n\n// PYBIND11:REMINDER: Needs refactoring of existing pybind11 code.\ninline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo);\n\nPYBIND11_WARNING_POP\n\nPYBIND11_NAMESPACE_BEGIN(smart_holder_type_caster_support)\n\nstruct value_and_holder_helper {\n    value_and_holder loaded_v_h;\n\n    bool have_holder() const {\n        return loaded_v_h.vh != nullptr && loaded_v_h.holder_constructed();\n    }\n\n    smart_holder &holder() const { return loaded_v_h.holder<smart_holder>(); }\n\n    void throw_if_uninitialized_or_disowned_holder(const char *typeid_name) const {\n        static const std::string missing_value_msg = \"Missing value for wrapped C++ type `\";\n        if (!holder().is_populated) {\n            throw value_error(missing_value_msg + clean_type_id(typeid_name)\n                              + \"`: Python instance is uninitialized.\");\n        }\n        if (!holder().has_pointee()) {\n            throw value_error(missing_value_msg + clean_type_id(typeid_name)\n                              + \"`: Python instance was disowned.\");\n        }\n    }\n\n    void throw_if_uninitialized_or_disowned_holder(const std::type_info &type_info) const {\n        throw_if_uninitialized_or_disowned_holder(type_info.name());\n    }\n\n    // have_holder() must be true or this function will fail.\n    void throw_if_instance_is_currently_owned_by_shared_ptr(const type_info *tinfo) const {\n        auto *vptr_gd_ptr = tinfo->get_memory_guarded_delete(holder().vptr);\n        if (vptr_gd_ptr != nullptr && !vptr_gd_ptr->released_ptr.expired()) {\n            throw value_error(\"Python instance is currently owned by a std::shared_ptr.\");\n        }\n    }\n\n    void *get_void_ptr_or_nullptr() const {\n        if (have_holder()) {\n            auto &hld = holder();\n            if (hld.is_populated && hld.has_pointee()) {\n                return hld.template as_raw_ptr_unowned<void>();\n            }\n        }\n        return nullptr;\n    }\n};\n\ntemplate <typename T, typename D>\nhandle smart_holder_from_unique_ptr(std::unique_ptr<T, D> &&src,\n                                    return_value_policy policy,\n                                    handle parent,\n                                    const cast_sources::resolved_source &cs) {\n    if (policy == return_value_policy::copy) {\n        throw cast_error(\"return_value_policy::copy is invalid for unique_ptr.\");\n    }\n    if (!src) {\n        return none().release();\n    }\n    // cs.cppobj is the subobject pointer appropriate for tinfo (may differ from src.get()\n    // under MI/VI). Use this for Python identity/registration, but keep ownership on T*.\n    void *src_raw_void_ptr = const_cast<void *>(cs.cppobj);\n    assert(cs.tinfo != nullptr);\n    const detail::type_info *tinfo = cs.tinfo;\n    if (handle existing_inst = find_registered_python_instance(src_raw_void_ptr, tinfo)) {\n        auto *self_life_support = tinfo->get_trampoline_self_life_support(src.get());\n        if (self_life_support != nullptr) {\n            value_and_holder &v_h = self_life_support->v_h;\n            if (v_h.inst != nullptr && v_h.vh != nullptr) {\n                auto &holder = v_h.holder<smart_holder>();\n                if (!holder.is_disowned) {\n                    pybind11_fail(\"smart_holder_from_unique_ptr: unexpected \"\n                                  \"smart_holder.is_disowned failure.\");\n                }\n                // Critical transfer-of-ownership section. This must stay together.\n                self_life_support->deactivate_life_support();\n                holder.reclaim_disowned(tinfo->get_memory_guarded_delete);\n                (void) src.release();\n                // Critical section end.\n                return existing_inst;\n            }\n        }\n        throw cast_error(\"Invalid unique_ptr: another instance owns this pointer already.\");\n    }\n\n    auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));\n    auto *inst_raw_ptr = reinterpret_cast<instance *>(inst.ptr());\n    inst_raw_ptr->owned = true;\n    void *&valueptr = values_and_holders(inst_raw_ptr).begin()->value_ptr();\n    valueptr = src_raw_void_ptr;\n\n    if (static_cast<void *>(src.get()) == src_raw_void_ptr) {\n        // This is a multiple-inheritance situation that is incompatible with the current\n        // shared_from_this handling (see PR #3023). Is there a better solution?\n        src_raw_void_ptr = nullptr;\n    }\n    auto smhldr = smart_holder::from_unique_ptr(std::move(src), src_raw_void_ptr);\n    tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr));\n\n    if (policy == return_value_policy::reference_internal) {\n        keep_alive_impl(inst, parent);\n    }\n\n    return inst.release();\n}\n\ntemplate <typename T, typename D>\nhandle smart_holder_from_unique_ptr(std::unique_ptr<T const, D> &&src,\n                                    return_value_policy policy,\n                                    handle parent,\n                                    const cast_sources::resolved_source &cs) {\n    return smart_holder_from_unique_ptr(\n        std::unique_ptr<T, D>(const_cast<T *>(src.release()),\n                              std::move(src.get_deleter())), // Const2Mutbl\n        policy,\n        parent,\n        cs);\n}\n\ntemplate <typename T>\nhandle smart_holder_from_shared_ptr(const std::shared_ptr<T> &src,\n                                    return_value_policy policy,\n                                    handle parent,\n                                    const cast_sources::resolved_source &cs) {\n    switch (policy) {\n        case return_value_policy::automatic:\n        case return_value_policy::automatic_reference:\n            break;\n        case return_value_policy::take_ownership:\n            throw cast_error(\"Invalid return_value_policy for shared_ptr (take_ownership).\");\n        case return_value_policy::copy:\n        case return_value_policy::move:\n            break;\n        case return_value_policy::reference:\n            throw cast_error(\"Invalid return_value_policy for shared_ptr (reference).\");\n        case return_value_policy::reference_internal:\n            break;\n    }\n    if (!src) {\n        return none().release();\n    }\n\n    // cs.cppobj is the subobject pointer appropriate for tinfo (may differ from src.get()\n    // under MI/VI). Use this for Python identity/registration, but keep ownership on T*.\n    void *src_raw_void_ptr = const_cast<void *>(cs.cppobj);\n    assert(cs.tinfo != nullptr);\n    const detail::type_info *tinfo = cs.tinfo;\n    if (handle existing_inst = find_registered_python_instance(src_raw_void_ptr, tinfo)) {\n        // PYBIND11:REMINDER: MISSING: Enforcement of consistency with existing smart_holder.\n        // PYBIND11:REMINDER: MISSING: keep_alive.\n        return existing_inst;\n    }\n\n    auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));\n    auto *inst_raw_ptr = reinterpret_cast<instance *>(inst.ptr());\n    inst_raw_ptr->owned = true;\n    void *&valueptr = values_and_holders(inst_raw_ptr).begin()->value_ptr();\n    valueptr = src_raw_void_ptr;\n\n    auto smhldr = smart_holder::from_shared_ptr(std::shared_ptr<void>(src, src_raw_void_ptr));\n    tinfo->init_instance(inst_raw_ptr, static_cast<const void *>(&smhldr));\n\n    if (policy == return_value_policy::reference_internal) {\n        keep_alive_impl(inst, parent);\n    }\n\n    return inst.release();\n}\n\ntemplate <typename T>\nhandle smart_holder_from_shared_ptr(const std::shared_ptr<T const> &src,\n                                    return_value_policy policy,\n                                    handle parent,\n                                    const cast_sources::resolved_source &cs) {\n    return smart_holder_from_shared_ptr(std::const_pointer_cast<T>(src), // Const2Mutbl\n                                        policy,\n                                        parent,\n                                        cs);\n}\n\nstruct shared_ptr_parent_life_support {\n    PyObject *parent;\n    explicit shared_ptr_parent_life_support(PyObject *parent) : parent{parent} {\n        Py_INCREF(parent);\n    }\n    // NOLINTNEXTLINE(readability-make-member-function-const)\n    void operator()(void *) {\n        gil_scoped_acquire gil;\n        Py_DECREF(parent);\n    }\n};\n\nstruct shared_ptr_trampoline_self_life_support {\n    PyObject *self;\n    explicit shared_ptr_trampoline_self_life_support(instance *inst)\n        : self{reinterpret_cast<PyObject *>(inst)} {\n        gil_scoped_acquire gil;\n        Py_INCREF(self);\n    }\n    // NOLINTNEXTLINE(readability-make-member-function-const)\n    void operator()(void *) {\n        gil_scoped_acquire gil;\n        Py_DECREF(self);\n    }\n};\n\ntemplate <typename T,\n          typename D,\n          typename std::enable_if<std::is_default_constructible<D>::value, int>::type = 0>\ninline std::unique_ptr<T, D> unique_with_deleter(T *raw_ptr, std::unique_ptr<D> &&deleter) {\n    if (deleter == nullptr) {\n        return std::unique_ptr<T, D>(raw_ptr);\n    }\n    return std::unique_ptr<T, D>(raw_ptr, std::move(*deleter));\n}\n\ntemplate <typename T,\n          typename D,\n          typename std::enable_if<!std::is_default_constructible<D>::value, int>::type = 0>\ninline std::unique_ptr<T, D> unique_with_deleter(T *raw_ptr, std::unique_ptr<D> &&deleter) {\n    if (deleter == nullptr) {\n        pybind11_fail(\"smart_holder_type_casters: deleter is not default constructible and no\"\n                      \" instance available to return.\");\n    }\n    return std::unique_ptr<T, D>(raw_ptr, std::move(*deleter));\n}\n\ntemplate <typename T>\nstruct load_helper : value_and_holder_helper {\n    bool was_populated = false;\n    bool python_instance_is_alias = false;\n\n    void maybe_set_python_instance_is_alias(handle src) {\n        if (was_populated) {\n            python_instance_is_alias = reinterpret_cast<instance *>(src.ptr())->is_alias;\n        }\n    }\n\n    static std::shared_ptr<T> make_shared_ptr_with_responsible_parent(T *raw_ptr, handle parent) {\n        return std::shared_ptr<T>(raw_ptr, shared_ptr_parent_life_support(parent.ptr()));\n    }\n\n    std::shared_ptr<T> load_as_shared_ptr(const type_info *tinfo,\n                                          void *void_raw_ptr,\n                                          handle responsible_parent = nullptr,\n                                          // to support py::potentially_slicing_weak_ptr\n                                          // with minimal added code complexity:\n                                          bool force_potentially_slicing_shared_ptr\n                                          = false) const {\n        if (!have_holder()) {\n            return nullptr;\n        }\n        throw_if_uninitialized_or_disowned_holder(typeid(T));\n        smart_holder &hld = holder();\n        hld.ensure_is_not_disowned(\"load_as_shared_ptr\");\n        if (hld.vptr_is_using_noop_deleter) {\n            if (responsible_parent) {\n                return make_shared_ptr_with_responsible_parent(static_cast<T *>(void_raw_ptr),\n                                                               responsible_parent);\n            }\n            throw std::runtime_error(\"Non-owning holder (load_as_shared_ptr).\");\n        }\n        auto *type_raw_ptr = static_cast<T *>(void_raw_ptr);\n        if (python_instance_is_alias && !force_potentially_slicing_shared_ptr) {\n            auto *vptr_gd_ptr = tinfo->get_memory_guarded_delete(holder().vptr);\n            if (vptr_gd_ptr != nullptr) {\n                std::shared_ptr<void> released_ptr = vptr_gd_ptr->released_ptr.lock();\n                if (released_ptr) {\n                    return std::shared_ptr<T>(released_ptr, type_raw_ptr);\n                }\n                std::shared_ptr<T> to_be_released(\n                    type_raw_ptr, shared_ptr_trampoline_self_life_support(loaded_v_h.inst));\n                vptr_gd_ptr->released_ptr = to_be_released;\n                return to_be_released;\n            }\n            auto *sptsls_ptr = std::get_deleter<shared_ptr_trampoline_self_life_support>(hld.vptr);\n            if (sptsls_ptr != nullptr) {\n                // This code is reachable only if there are multiple registered_instances for the\n                // same pointee.\n                if (reinterpret_cast<PyObject *>(loaded_v_h.inst) == sptsls_ptr->self) {\n                    pybind11_fail(\"smart_holder_type_caster_support load_as_shared_ptr failure: \"\n                                  \"loaded_v_h.inst == sptsls_ptr->self\");\n                }\n            }\n            if (sptsls_ptr != nullptr || !memory::type_has_shared_from_this(type_raw_ptr)) {\n                return std::shared_ptr<T>(\n                    type_raw_ptr, shared_ptr_trampoline_self_life_support(loaded_v_h.inst));\n            }\n            if (hld.vptr_is_external_shared_ptr) {\n                pybind11_fail(\"smart_holder_type_casters load_as_shared_ptr failure: not \"\n                              \"implemented: trampoline-self-life-support for external shared_ptr \"\n                              \"to type inheriting from std::enable_shared_from_this.\");\n            }\n            pybind11_fail(\n                \"smart_holder_type_casters: load_as_shared_ptr failure: internal inconsistency.\");\n        }\n        std::shared_ptr<void> void_shd_ptr = hld.template as_shared_ptr<void>();\n        return std::shared_ptr<T>(void_shd_ptr, type_raw_ptr);\n    }\n\n    template <typename D>\n    std::unique_ptr<T, D> load_as_unique_ptr(const type_info *tinfo,\n                                             void *raw_void_ptr,\n                                             const char *context = \"load_as_unique_ptr\") {\n        if (!have_holder()) {\n            return unique_with_deleter<T, D>(nullptr, std::unique_ptr<D>());\n        }\n        throw_if_uninitialized_or_disowned_holder(typeid(T));\n        throw_if_instance_is_currently_owned_by_shared_ptr(tinfo);\n        holder().ensure_is_not_disowned(context);\n        holder().template ensure_compatible_uqp_del<T, D>(context);\n        holder().ensure_use_count_1(context);\n\n        T *raw_type_ptr = static_cast<T *>(raw_void_ptr);\n\n        auto *self_life_support = tinfo->get_trampoline_self_life_support(raw_type_ptr);\n        // This is enforced indirectly by a static_assert in the class_ implementation:\n        assert(!python_instance_is_alias || self_life_support);\n\n        std::unique_ptr<D> extracted_deleter\n            = holder().template extract_deleter<T, D>(context, tinfo->get_memory_guarded_delete);\n\n        // Critical transfer-of-ownership section. This must stay together.\n        if (self_life_support != nullptr) {\n            holder().disown(tinfo->get_memory_guarded_delete);\n        } else {\n            holder().release_ownership(tinfo->get_memory_guarded_delete);\n        }\n        auto result = unique_with_deleter<T, D>(raw_type_ptr, std::move(extracted_deleter));\n        if (self_life_support != nullptr) {\n            self_life_support->activate_life_support(loaded_v_h);\n        } else {\n            void *value_void_ptr = loaded_v_h.value_ptr();\n            loaded_v_h.value_ptr() = nullptr;\n            deregister_instance(loaded_v_h.inst, value_void_ptr, loaded_v_h.type);\n        }\n        // Critical section end.\n\n        return result;\n    }\n\n    // This assumes load_as_shared_ptr succeeded(), and the returned shared_ptr is still alive.\n    // The returned unique_ptr is meant to never expire (the behavior is undefined otherwise).\n    template <typename D>\n    std::unique_ptr<T, D> load_as_const_unique_ptr(const type_info *tinfo,\n                                                   T *raw_type_ptr,\n                                                   const char *context\n                                                   = \"load_as_const_unique_ptr\") {\n        if (!have_holder()) {\n            return unique_with_deleter<T, D>(nullptr, std::unique_ptr<D>());\n        }\n        holder().template ensure_compatible_uqp_del<T, D>(context);\n        return unique_with_deleter<T, D>(raw_type_ptr,\n                                         std::move(holder().template extract_deleter<T, D>(\n                                             context, tinfo->get_memory_guarded_delete)));\n    }\n};\n\nPYBIND11_NAMESPACE_END(smart_holder_type_caster_support)\n\nclass type_caster_generic {\npublic:\n    PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)\n        : typeinfo(get_type_info(type_info)), cpptype(&type_info) {}\n\n    explicit type_caster_generic(const type_info *typeinfo)\n        : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}\n\n    bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }\n\n    static handle cast(const void *src,\n                       return_value_policy policy,\n                       handle parent,\n                       const detail::type_info *tinfo,\n                       void *(*copy_constructor)(const void *),\n                       void *(*move_constructor)(const void *),\n                       const void *existing_holder = nullptr) {\n        cast_sources srcs{src, tinfo};\n        return cast(srcs, policy, parent, copy_constructor, move_constructor, existing_holder);\n    }\n\n    PYBIND11_NOINLINE static handle cast(const cast_sources &srcs,\n                                         return_value_policy policy,\n                                         handle parent,\n                                         void *(*copy_constructor)(const void *),\n                                         void *(*move_constructor)(const void *),\n                                         const void *existing_holder = nullptr) {\n        if (!srcs.result.tinfo) {\n            // No pybind11 type info. Raise an exception.\n            std::string tname = srcs.downcast.cpptype   ? srcs.downcast.cpptype->name()\n                                : srcs.original.cpptype ? srcs.original.cpptype->name()\n                                                        : \"<unspecified>\";\n            detail::clean_type_id(tname);\n            std::string msg = \"Unregistered type : \" + tname;\n            set_error(PyExc_TypeError, msg.c_str());\n            return handle();\n        }\n\n        void *src = const_cast<void *>(srcs.result.cppobj);\n        if (src == nullptr) {\n            return none().release();\n        }\n        const type_info *tinfo = srcs.result.tinfo;\n\n        if (handle registered_inst = find_registered_python_instance(src, tinfo)) {\n            return registered_inst;\n        }\n\n        auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));\n        auto *wrapper = reinterpret_cast<instance *>(inst.ptr());\n        wrapper->owned = false;\n        void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();\n\n        switch (policy) {\n            case return_value_policy::automatic:\n            case return_value_policy::take_ownership:\n                valueptr = src;\n                wrapper->owned = true;\n                break;\n\n            case return_value_policy::automatic_reference:\n            case return_value_policy::reference:\n                valueptr = src;\n                wrapper->owned = false;\n                break;\n\n            case return_value_policy::copy:\n                if (copy_constructor) {\n                    valueptr = copy_constructor(src);\n                } else {\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                    std::string type_name(tinfo->cpptype->name());\n                    detail::clean_type_id(type_name);\n                    throw cast_error(\"return_value_policy = copy, but type \" + type_name\n                                     + \" is non-copyable!\");\n#else\n                    throw cast_error(\"return_value_policy = copy, but type is \"\n                                     \"non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or \"\n                                     \"compile in debug mode for details)\");\n#endif\n                }\n                wrapper->owned = true;\n                break;\n\n            case return_value_policy::move:\n                if (move_constructor) {\n                    valueptr = move_constructor(src);\n                } else if (copy_constructor) {\n                    valueptr = copy_constructor(src);\n                } else {\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                    std::string type_name(tinfo->cpptype->name());\n                    detail::clean_type_id(type_name);\n                    throw cast_error(\"return_value_policy = move, but type \" + type_name\n                                     + \" is neither movable nor copyable!\");\n#else\n                    throw cast_error(\"return_value_policy = move, but type is neither \"\n                                     \"movable nor copyable! \"\n                                     \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in \"\n                                     \"debug mode for details)\");\n#endif\n                }\n                wrapper->owned = true;\n                break;\n\n            case return_value_policy::reference_internal:\n                valueptr = src;\n                wrapper->owned = false;\n                keep_alive_impl(inst, parent);\n                break;\n\n            default:\n                throw cast_error(\"unhandled return_value_policy: should not happen!\");\n        }\n\n        tinfo->init_instance(wrapper, existing_holder);\n\n        return inst.release();\n    }\n\n    // Base methods for generic caster; there are overridden in copyable_holder_caster\n    void load_value(value_and_holder &&v_h) {\n        if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {\n            smart_holder_type_caster_support::value_and_holder_helper v_h_helper;\n            v_h_helper.loaded_v_h = v_h;\n            if (v_h_helper.have_holder()) {\n                v_h_helper.throw_if_uninitialized_or_disowned_holder(cpptype->name());\n                value = v_h_helper.holder().template as_raw_ptr_unowned<void>();\n                return;\n            }\n        }\n        auto *&vptr = v_h.value_ptr();\n        // Lazy allocation for unallocated values:\n        if (vptr == nullptr) {\n            const auto *type = v_h.type ? v_h.type : typeinfo;\n            if (type->operator_new) {\n                vptr = type->operator_new(type->type_size);\n            } else {\n#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)\n                if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {\n                    vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));\n                } else {\n                    vptr = ::operator new(type->type_size);\n                }\n#else\n                vptr = ::operator new(type->type_size);\n#endif\n            }\n        }\n        value = vptr;\n    }\n    bool try_implicit_casts(handle src, bool convert) {\n        for (const auto &cast : typeinfo->implicit_casts) {\n            type_caster_generic sub_caster(*cast.first);\n            if (sub_caster.load(src, convert)) {\n                value = cast.second(sub_caster.value);\n                return true;\n            }\n        }\n        return false;\n    }\n    bool try_direct_conversions(handle src) {\n        for (auto &converter : *typeinfo->direct_conversions) {\n            if (converter(src.ptr(), value)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    bool try_cpp_conduit(handle src) {\n        value = try_raw_pointer_ephemeral_from_cpp_conduit(src, cpptype);\n        if (value != nullptr) {\n            return true;\n        }\n        return false;\n    }\n    void check_holder_compat() {}\n    bool set_foreign_holder(handle) { return true; }\n\n    PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {\n        auto caster = type_caster_generic(ti);\n        if (caster.load(src, false)) {\n            return caster.value;\n        }\n        return nullptr;\n    }\n\n    /// Try to load with foreign typeinfo, if available. Used when there is no\n    /// native typeinfo, or when the native one wasn't able to produce a value.\n    PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {\n        constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;\n        const auto pytype = type::handle_of(src);\n        if (!hasattr(pytype, local_key)) {\n            return false;\n        }\n\n        type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));\n        // Only consider this foreign loader if actually foreign and is a loader of the correct cpp\n        // type\n        if (foreign_typeinfo->module_local_load == &local_load\n            || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {\n            return false;\n        }\n\n        if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {\n            value = result;\n            return true;\n        }\n        return false;\n    }\n\n    // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant\n    // bits of code between here and copyable_holder_caster where the two classes need different\n    // logic (without having to resort to virtual inheritance).\n    template <typename ThisT>\n    PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {\n        auto &this_ = static_cast<ThisT &>(*this);\n        if (!src) {\n            return false;\n        }\n        if (!typeinfo) {\n            return try_load_foreign_module_local(src) && this_.set_foreign_holder(src);\n        }\n\n        this_.check_holder_compat();\n\n        PyTypeObject *srctype = Py_TYPE(src.ptr());\n\n        // Case 1: If src is an exact type match for the target type then we can reinterpret_cast\n        // the instance's value pointer to the target type:\n        if (srctype == typeinfo->type) {\n            this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());\n            return true;\n        }\n        // Case 2: We have a derived class\n        if (PyType_IsSubtype(srctype, typeinfo->type)) {\n            const auto &bases = all_type_info(srctype);\n            bool no_cpp_mi = typeinfo->simple_type;\n\n            // Case 2a: the python type is a Python-inherited derived class that inherits from just\n            // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of\n            // the right type and we can use reinterpret_cast.\n            // (This is essentially the same as case 2b, but because not using multiple inheritance\n            // is extremely common, we handle it specially to avoid the loop iterator and type\n            // pointer lookup overhead)\n            if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {\n                this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());\n                return true;\n            }\n            // Case 2b: the python type inherits from multiple C++ bases.  Check the bases to see\n            // if we can find an exact match (or, for a simple C++ type, an inherited match); if\n            // so, we can safely reinterpret_cast to the relevant pointer.\n            if (bases.size() > 1) {\n                for (auto *base : bases) {\n                    if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)\n                                  : base->type == typeinfo->type) {\n                        this_.load_value(\n                            reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));\n                        return true;\n                    }\n                }\n            }\n\n            // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type\n            // match in the registered bases, above, so try implicit casting (needed for proper C++\n            // casting when MI is involved).\n            if (this_.try_implicit_casts(src, convert)) {\n                return true;\n            }\n        }\n\n        // Perform an implicit conversion\n        if (convert) {\n            for (const auto &converter : typeinfo->implicit_conversions) {\n                auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));\n                if (load_impl<ThisT>(temp, false)) {\n                    loader_life_support::add_patient(temp);\n                    return true;\n                }\n            }\n            if (this_.try_direct_conversions(src)) {\n                return true;\n            }\n        }\n\n        // Failed to match local typeinfo. Try again with global.\n        if (typeinfo->module_local) {\n            if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {\n                typeinfo = gtype;\n                return load_impl<ThisT>(src, false);\n            }\n        }\n\n        // Global typeinfo has precedence over foreign module_local\n        if (try_load_foreign_module_local(src)) {\n            return this_.set_foreign_holder(src);\n        }\n\n        // Custom converters didn't take None, now we convert None to nullptr.\n        if (src.is_none()) {\n            // Defer accepting None to other overloads (if we aren't in convert mode):\n            if (!convert) {\n                return false;\n            }\n            value = nullptr;\n            return true;\n        }\n\n        if (convert && cpptype && this_.try_cpp_conduit(src)) {\n            return this_.set_foreign_holder(src);\n        }\n\n        return false;\n    }\n\n    const type_info *typeinfo = nullptr;\n    const std::type_info *cpptype = nullptr;\n    void *value = nullptr;\n};\n\ninline object cpp_conduit_method(handle self,\n                                 const bytes &pybind11_platform_abi_id,\n                                 const capsule &cpp_type_info_capsule,\n                                 const bytes &pointer_kind) {\n#ifdef PYBIND11_HAS_STRING_VIEW\n    using cpp_str = std::string_view;\n#else\n    using cpp_str = std::string;\n#endif\n    if (cpp_str(pybind11_platform_abi_id) != PYBIND11_PLATFORM_ABI_ID) {\n        return none();\n    }\n    if (std::strcmp(cpp_type_info_capsule.name(), typeid(std::type_info).name()) != 0) {\n        return none();\n    }\n    if (cpp_str(pointer_kind) != \"raw_pointer_ephemeral\") {\n        throw std::runtime_error(\"Invalid pointer_kind: \\\"\" + std::string(pointer_kind) + \"\\\"\");\n    }\n    const auto *cpp_type_info = cpp_type_info_capsule.get_pointer<const std::type_info>();\n    type_caster_generic caster(*cpp_type_info);\n    if (!caster.load(self, false)) {\n        return none();\n    }\n    return capsule(caster.value, cpp_type_info->name());\n}\n\n/**\n * Determine suitable casting operator for pointer-or-lvalue-casting type casters.  The type caster\n * needs to provide `operator T*()` and `operator T&()` operators.\n *\n * If the type supports moving the value away via an `operator T&&() &&` method, it should use\n * `movable_cast_op_type` instead.\n */\ntemplate <typename T>\nusing cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,\n                                   typename std::add_pointer<intrinsic_t<T>>::type,\n                                   typename std::add_lvalue_reference<intrinsic_t<T>>::type>;\n\n/**\n * Determine suitable casting operator for a type caster with a movable value.  Such a type caster\n * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`.  The latter will be\n * called in appropriate contexts where the value can be moved rather than copied.\n *\n * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.\n */\ntemplate <typename T>\nusing movable_cast_op_type\n    = conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,\n                    typename std::add_pointer<intrinsic_t<T>>::type,\n                    conditional_t<std::is_rvalue_reference<T>::value,\n                                  typename std::add_rvalue_reference<intrinsic_t<T>>::type,\n                                  typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;\n\n// Does the container have a mapped type and is it recursive?\n// Implemented by specializations below.\ntemplate <typename Container, typename SFINAE = void>\nstruct container_mapped_type_traits {\n    static constexpr bool has_mapped_type = false;\n    static constexpr bool has_recursive_mapped_type = false;\n};\n\ntemplate <typename Container>\nstruct container_mapped_type_traits<\n    Container,\n    typename std::enable_if<\n        std::is_same<typename Container::mapped_type, Container>::value>::type> {\n    static constexpr bool has_mapped_type = true;\n    static constexpr bool has_recursive_mapped_type = true;\n};\n\ntemplate <typename Container>\nstruct container_mapped_type_traits<\n    Container,\n    typename std::enable_if<\n        negation<std::is_same<typename Container::mapped_type, Container>>::value>::type> {\n    static constexpr bool has_mapped_type = true;\n    static constexpr bool has_recursive_mapped_type = false;\n};\n\n// Does the container have a value type and is it recursive?\n// Implemented by specializations below.\ntemplate <typename Container, typename SFINAE = void>\nstruct container_value_type_traits : std::false_type {\n    static constexpr bool has_value_type = false;\n    static constexpr bool has_recursive_value_type = false;\n};\n\ntemplate <typename Container>\nstruct container_value_type_traits<\n    Container,\n    typename std::enable_if<\n        std::is_same<typename Container::value_type, Container>::value>::type> {\n    static constexpr bool has_value_type = true;\n    static constexpr bool has_recursive_value_type = true;\n};\n\ntemplate <typename Container>\nstruct container_value_type_traits<\n    Container,\n    typename std::enable_if<\n        negation<std::is_same<typename Container::value_type, Container>>::value>::type> {\n    static constexpr bool has_value_type = true;\n    static constexpr bool has_recursive_value_type = false;\n};\n\n/*\n * Tag to be used for representing the bottom of recursively defined types.\n * Define this tag so we don't have to use void.\n */\nstruct recursive_bottom {};\n\n/*\n * Implementation detail of `recursive_container_traits` below.\n * `T` is the `value_type` of the container, which might need to be modified to\n * avoid recursive types and const types.\n */\ntemplate <typename T, bool is_this_a_map>\nstruct impl_type_to_check_recursively {\n    /*\n     * If the container is recursive, then no further recursion should be done.\n     */\n    using if_recursive = recursive_bottom;\n    /*\n     * Otherwise yield `T` unchanged.\n     */\n    using if_not_recursive = T;\n};\n\n/*\n * For pairs - only as value type of a map -, the first type should remove the `const`.\n * Also, if the map is recursive, then the recursive checking should consider\n * the first type only.\n */\ntemplate <typename A, typename B>\nstruct impl_type_to_check_recursively<std::pair<A, B>, /* is_this_a_map = */ true> {\n    using if_recursive = typename std::remove_const<A>::type;\n    using if_not_recursive = std::pair<typename std::remove_const<A>::type, B>;\n};\n\n/*\n * Implementation of `recursive_container_traits` below.\n */\ntemplate <typename Container, typename SFINAE = void>\nstruct impl_recursive_container_traits {\n    using type_to_check_recursively = recursive_bottom;\n};\n\ntemplate <typename Container>\nstruct impl_recursive_container_traits<\n    Container,\n    typename std::enable_if<container_value_type_traits<Container>::has_value_type>::type> {\n    static constexpr bool is_recursive\n        = container_mapped_type_traits<Container>::has_recursive_mapped_type\n          || container_value_type_traits<Container>::has_recursive_value_type;\n    /*\n     * This member dictates which type Pybind11 should check recursively in traits\n     * such as `is_move_constructible`, `is_copy_constructible`, `is_move_assignable`, ...\n     * Direct access to `value_type` should be avoided:\n     * 1. `value_type` might recursively contain the type again\n     * 2. `value_type` of STL map types is `std::pair<A const, B>`, the `const`\n     *    should be removed.\n     *\n     */\n    using type_to_check_recursively = typename std::conditional<\n        is_recursive,\n        typename impl_type_to_check_recursively<\n            typename Container::value_type,\n            container_mapped_type_traits<Container>::has_mapped_type>::if_recursive,\n        typename impl_type_to_check_recursively<\n            typename Container::value_type,\n            container_mapped_type_traits<Container>::has_mapped_type>::if_not_recursive>::type;\n};\n\n/*\n * This trait defines the `type_to_check_recursively` which is needed to properly\n * handle recursively defined traits such as `is_move_constructible` without going\n * into an infinite recursion.\n * Should be used instead of directly accessing the `value_type`.\n * It cancels the recursion by returning the `recursive_bottom` tag.\n *\n * The default definition of `type_to_check_recursively` is as follows:\n *\n * 1. By default, it is `recursive_bottom`, so that the recursion is canceled.\n * 2. If the type is non-recursive and defines a `value_type`, then the `value_type` is used.\n *    If the `value_type` is a pair and a `mapped_type` is defined,\n *    then the `const` is removed from the first type.\n * 3. If the type is recursive and `value_type` is not a pair, then `recursive_bottom` is returned.\n * 4. If the type is recursive and `value_type` is a pair and a `mapped_type` is defined,\n *    then `const` is removed from the first type and the first type is returned.\n *\n * This behavior can be extended by the user as seen in test_stl_binders.cpp.\n *\n * This struct is exactly the same as impl_recursive_container_traits.\n * The duplication achieves that user-defined specializations don't compete\n * with internal specializations, but take precedence.\n */\ntemplate <typename Container, typename SFINAE = void>\nstruct recursive_container_traits : impl_recursive_container_traits<Container> {};\n\ntemplate <typename T>\nstruct is_move_constructible\n    : all_of<std::is_move_constructible<T>,\n             is_move_constructible<\n                 typename recursive_container_traits<T>::type_to_check_recursively>> {};\n\ntemplate <>\nstruct is_move_constructible<recursive_bottom> : std::true_type {};\n\n// Likewise for std::pair\n// (after C++17 it is mandatory that the move constructor not exist when the two types aren't\n// themselves move constructible, but this can not be relied upon when T1 or T2 are themselves\n// containers).\ntemplate <typename T1, typename T2>\nstruct is_move_constructible<std::pair<T1, T2>>\n    : all_of<is_move_constructible<T1>, is_move_constructible<T2>> {};\n\n// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when\n// T is non-copyable, but code containing such a copy constructor fails to actually compile.\ntemplate <typename T>\nstruct is_copy_constructible\n    : all_of<std::is_copy_constructible<T>,\n             is_copy_constructible<\n                 typename recursive_container_traits<T>::type_to_check_recursively>> {};\n\ntemplate <>\nstruct is_copy_constructible<recursive_bottom> : std::true_type {};\n\n// Likewise for std::pair\n// (after C++17 it is mandatory that the copy constructor not exist when the two types aren't\n// themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves\n// containers).\ntemplate <typename T1, typename T2>\nstruct is_copy_constructible<std::pair<T1, T2>>\n    : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};\n\n// The same problems arise with std::is_copy_assignable, so we use the same workaround.\ntemplate <typename T>\nstruct is_copy_assignable\n    : all_of<\n          std::is_copy_assignable<T>,\n          is_copy_assignable<typename recursive_container_traits<T>::type_to_check_recursively>> {\n};\n\ntemplate <>\nstruct is_copy_assignable<recursive_bottom> : std::true_type {};\n\ntemplate <typename T1, typename T2>\nstruct is_copy_assignable<std::pair<T1, T2>>\n    : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};\n\nPYBIND11_NAMESPACE_END(detail)\n\n// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed\n// to by `src` actually is an instance of some class derived from `itype`.\n// If so, it sets `tinfo` to point to the std::type_info representing that derived\n// type, and returns a pointer to the start of the most-derived object of that type\n// (in which `src` is a subobject; this will be the same address as `src` in most\n// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`\n// and leaves `tinfo` at its default value of nullptr.\n//\n// The default polymorphic_type_hook just returns src. A specialization for polymorphic\n// types determines the runtime type of the passed object and adjusts the this-pointer\n// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear\n// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is\n// registered with pybind11, and this Animal is in fact a Dog).\n//\n// You may specialize polymorphic_type_hook yourself for types that want to appear\n// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern\n// in performance-sensitive applications, used most notably in LLVM.)\n//\n// polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with\n// std::enable_if. User provided specializations will always have higher priority than\n// the default implementation and specialization provided in polymorphic_type_hook_base.\ntemplate <typename itype, typename SFINAE = void>\nstruct polymorphic_type_hook_base {\n    static const void *get(const itype *src, const std::type_info *&) { return src; }\n};\ntemplate <typename itype>\nstruct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {\n    static const void *get(const itype *src, const std::type_info *&type) {\n        type = src ? &typeid(*src) : nullptr;\n        return dynamic_cast<const void *>(src);\n    }\n};\ntemplate <typename itype, typename SFINAE = void>\nstruct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename itype>\ncast_sources::cast_sources(const itype *ptr) : original{ptr, &typeid(itype)} {\n    // If this is a base pointer to a derived type, and the derived type is\n    // registered with pybind11, we want to make the full derived object\n    // available. In the typical case where itype is polymorphic, we get the\n    // correct derived pointer (which may be != base pointer) by a dynamic_cast\n    // to most derived type. If itype is not polymorphic, a user-provided\n    // specialization of polymorphic_type_hook can do the same thing.\n    // If there is no downcast to perform, then the default hook will leave\n    // derived.type set to nullptr, which causes us to ignore derived.obj.\n    downcast.cppobj = polymorphic_type_hook<itype>::get(ptr, downcast.cpptype);\n    result = resolve();\n}\n\n/// Generic type caster for objects stored on the heap\ntemplate <typename type>\nclass type_caster_base : public type_caster_generic {\n    using itype = intrinsic_t<type>;\n\npublic:\n    static constexpr auto name = const_name<type>();\n\n    type_caster_base() : type_caster_base(typeid(type)) {}\n    explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}\n\n    // Wrap the generic cast_sources to be only constructible from the type\n    // that's correct in this context, so you can't use type_caster_base<A>\n    // to convert an unrelated B* to Python.\n    struct cast_sources : detail::cast_sources {\n        explicit cast_sources(const itype *ptr) : detail::cast_sources(ptr) {}\n    };\n\n    static handle cast(const itype &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast(std::addressof(src), policy, parent);\n    }\n\n    static handle cast(itype &&src, return_value_policy, handle parent) {\n        return cast(std::addressof(src), return_value_policy::move, parent);\n    }\n\n    static handle cast(const itype *src, return_value_policy policy, handle parent) {\n        return cast(cast_sources{src}, policy, parent);\n    }\n\n    static handle cast(const cast_sources &srcs, return_value_policy policy, handle parent) {\n        return type_caster_generic::cast(srcs,\n                                         policy,\n                                         parent,\n                                         make_copy_constructor((const itype *) nullptr),\n                                         make_move_constructor((const itype *) nullptr));\n    }\n\n    static handle cast_holder(const itype *src, const void *holder) {\n        return cast_holder(cast_sources{src}, holder);\n    }\n\n    static handle cast_holder(const cast_sources &srcs, const void *holder) {\n        auto policy = return_value_policy::take_ownership;\n        return type_caster_generic::cast(srcs, policy, {}, nullptr, nullptr, holder);\n    }\n\n    template <typename T>\n    using cast_op_type = detail::cast_op_type<T>;\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator itype *() { return (type *) value; }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator itype &() {\n        if (!value) {\n            throw reference_cast_error();\n        }\n        return *((itype *) value);\n    }\n\nprotected:\n    using Constructor = void *(*) (const void *);\n\n    /* Only enabled when the types are {copy,move}-constructible *and* when the type\n       does not have a private operator new implementation. A comma operator is used in the\n       decltype argument to apply SFINAE to the public copy/move constructors.*/\n    template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>\n    static auto make_copy_constructor(const T *)\n        -> decltype(new T(std::declval<const T>()), Constructor{}) {\n        return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };\n    }\n\n    template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>\n    static auto make_move_constructor(const T *)\n        -> decltype(new T(std::declval<T &&>()), Constructor{}) {\n        return [](const void *arg) -> void * {\n            return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));\n        };\n    }\n\n    static Constructor make_copy_constructor(...) { return nullptr; }\n    static Constructor make_move_constructor(...) { return nullptr; }\n};\n\ninline std::string quote_cpp_type_name(const std::string &cpp_type_name) {\n    return cpp_type_name; // No-op for now. See PR #4888\n}\n\nPYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {\n    if (auto *type_data = get_type_info(ti)) {\n        handle th(reinterpret_cast<PyObject *>(type_data->type));\n        return th.attr(\"__module__\").cast<std::string>() + '.'\n               + th.attr(\"__qualname__\").cast<std::string>();\n    }\n    return quote_cpp_type_name(clean_type_id(ti.name()));\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/typeid.h",
    "content": "/*\n    pybind11/detail/typeid.h: Compiler-independent access to type identifiers\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <cstdio>\n#include <cstdlib>\n\n#if defined(__GNUG__)\n#    include <cxxabi.h>\n#endif\n\n#include \"common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/// Erase all occurrences of a substring\ninline void erase_all(std::string &string, const std::string &search) {\n    for (size_t pos = 0;;) {\n        pos = string.find(search, pos);\n        if (pos == std::string::npos) {\n            break;\n        }\n        string.erase(pos, search.length());\n    }\n}\n\nPYBIND11_NOINLINE void clean_type_id(std::string &name) {\n#if defined(__GNUG__)\n    int status = 0;\n    std::unique_ptr<char, void (*)(void *)> res{\n        abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};\n    if (status == 0) {\n        name = res.get();\n    }\n#else\n    detail::erase_all(name, \"class \");\n    detail::erase_all(name, \"struct \");\n    detail::erase_all(name, \"enum \");\n#endif\n    detail::erase_all(name, \"pybind11::\");\n}\n\ninline std::string clean_type_id(const char *typeid_name) {\n    std::string name(typeid_name);\n    detail::clean_type_id(name);\n    return name;\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Return a string representation of a C++ type\ntemplate <typename T>\nstatic std::string type_id() {\n    return detail::clean_type_id(typeid(T).name());\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/using_smart_holder.h",
    "content": "// Copyright (c) 2024 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"common.h\"\n#include \"struct_smart_holder.h\"\n\n#include <type_traits>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nusing pybind11::memory::smart_holder;\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename H>\nusing is_smart_holder = std::is_same<H, smart_holder>;\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/detail/value_and_holder.h",
    "content": "// Copyright (c) 2016-2024 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"common.h\"\n\n#include <cstddef>\n#include <cstdint>\n#include <typeinfo>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nstruct value_and_holder {\n    instance *inst = nullptr;\n    size_t index = 0u;\n    const detail::type_info *type = nullptr;\n    void **vh = nullptr;\n\n    // Main constructor for a found value/holder:\n    value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)\n        : inst{i}, index{index}, type{type},\n          vh{inst->simple_layout ? inst->simple_value_holder\n                                 : &inst->nonsimple.values_and_holders[vpos]} {}\n\n    // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())\n    value_and_holder() = default;\n\n    // Used for past-the-end iterator\n    explicit value_and_holder(size_t index) : index{index} {}\n\n    template <typename V = void>\n    V *&value_ptr() const {\n        return reinterpret_cast<V *&>(vh[0]);\n    }\n    // True if this `value_and_holder` has a non-null value pointer\n    explicit operator bool() const { return value_ptr() != nullptr; }\n\n    template <typename H>\n    H &holder() const {\n        return reinterpret_cast<H &>(vh[1]);\n    }\n    bool holder_constructed() const {\n        return inst->simple_layout\n                   ? inst->simple_holder_constructed\n                   : (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;\n    }\n    // NOLINTNEXTLINE(readability-make-member-function-const)\n    void set_holder_constructed(bool v = true) {\n        if (inst->simple_layout) {\n            inst->simple_holder_constructed = v;\n        } else if (v) {\n            inst->nonsimple.status[index] |= instance::status_holder_constructed;\n        } else {\n            inst->nonsimple.status[index]\n                &= static_cast<std::uint8_t>(~instance::status_holder_constructed);\n        }\n    }\n    bool instance_registered() const {\n        return inst->simple_layout\n                   ? inst->simple_instance_registered\n                   : ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);\n    }\n    // NOLINTNEXTLINE(readability-make-member-function-const)\n    void set_instance_registered(bool v = true) {\n        if (inst->simple_layout) {\n            inst->simple_instance_registered = v;\n        } else if (v) {\n            inst->nonsimple.status[index] |= instance::status_instance_registered;\n        } else {\n            inst->nonsimple.status[index]\n                &= static_cast<std::uint8_t>(~instance::status_instance_registered);\n        }\n    }\n};\n\n// This is a semi-public API to check if the corresponding instance has been constructed with a\n// holder. That is, if the instance has been constructed with a holder, the `__init__` method is\n// called and the C++ object is valid. Otherwise, the C++ object might only be allocated, but not\n// initialized. This will lead to **SEGMENTATION FAULTS** if the C++ object is used in any way.\n// Example usage: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#custom-type-setup\n//                for `tp_traverse` and `tp_clear` implementations.\n// WARNING: The caller is responsible for ensuring that the `reinterpret_cast` is valid.\ninline bool is_holder_constructed(PyObject *obj) {\n    auto *const instance = reinterpret_cast<pybind11::detail::instance *>(obj);\n    return instance->get_value_and_holder().holder_constructed();\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/eigen/common.h",
    "content": "// Copyright (c) 2023 The pybind Community.\n\n#pragma once\n\n// Common message for `static_assert()`s, which are useful to easily\n// preempt much less obvious errors.\n#define PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED                                    \\\n    \"Pointer types (in particular `PyObject *`) are not supported as scalar types for Eigen \"     \\\n    \"types.\"\n"
  },
  {
    "path": "include/pybind11/eigen/matrix.h",
    "content": "/*\n    pybind11/eigen/matrix.h: Transparent conversion for dense and sparse Eigen matrices\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/numpy.h>\n\n#include \"common.h\"\n\n/* HINT: To suppress warnings originating from the Eigen headers, use -isystem.\n   See also:\n       https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir\n       https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler\n*/\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741\n//       C5054: operator '&': deprecated between enumerations of different types\n#if defined(__MINGW32__)\nPYBIND11_WARNING_DISABLE_GCC(\"-Wmaybe-uninitialized\")\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nPYBIND11_WARNING_POP\n\n// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit\n// move constructors that break things.  We could detect this an explicitly copy, but an extra copy\n// of matrices seems highly undesirable.\nstatic_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),\n              \"Eigen matrix support in pybind11 requires Eigen >= 3.2.7\");\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\n// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:\nusing EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;\ntemplate <typename MatrixType>\nusing EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;\ntemplate <typename MatrixType>\nusing EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n#if EIGEN_VERSION_AT_LEAST(3, 3, 0)\nusing EigenIndex = Eigen::Index;\ntemplate <typename Scalar, int Flags, typename StorageIndex>\nusing EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;\n#else\nusing EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;\ntemplate <typename Scalar, int Flags, typename StorageIndex>\nusing EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;\n#endif\n\n// Matches Eigen::Map, Eigen::Ref, blocks, etc:\ntemplate <typename T>\nusing is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,\n                                  std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;\ntemplate <typename T>\nusing is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;\ntemplate <typename T>\nusing is_eigen_dense_plain\n    = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;\ntemplate <typename T>\nusing is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;\n// Test for objects inheriting from EigenBase<Derived> that aren't captured by the above.  This\n// basically covers anything that can be assigned to a dense matrix but that don't have a typical\n// matrix data layout that can be copied from their .data().  For example, DiagonalMatrix and\n// SelfAdjointView fall into this category.\ntemplate <typename T>\nusing is_eigen_other\n    = all_of<is_template_base_of<Eigen::EigenBase, T>,\n             negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;\n\n// Captures numpy/eigen conformability status (returned by EigenProps::conformable()):\ntemplate <bool EigenRowMajor>\nstruct EigenConformable {\n    bool conformable = false;\n    EigenIndex rows = 0, cols = 0;\n    EigenDStride stride{0, 0};    // Only valid if negativestrides is false!\n    bool negativestrides = false; // If true, do not use stride!\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    EigenConformable(bool fits = false) : conformable{fits} {}\n    // Matrix type:\n    EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)\n        : conformable{true}, rows{r}, cols{c},\n          // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.\n          // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747\n          stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)\n                               : (cstride > 0 ? cstride : 0) /* outer stride */,\n                 EigenRowMajor ? (cstride > 0 ? cstride : 0)\n                               : (rstride > 0 ? rstride : 0) /* inner stride */},\n          negativestrides{rstride < 0 || cstride < 0} {}\n    // Vector type:\n    EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)\n        : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}\n\n    template <typename props>\n    bool stride_compatible() const {\n        // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,\n        // matching strides, or a dimension size of 1 (in which case the stride value is\n        // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant\n        // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).\n        if (negativestrides) {\n            return false;\n        }\n        if (rows == 0 || cols == 0) {\n            return true;\n        }\n        return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()\n                || (EigenRowMajor ? cols : rows) == 1)\n               && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()\n                   || (EigenRowMajor ? rows : cols) == 1);\n    }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator bool() const { return conformable; }\n};\n\ntemplate <typename Type>\nstruct eigen_extract_stride {\n    using type = Type;\n};\ntemplate <typename PlainObjectType, int MapOptions, typename StrideType>\nstruct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {\n    using type = StrideType;\n};\ntemplate <typename PlainObjectType, int Options, typename StrideType>\nstruct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {\n    using type = StrideType;\n};\n\n// Helper struct for extracting information from an Eigen type\ntemplate <typename Type_>\nstruct EigenProps {\n    using Type = Type_;\n    using Scalar = typename Type::Scalar;\n    using StrideType = typename eigen_extract_stride<Type>::type;\n    static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,\n                                size = Type::SizeAtCompileTime;\n    static constexpr bool row_major = Type::IsRowMajor,\n                          vector\n                          = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1\n        fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,\n                          fixed = size != Eigen::Dynamic, // Fully-fixed size\n        dynamic = !fixed_rows && !fixed_cols;             // Fully-dynamic size\n\n    template <EigenIndex i, EigenIndex ifzero>\n    using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;\n    static constexpr EigenIndex inner_stride\n        = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,\n        outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,\n        vector      ? size\n        : row_major ? cols\n                    : rows > ::value;\n    static constexpr bool dynamic_stride\n        = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;\n    static constexpr bool requires_row_major\n        = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;\n    static constexpr bool requires_col_major\n        = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;\n\n    // Takes an input array and determines whether we can make it fit into the Eigen type.  If\n    // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector\n    // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).\n    static EigenConformable<row_major> conformable(const array &a) {\n        const auto dims = a.ndim();\n        if (dims < 1 || dims > 2) {\n            return false;\n        }\n\n        if (dims == 2) { // Matrix type: require exact match (or dynamic)\n\n            EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),\n                       np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),\n                       np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));\n            if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {\n                return false;\n            }\n\n            return {np_rows, np_cols, np_rstride, np_cstride};\n        }\n\n        // Otherwise we're storing an n-vector.  Only one of the strides will be used, but\n        // whichever is used, we want the (single) numpy stride value.\n        const EigenIndex n = a.shape(0),\n                         stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));\n\n        if (vector) { // Eigen type is a compile-time vector\n            if (fixed && size != n) {\n                return false; // Vector size mismatch\n            }\n            return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};\n        }\n        if (fixed) {\n            // The type has a fixed size, but is not a vector: abort\n            return false;\n        }\n        if (fixed_cols) {\n            // Since this isn't a vector, cols must be != 1.  We allow this only if it exactly\n            // equals the number of elements (rows is Dynamic, and so 1 row is allowed).\n            if (cols != n) {\n                return false;\n            }\n            return {1, n, stride};\n        } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector\n        if (fixed_rows && rows != n) {\n            return false;\n        }\n        return {n, 1, stride};\n    }\n\n    static constexpr bool show_writeable\n        = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;\n    static constexpr bool show_order = is_eigen_dense_map<Type>::value;\n    static constexpr bool show_c_contiguous = show_order && requires_row_major;\n    static constexpr bool show_f_contiguous\n        = !show_c_contiguous && show_order && requires_col_major;\n\n    static constexpr auto descriptor\n        = const_name(\"typing.Annotated[\")\n          + io_name(\"numpy.typing.ArrayLike, \", \"numpy.typing.NDArray[\")\n          + npy_format_descriptor<Scalar>::name + io_name(\"\", \"]\") + const_name(\", \\\"[\")\n          + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name(\"m\")) + const_name(\", \")\n          + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name(\"n\"))\n          + const_name(\"]\\\"\")\n          // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to\n          // be satisfied: writeable=True (for a mutable reference), and, depending on the map's\n          // stride options, possibly f_contiguous or c_contiguous.  We include them in the\n          // descriptor output to provide some hint as to why a TypeError is occurring (otherwise\n          // it can be confusing to see that a function accepts a\n          // 'typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[3,2]\"]' and an error message\n          // that you *gave* a numpy.ndarray of the right type and dimensions.\n          + const_name<show_writeable>(\", \\\"flags.writeable\\\"\", \"\")\n          + const_name<show_c_contiguous>(\", \\\"flags.c_contiguous\\\"\", \"\")\n          + const_name<show_f_contiguous>(\", \\\"flags.f_contiguous\\\"\", \"\") + const_name(\"]\");\n};\n\n// Casts an Eigen type to numpy array.  If given a base, the numpy array references the src data,\n// otherwise it'll make a copy.  writeable lets you turn off the writeable flag for the array.\ntemplate <typename props>\nhandle\neigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {\n    constexpr ssize_t elem_size = sizeof(typename props::Scalar);\n    array a;\n    if (props::vector) {\n        a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);\n    } else {\n        a = array({src.rows(), src.cols()},\n                  {elem_size * src.rowStride(), elem_size * src.colStride()},\n                  src.data(),\n                  base);\n    }\n\n    if (!writeable) {\n        array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;\n    }\n\n    return a.release();\n}\n\n// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that\n// reference the Eigen object's data with `base` as the python-registered base class (if omitted,\n// the base will be set to None, and lifetime management is up to the caller).  The numpy array is\n// non-writeable if the given type is const.\ntemplate <typename props, typename Type>\nhandle eigen_ref_array(Type &src, handle parent = none()) {\n    // none here is to get past array's should-we-copy detection, which currently always\n    // copies when there is no base.  Setting the base to None should be harmless.\n    return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);\n}\n\n// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a\n// numpy array that references the encapsulated data with a python-side reference to the capsule to\n// tie its destruction to that of any dependent python objects.  Const-ness is determined by\n// whether or not the Type of the pointer given is const.\ntemplate <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>\nhandle eigen_encapsulate(Type *src) {\n    capsule base(src, [](void *o) { delete static_cast<Type *>(o); });\n    return eigen_ref_array<props>(*src, base);\n}\n\n// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense\n// types.\ntemplate <typename Type>\nstruct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {\n    using Scalar = typename Type::Scalar;\n    static_assert(!std::is_pointer<Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n    using props = EigenProps<Type>;\n\n    bool load(handle src, bool convert) {\n        // If we're in no-convert mode, only load if given an array of the correct type\n        if (!convert && !isinstance<array_t<Scalar>>(src)) {\n            return false;\n        }\n\n        // Coerce into an array, but don't do type conversion yet; the copy below handles it.\n        auto buf = array::ensure(src);\n\n        if (!buf) {\n            return false;\n        }\n\n        auto dims = buf.ndim();\n        if (dims < 1 || dims > 2) {\n            return false;\n        }\n\n        auto fits = props::conformable(buf);\n        if (!fits) {\n            return false;\n        }\n\n        PYBIND11_WARNING_PUSH\n        PYBIND11_WARNING_DISABLE_GCC(\"-Wmaybe-uninitialized\") // See PR #5516\n        // Allocate the new type, then build a numpy reference into it\n        value = Type(fits.rows, fits.cols);\n        PYBIND11_WARNING_POP\n        auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));\n        if (dims == 1) {\n            ref = ref.squeeze();\n        } else if (ref.ndim() == 1) {\n            buf = buf.squeeze();\n        }\n\n        int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());\n\n        if (result < 0) { // Copy failed!\n            PyErr_Clear();\n            return false;\n        }\n\n        return true;\n    }\n\nprivate:\n    // Cast implementation\n    template <typename CType>\n    static handle cast_impl(CType *src, return_value_policy policy, handle parent) {\n        switch (policy) {\n            case return_value_policy::take_ownership:\n            case return_value_policy::automatic:\n                return eigen_encapsulate<props>(src);\n            case return_value_policy::move:\n                return eigen_encapsulate<props>(new CType(std::move(*src)));\n            case return_value_policy::copy:\n                return eigen_array_cast<props>(*src);\n            case return_value_policy::reference:\n            case return_value_policy::automatic_reference:\n                return eigen_ref_array<props>(*src);\n            case return_value_policy::reference_internal:\n                return eigen_ref_array<props>(*src, parent);\n            default:\n                throw cast_error(\"unhandled return_value_policy: should not happen!\");\n        };\n    }\n\npublic:\n    // Normal returned non-reference, non-const value:\n    static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {\n        return cast_impl(&src, return_value_policy::move, parent);\n    }\n    // If you return a non-reference const, we mark the numpy array readonly:\n    static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {\n        return cast_impl(&src, return_value_policy::move, parent);\n    }\n    // lvalue reference return; default (automatic) becomes copy\n    static handle cast(Type &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast_impl(&src, policy, parent);\n    }\n    // const lvalue reference return; default (automatic) becomes copy\n    static handle cast(const Type &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast(&src, policy, parent);\n    }\n    // non-const pointer return\n    static handle cast(Type *src, return_value_policy policy, handle parent) {\n        return cast_impl(src, policy, parent);\n    }\n    // const pointer return\n    static handle cast(const Type *src, return_value_policy policy, handle parent) {\n        return cast_impl(src, policy, parent);\n    }\n\n    static constexpr auto name = props::descriptor;\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator Type *() { return &value; }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator Type &() { return value; }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator Type &&() && { return std::move(value); }\n    template <typename T>\n    using cast_op_type = movable_cast_op_type<T>;\n\nprivate:\n    Type value;\n};\n\n// Base class for casting reference/map/block/etc. objects back to python.\ntemplate <typename MapType>\nstruct eigen_map_caster {\n    static_assert(!std::is_pointer<typename MapType::Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n\nprivate:\n    using props = EigenProps<MapType>;\n\npublic:\n    // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has\n    // to stay around), but we'll allow it under the assumption that you know what you're doing\n    // (and have an appropriate keep_alive in place).  We return a numpy array pointing directly at\n    // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)\n    // Note that this means you need to ensure you don't destroy the object in some other way (e.g.\n    // with an appropriate keep_alive, or with a reference to a statically allocated matrix).\n    static handle cast(const MapType &src, return_value_policy policy, handle parent) {\n        switch (policy) {\n            case return_value_policy::copy:\n                return eigen_array_cast<props>(src);\n            case return_value_policy::reference_internal:\n                return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);\n            case return_value_policy::reference:\n            case return_value_policy::automatic:\n            case return_value_policy::automatic_reference:\n                return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);\n            default:\n                // move, take_ownership don't make any sense for a ref/map:\n                pybind11_fail(\"Invalid return_value_policy for Eigen Map/Ref/Block type\");\n        }\n    }\n\n    // return_descr forces the use of NDArray instead of ArrayLike in args\n    // since Ref<...> args can only accept arrays.\n    static constexpr auto name = return_descr(props::descriptor);\n\n    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return\n    // types but not bound arguments).  We still provide them (with an explicitly delete) so that\n    // you end up here if you try anyway.\n    bool load(handle, bool) = delete;\n    operator MapType() = delete;\n    template <typename>\n    using cast_op_type = MapType;\n};\n\n// We can return any map-like object (but can only load Refs, specialized next):\ntemplate <typename Type>\nstruct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};\n\n// Loader for Ref<...> arguments.  See the documentation for info on how to make this work without\n// copying (it requires some extra effort in many cases).\ntemplate <typename PlainObjectType, typename StrideType>\nstruct type_caster<\n    Eigen::Ref<PlainObjectType, 0, StrideType>,\n    enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>\n    : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {\nprivate:\n    using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;\n    using props = EigenProps<Type>;\n    using Scalar = typename props::Scalar;\n    static_assert(!std::is_pointer<Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n    using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;\n    using Array\n        = array_t<Scalar,\n                  array::forcecast\n                      | ((props::row_major ? props::inner_stride : props::outer_stride) == 1\n                             ? array::c_style\n                         : (props::row_major ? props::outer_stride : props::inner_stride) == 1\n                             ? array::f_style\n                             : 0)>;\n    static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;\n    // Delay construction (these have no default constructor)\n    std::unique_ptr<MapType> map;\n    std::unique_ptr<Type> ref;\n    // Our array.  When possible, this is just a numpy array pointing to the source data, but\n    // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an\n    // incompatible layout, or is an array of a type that needs to be converted).  Using a numpy\n    // temporary (rather than an Eigen temporary) saves an extra copy when we need both type\n    // conversion and storage order conversion.  (Note that we refuse to use this temporary copy\n    // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).\n    Array copy_or_ref;\n\npublic:\n    bool load(handle src, bool convert) {\n        // First check whether what we have is already an array of the right type.  If not, we\n        // can't avoid a copy (because the copy is also going to do type conversion).\n        bool need_copy = !isinstance<Array>(src);\n\n        EigenConformable<props::row_major> fits;\n        if (!need_copy) {\n            // We don't need a converting copy, but we also need to check whether the strides are\n            // compatible with the Ref's stride requirements\n            auto aref = reinterpret_borrow<Array>(src);\n\n            if (aref && (!need_writeable || aref.writeable())) {\n                fits = props::conformable(aref);\n                if (!fits) {\n                    return false; // Incompatible dimensions\n                }\n                if (!fits.template stride_compatible<props>()) {\n                    need_copy = true;\n                } else {\n                    copy_or_ref = std::move(aref);\n                }\n            } else {\n                need_copy = true;\n            }\n        }\n\n        if (need_copy) {\n            // We need to copy: If we need a mutable reference, or we're not supposed to convert\n            // (either because we're in the no-convert overload pass, or because we're explicitly\n            // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.\n            if (!convert || need_writeable) {\n                return false;\n            }\n\n            Array copy = Array::ensure(src);\n            if (!copy) {\n                return false;\n            }\n            fits = props::conformable(copy);\n            if (!fits || !fits.template stride_compatible<props>()) {\n                return false;\n            }\n            copy_or_ref = std::move(copy);\n            loader_life_support::add_patient(copy_or_ref);\n        }\n\n        ref.reset();\n        map.reset(new MapType(data(copy_or_ref),\n                              fits.rows,\n                              fits.cols,\n                              make_stride(fits.stride.outer(), fits.stride.inner())));\n        ref.reset(new Type(*map));\n\n        return true;\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator Type *() { return ref.get(); }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator Type &() { return *ref; }\n    template <typename _T>\n    using cast_op_type = pybind11::detail::cast_op_type<_T>;\n\nprivate:\n    template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>\n    Scalar *data(Array &a) {\n        return a.mutable_data();\n    }\n\n    template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>\n    const Scalar *data(Array &a) {\n        return a.data();\n    }\n\n    // Attempt to figure out a constructor of `Stride` that will work.\n    // If both strides are fixed, use a default constructor:\n    template <typename S>\n    using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic\n                                              && S::OuterStrideAtCompileTime != Eigen::Dynamic\n                                              && std::is_default_constructible<S>::value>;\n    // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like\n    // Eigen::Stride, and use it:\n    template <typename S>\n    using stride_ctor_dual\n        = bool_constant<!stride_ctor_default<S>::value\n                        && std::is_constructible<S, EigenIndex, EigenIndex>::value>;\n    // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use\n    // it (passing whichever stride is dynamic).\n    template <typename S>\n    using stride_ctor_outer\n        = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value\n                        && S::OuterStrideAtCompileTime == Eigen::Dynamic\n                        && S::InnerStrideAtCompileTime != Eigen::Dynamic\n                        && std::is_constructible<S, EigenIndex>::value>;\n    template <typename S>\n    using stride_ctor_inner\n        = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value\n                        && S::InnerStrideAtCompileTime == Eigen::Dynamic\n                        && S::OuterStrideAtCompileTime != Eigen::Dynamic\n                        && std::is_constructible<S, EigenIndex>::value>;\n\n    template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>\n    static S make_stride(EigenIndex, EigenIndex) {\n        return S();\n    }\n    template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>\n    static S make_stride(EigenIndex outer, EigenIndex inner) {\n        return S(outer, inner);\n    }\n    template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>\n    static S make_stride(EigenIndex outer, EigenIndex) {\n        return S(outer);\n    }\n    template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>\n    static S make_stride(EigenIndex, EigenIndex inner) {\n        return S(inner);\n    }\n};\n\n// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not\n// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).\n// load() is not supported, but we can cast them into the python domain by first copying to a\n// regular Eigen::Matrix, then casting that.\ntemplate <typename Type>\nstruct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {\n    static_assert(!std::is_pointer<typename Type::Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n\nprotected:\n    using Matrix\n        = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;\n    using props = EigenProps<Matrix>;\n\npublic:\n    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {\n        handle h = eigen_encapsulate<props>(new Matrix(src));\n        return h;\n    }\n    static handle cast(const Type *src, return_value_policy policy, handle parent) {\n        return cast(*src, policy, parent);\n    }\n\n    static constexpr auto name = props::descriptor;\n\n    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return\n    // types but not bound arguments).  We still provide them (with an explicitly delete) so that\n    // you end up here if you try anyway.\n    bool load(handle, bool) = delete;\n    operator Type() = delete;\n    template <typename>\n    using cast_op_type = Type;\n};\n\ntemplate <typename Type>\nstruct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {\n    using Scalar = typename Type::Scalar;\n    static_assert(!std::is_pointer<Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n    using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;\n    using Index = typename Type::Index;\n    static constexpr bool rowMajor = Type::IsRowMajor;\n\n    bool load(handle src, bool) {\n        if (!src) {\n            return false;\n        }\n\n        auto obj = reinterpret_borrow<object>(src);\n        object sparse_module = module_::import(\"scipy.sparse\");\n        object matrix_type = sparse_module.attr(rowMajor ? \"csr_matrix\" : \"csc_matrix\");\n\n        if (!type::handle_of(obj).is(matrix_type)) {\n            try {\n                obj = matrix_type(obj);\n            } catch (const error_already_set &) {\n                return false;\n            }\n        }\n\n        auto values = array_t<Scalar>((object) obj.attr(\"data\"));\n        auto innerIndices = array_t<StorageIndex>((object) obj.attr(\"indices\"));\n        auto outerIndices = array_t<StorageIndex>((object) obj.attr(\"indptr\"));\n        auto shape = pybind11::tuple((pybind11::object) obj.attr(\"shape\"));\n        auto nnz = obj.attr(\"nnz\").cast<Index>();\n\n        if (!values || !innerIndices || !outerIndices) {\n            return false;\n        }\n\n        value = EigenMapSparseMatrix<Scalar,\n                                     Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),\n                                     StorageIndex>(shape[0].cast<Index>(),\n                                                   shape[1].cast<Index>(),\n                                                   std::move(nnz),\n                                                   outerIndices.mutable_data(),\n                                                   innerIndices.mutable_data(),\n                                                   values.mutable_data());\n\n        return true;\n    }\n\n    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {\n        const_cast<Type &>(src).makeCompressed();\n\n        object matrix_type\n            = module_::import(\"scipy.sparse\").attr(rowMajor ? \"csr_matrix\" : \"csc_matrix\");\n\n        array data(src.nonZeros(), src.valuePtr());\n        array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());\n        array innerIndices(src.nonZeros(), src.innerIndexPtr());\n\n        return matrix_type(pybind11::make_tuple(\n                               std::move(data), std::move(innerIndices), std::move(outerIndices)),\n                           pybind11::make_tuple(src.rows(), src.cols()))\n            .release();\n    }\n\n    PYBIND11_TYPE_CASTER(Type,\n                         const_name<(Type::IsRowMajor) != 0>(\"scipy.sparse.csr_matrix[\",\n                                                             \"scipy.sparse.csc_matrix[\")\n                             + npy_format_descriptor<Scalar>::name + const_name(\"]\"));\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/eigen/tensor.h",
    "content": "/*\n    pybind11/eigen/tensor.h: Transparent conversion for Eigen tensors\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include <pybind11/numpy.h>\n\n#include \"common.h\"\n\n#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)\nstatic_assert(__GNUC__ > 5, \"Eigen Tensor support in pybind11 requires GCC > 5.0\");\n#endif\n\n// Disable warnings for Eigen\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_MSVC(4554)\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n#if defined(__MINGW32__)\nPYBIND11_WARNING_DISABLE_GCC(\"-Wmaybe-uninitialized\")\n#endif\n\n#include <unsupported/Eigen/CXX11/Tensor>\n\nPYBIND11_WARNING_POP\n\nstatic_assert(EIGEN_VERSION_AT_LEAST(3, 3, 0),\n              \"Eigen Tensor support in pybind11 requires Eigen >= 3.3.0\");\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline bool is_tensor_aligned(const void *data) {\n    return (reinterpret_cast<std::size_t>(data) % EIGEN_DEFAULT_ALIGN_BYTES) == 0;\n}\n\ntemplate <typename T>\nconstexpr int compute_array_flag_from_tensor() {\n    static_assert((static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor))\n                      || (static_cast<int>(T::Layout) == static_cast<int>(Eigen::ColMajor)),\n                  \"Layout must be row or column major\");\n    return (static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor)) ? array::c_style\n                                                                              : array::f_style;\n}\n\ntemplate <typename T>\nstruct eigen_tensor_helper {};\n\ntemplate <typename Scalar_, int NumIndices_, int Options_, typename IndexType>\nstruct eigen_tensor_helper<Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>> {\n    using Type = Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>;\n    using ValidType = void;\n\n    static Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape(const Type &f) {\n        return f.dimensions();\n    }\n\n    static constexpr bool\n    is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> & /*shape*/) {\n        return true;\n    }\n\n    template <typename T>\n    struct helper {};\n\n    template <size_t... Is>\n    struct helper<index_sequence<Is...>> {\n        static constexpr auto value = ::pybind11::detail::concat(const_name(((void) Is, \"?\"))...);\n    };\n\n    static constexpr auto dimensions_descriptor\n        = helper<decltype(make_index_sequence<Type::NumIndices>())>::value;\n\n    template <typename... Args>\n    static Type *alloc(Args &&...args) {\n        return new Type(std::forward<Args>(args)...);\n    }\n\n    static void free(Type *tensor) { delete tensor; }\n};\n\ntemplate <typename Scalar_, typename std::ptrdiff_t... Indices, int Options_, typename IndexType>\nstruct eigen_tensor_helper<\n    Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>> {\n    using Type = Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>;\n    using ValidType = void;\n\n    static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices>\n    get_shape(const Type & /*f*/) {\n        return get_shape();\n    }\n\n    static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape() {\n        return Eigen::DSizes<typename Type::Index, Type::NumIndices>(Indices...);\n    }\n\n    static bool\n    is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> &shape) {\n        return get_shape() == shape;\n    }\n\n    static constexpr auto dimensions_descriptor\n        = ::pybind11::detail::concat(const_name<Indices>()...);\n\n    template <typename... Args>\n    static Type *alloc(Args &&...args) {\n        Eigen::aligned_allocator<Type> allocator;\n        return ::new (allocator.allocate(1)) Type(std::forward<Args>(args)...);\n    }\n\n    static void free(Type *tensor) {\n        Eigen::aligned_allocator<Type> allocator;\n        tensor->~Type();\n        allocator.deallocate(tensor, 1);\n    }\n};\n\ntemplate <typename Type, bool ShowDetails, bool NeedsWriteable = false>\nstruct get_tensor_descriptor {\n    static constexpr auto details\n        = const_name<NeedsWriteable>(\", \\\"flags.writeable\\\"\", \"\")\n          + const_name<static_cast<int>(Type::Layout) == static_cast<int>(Eigen::RowMajor)>(\n              \", \\\"flags.c_contiguous\\\"\", \", \\\"flags.f_contiguous\\\"\");\n    static constexpr auto value\n        = const_name(\"typing.Annotated[\")\n          + io_name(\"numpy.typing.ArrayLike, \", \"numpy.typing.NDArray[\")\n          + npy_format_descriptor<typename Type::Scalar>::name + io_name(\"\", \"]\")\n          + const_name(\", \\\"[\") + eigen_tensor_helper<remove_cv_t<Type>>::dimensions_descriptor\n          + const_name(\"]\\\"\") + const_name<ShowDetails>(details, const_name(\"\")) + const_name(\"]\");\n};\n\n// When EIGEN_AVOID_STL_ARRAY is defined, Eigen::DSizes<T, 0> does not have the begin() member\n// function. Falling back to a simple loop works around this issue.\n//\n// We need to disable the type-limits warning for the inner loop when size = 0.\n\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_GCC(\"-Wtype-limits\")\n\ntemplate <typename T, int size>\nstd::vector<T> convert_dsizes_to_vector(const Eigen::DSizes<T, size> &arr) {\n    std::vector<T> result(size);\n\n    for (size_t i = 0; i < size; i++) {\n        result[i] = arr[i];\n    }\n\n    return result;\n}\n\ntemplate <typename T, int size>\nEigen::DSizes<T, size> get_shape_for_array(const array &arr) {\n    Eigen::DSizes<T, size> result;\n    const T *shape = arr.shape();\n    for (size_t i = 0; i < size; i++) {\n        result[i] = shape[i];\n    }\n\n    return result;\n}\n\nPYBIND11_WARNING_POP\n\ntemplate <typename Type>\nstruct type_caster<Type, typename eigen_tensor_helper<Type>::ValidType> {\n    static_assert(!std::is_pointer<typename Type::Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n    using Helper = eigen_tensor_helper<Type>;\n    static constexpr auto temp_name = get_tensor_descriptor<Type, false>::value;\n    PYBIND11_TYPE_CASTER(Type, temp_name);\n\n    bool load(handle src, bool convert) {\n        if (!convert) {\n            if (!isinstance<array>(src)) {\n                return false;\n            }\n            array temp = array::ensure(src);\n            if (!temp) {\n                return false;\n            }\n\n            if (!temp.dtype().is(dtype::of<typename Type::Scalar>())) {\n                return false;\n            }\n        }\n\n        array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()> arr(\n            reinterpret_borrow<object>(src));\n\n        if (arr.ndim() != Type::NumIndices) {\n            return false;\n        }\n        auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);\n\n        if (!Helper::is_correct_shape(shape)) {\n            return false;\n        }\n\n#if EIGEN_VERSION_AT_LEAST(3, 4, 0)\n        auto data_pointer = arr.data();\n#else\n        // Handle Eigen bug\n        auto data_pointer = const_cast<typename Type::Scalar *>(arr.data());\n#endif\n\n        if (is_tensor_aligned(arr.data())) {\n            value = Eigen::TensorMap<const Type, Eigen::Aligned>(data_pointer, shape);\n        } else {\n            value = Eigen::TensorMap<const Type>(data_pointer, shape);\n        }\n\n        return true;\n    }\n\n    static handle cast(Type &&src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::reference\n            || policy == return_value_policy::reference_internal) {\n            pybind11_fail(\"Cannot use a reference return value policy for an rvalue\");\n        }\n        return cast_impl(&src, return_value_policy::move, parent);\n    }\n\n    static handle cast(const Type &&src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::reference\n            || policy == return_value_policy::reference_internal) {\n            pybind11_fail(\"Cannot use a reference return value policy for an rvalue\");\n        }\n        return cast_impl(&src, return_value_policy::move, parent);\n    }\n\n    static handle cast(Type &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast_impl(&src, policy, parent);\n    }\n\n    static handle cast(const Type &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast(&src, policy, parent);\n    }\n\n    static handle cast(Type *src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic) {\n            policy = return_value_policy::take_ownership;\n        } else if (policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::reference;\n        }\n        return cast_impl(src, policy, parent);\n    }\n\n    static handle cast(const Type *src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic) {\n            policy = return_value_policy::take_ownership;\n        } else if (policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::reference;\n        }\n        return cast_impl(src, policy, parent);\n    }\n\n    template <typename C>\n    static handle cast_impl(C *src, return_value_policy policy, handle parent) {\n        object parent_object;\n        bool writeable = false;\n        switch (policy) {\n            case return_value_policy::move:\n                if (std::is_const<C>::value) {\n                    pybind11_fail(\"Cannot move from a constant reference\");\n                }\n\n                src = Helper::alloc(std::move(*src));\n\n                parent_object\n                    = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });\n                writeable = true;\n                break;\n\n            case return_value_policy::take_ownership:\n                if (std::is_const<C>::value) {\n                    // This cast is ugly, and might be UB in some cases, but we don't have an\n                    // alternative here as we must free that memory\n                    Helper::free(const_cast<Type *>(src));\n                    pybind11_fail(\"Cannot take ownership of a const reference\");\n                }\n\n                parent_object\n                    = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });\n                writeable = true;\n                break;\n\n            case return_value_policy::copy:\n                writeable = true;\n                break;\n\n            case return_value_policy::reference:\n                parent_object = none();\n                writeable = !std::is_const<C>::value;\n                break;\n\n            case return_value_policy::reference_internal:\n                // Default should do the right thing\n                if (!parent) {\n                    pybind11_fail(\"Cannot use reference internal when there is no parent\");\n                }\n                parent_object = reinterpret_borrow<object>(parent);\n                writeable = !std::is_const<C>::value;\n                break;\n\n            default:\n                pybind11_fail(\"pybind11 bug in eigen.h, please file a bug report\");\n        }\n\n        auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(\n            convert_dsizes_to_vector(Helper::get_shape(*src)), src->data(), parent_object);\n\n        if (!writeable) {\n            array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;\n        }\n\n        return result.release();\n    }\n};\n\ntemplate <typename StoragePointerType,\n          bool needs_writeable,\n          enable_if_t<!needs_writeable, bool> = true>\nStoragePointerType get_array_data_for_type(array &arr) {\n#if EIGEN_VERSION_AT_LEAST(3, 4, 0)\n    return reinterpret_cast<StoragePointerType>(arr.data());\n#else\n    // Handle Eigen bug\n    return reinterpret_cast<StoragePointerType>(const_cast<void *>(arr.data()));\n#endif\n}\n\ntemplate <typename StoragePointerType,\n          bool needs_writeable,\n          enable_if_t<needs_writeable, bool> = true>\nStoragePointerType get_array_data_for_type(array &arr) {\n    return reinterpret_cast<StoragePointerType>(arr.mutable_data());\n}\n\ntemplate <typename T, typename = void>\nstruct get_storage_pointer_type;\n\ntemplate <typename MapType>\nstruct get_storage_pointer_type<MapType, void_t<typename MapType::StoragePointerType>> {\n    using SPT = typename MapType::StoragePointerType;\n};\n\ntemplate <typename MapType>\nstruct get_storage_pointer_type<MapType, void_t<typename MapType::PointerArgType>> {\n    using SPT = typename MapType::PointerArgType;\n};\n\ntemplate <typename Type, int Options>\nstruct type_caster<Eigen::TensorMap<Type, Options>,\n                   typename eigen_tensor_helper<remove_cv_t<Type>>::ValidType> {\n    static_assert(!std::is_pointer<typename Type::Scalar>::value,\n                  PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);\n    using MapType = Eigen::TensorMap<Type, Options>;\n    using Helper = eigen_tensor_helper<remove_cv_t<Type>>;\n\n    bool load(handle src, bool /*convert*/) {\n        // Note that we have a lot more checks here as we want to make sure to avoid copies\n        if (!isinstance<array>(src)) {\n            return false;\n        }\n        auto arr = reinterpret_borrow<array>(src);\n        if ((arr.flags() & compute_array_flag_from_tensor<Type>()) == 0) {\n            return false;\n        }\n\n        if (!arr.dtype().is(dtype::of<typename Type::Scalar>())) {\n            return false;\n        }\n\n        if (arr.ndim() != Type::NumIndices) {\n            return false;\n        }\n\n        constexpr bool is_aligned = (Options & Eigen::Aligned) != 0;\n\n        if (is_aligned && !is_tensor_aligned(arr.data())) {\n            return false;\n        }\n\n        auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);\n\n        if (!Helper::is_correct_shape(shape)) {\n            return false;\n        }\n\n        if (needs_writeable && !arr.writeable()) {\n            return false;\n        }\n\n        auto result = get_array_data_for_type<typename get_storage_pointer_type<MapType>::SPT,\n                                              needs_writeable>(arr);\n\n        value.reset(new MapType(std::move(result), std::move(shape)));\n\n        return true;\n    }\n\n    static handle cast(MapType &&src, return_value_policy policy, handle parent) {\n        return cast_impl(&src, policy, parent);\n    }\n\n    static handle cast(const MapType &&src, return_value_policy policy, handle parent) {\n        return cast_impl(&src, policy, parent);\n    }\n\n    static handle cast(MapType &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast_impl(&src, policy, parent);\n    }\n\n    static handle cast(const MapType &src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic\n            || policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::copy;\n        }\n        return cast(&src, policy, parent);\n    }\n\n    static handle cast(MapType *src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic) {\n            policy = return_value_policy::take_ownership;\n        } else if (policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::reference;\n        }\n        return cast_impl(src, policy, parent);\n    }\n\n    static handle cast(const MapType *src, return_value_policy policy, handle parent) {\n        if (policy == return_value_policy::automatic) {\n            policy = return_value_policy::take_ownership;\n        } else if (policy == return_value_policy::automatic_reference) {\n            policy = return_value_policy::reference;\n        }\n        return cast_impl(src, policy, parent);\n    }\n\n    template <typename C>\n    static handle cast_impl(C *src, return_value_policy policy, handle parent) {\n        object parent_object;\n        constexpr bool writeable = !std::is_const<C>::value;\n        switch (policy) {\n            case return_value_policy::reference:\n                parent_object = none();\n                break;\n\n            case return_value_policy::reference_internal:\n                // Default should do the right thing\n                if (!parent) {\n                    pybind11_fail(\"Cannot use reference internal when there is no parent\");\n                }\n                parent_object = reinterpret_borrow<object>(parent);\n                break;\n\n            default:\n                // move, take_ownership don't make any sense for a ref/map:\n                pybind11_fail(\"Invalid return_value_policy for Eigen Map type, must be either \"\n                              \"reference or reference_internal\");\n        }\n\n        auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(\n            convert_dsizes_to_vector(Helper::get_shape(*src)),\n            src->data(),\n            std::move(parent_object));\n\n        if (!writeable) {\n            array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;\n        }\n\n        return result.release();\n    }\n\n#if EIGEN_VERSION_AT_LEAST(3, 4, 0)\n\n    static constexpr bool needs_writeable = !std::is_const<typename std::remove_pointer<\n        typename get_storage_pointer_type<MapType>::SPT>::type>::value;\n#else\n    // Handle Eigen bug\n    static constexpr bool needs_writeable = !std::is_const<Type>::value;\n#endif\n\nprotected:\n    // TODO: Move to std::optional once std::optional has more support\n    std::unique_ptr<MapType> value;\n\npublic:\n    // return_descr forces the use of NDArray instead of ArrayLike since refs can only reference\n    // arrays\n    static constexpr auto name\n        = return_descr(get_tensor_descriptor<Type, true, needs_writeable>::value);\n    explicit operator MapType *() { return value.get(); }\n    explicit operator MapType &() { return *value; }\n    explicit operator MapType &&() && { return std::move(*value); }\n\n    template <typename T_>\n    using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>;\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/eigen.h",
    "content": "/*\n    pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"eigen/matrix.h\"\n"
  },
  {
    "path": "include/pybind11/embed.h",
    "content": "/*\n    pybind11/embed.h: Support for embedding the interpreter\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n#include \"eval.h\"\n\n#include <memory>\n#include <vector>\n\n#if defined(PYPY_VERSION)\n#    error Embedding the interpreter is not supported with PyPy\n#endif\n\n#define PYBIND11_EMBEDDED_MODULE_IMPL(name)                                                       \\\n    extern \"C\" PyObject *pybind11_init_impl_##name();                                             \\\n    extern \"C\" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }\n\n/** \\rst\n    Add a new module to the table of builtins for the interpreter. Must be\n    defined in global scope. The first macro parameter is the name of the\n    module (without quotes). The second parameter is the variable which will\n    be used as the interface to add functions and classes to the module.\n\n    .. code-block:: cpp\n\n        PYBIND11_EMBEDDED_MODULE(example, m) {\n            // ... initialize functions and classes here\n            m.def(\"foo\", []() {\n                return \"Hello, World!\";\n            });\n        }\n\n    The third and subsequent macro arguments are optional, and can be used to\n    mark the module as supporting various Python features.\n\n    - ``mod_gil_not_used()``\n    - ``multiple_interpreters::per_interpreter_gil()``\n    - ``multiple_interpreters::shared_gil()``\n    - ``multiple_interpreters::not_supported()``\n\n    .. code-block:: cpp\n\n        PYBIND11_EMBEDDED_MODULE(example, m, py::mod_gil_not_used()) {\n            m.def(\"foo\", []() {\n                return \"Hello, Free-threaded World!\";\n            });\n        }\n\n \\endrst */\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wgnu-zero-variadic-macro-arguments\")\n#define PYBIND11_EMBEDDED_MODULE(name, variable, ...)                                             \\\n    PYBIND11_MODULE_PYINIT(name, ##__VA_ARGS__)                                                   \\\n    ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)(                  \\\n        PYBIND11_TOSTRING(name), PYBIND11_CONCAT(PyInit_, name));                                 \\\n    PYBIND11_MODULE_EXEC(name, variable)\nPYBIND11_WARNING_POP\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.\nstruct embedded_module {\n    using init_t = PyObject *(*) ();\n    embedded_module(const char *name, init_t init) {\n        if (Py_IsInitialized() != 0) {\n            pybind11_fail(\"Can't add new modules after the interpreter has been initialized\");\n        }\n\n        auto result = PyImport_AppendInittab(name, init);\n        if (result == -1) {\n            pybind11_fail(\"Insufficient memory to add a new module\");\n        }\n    }\n};\n\nstruct wide_char_arg_deleter {\n    void operator()(wchar_t *ptr) const {\n        // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale\n        PyMem_RawFree(ptr);\n    }\n};\n\ninline wchar_t *widen_chars(const char *safe_arg) {\n    wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);\n    return widened_arg;\n}\n\ninline void precheck_interpreter() {\n    if (Py_IsInitialized() != 0) {\n        pybind11_fail(\"The interpreter is already running\");\n    }\n}\n\n#if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)\n#    define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)\n#endif\n\n#if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\ninline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,\n                                                int argc,\n                                                const char *const *argv,\n                                                bool add_program_dir_to_path) {\n    detail::precheck_interpreter();\n    Py_InitializeEx(init_signal_handlers ? 1 : 0);\n\n    auto argv_size = static_cast<size_t>(argc);\n    // SetArgv* on python 3 takes wchar_t, so we have to convert.\n    std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);\n    std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;\n    widened_argv_entries.reserve(argv_size);\n    for (size_t ii = 0; ii < argv_size; ++ii) {\n        widened_argv_entries.emplace_back(detail::widen_chars(argv[ii]));\n        if (!widened_argv_entries.back()) {\n            // A null here indicates a character-encoding failure or the python\n            // interpreter out of memory. Give up.\n            return;\n        }\n        widened_argv[ii] = widened_argv_entries.back().get();\n    }\n\n    auto *pysys_argv = widened_argv.get();\n\n    PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));\n}\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\n\n#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\ninline void initialize_interpreter(PyConfig *config,\n                                   int argc = 0,\n                                   const char *const *argv = nullptr,\n                                   bool add_program_dir_to_path = true) {\n    detail::precheck_interpreter();\n    PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));\n    if (PyStatus_Exception(status) != 0) {\n        // A failure here indicates a character-encoding failure or the python\n        // interpreter out of memory. Give up.\n        PyConfig_Clear(config);\n        throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg\n                                                               : \"Failed to prepare CPython\");\n    }\n    status = Py_InitializeFromConfig(config);\n    if (PyStatus_Exception(status) != 0) {\n        PyConfig_Clear(config);\n        throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg\n                                                               : \"Failed to init CPython\");\n    }\n    if (add_program_dir_to_path) {\n        PyRun_SimpleString(\"import sys, os.path; \"\n                           \"sys.path.insert(0, \"\n                           \"os.path.abspath(os.path.dirname(sys.argv[0])) \"\n                           \"if sys.argv and os.path.exists(sys.argv[0]) else '')\");\n    }\n    PyConfig_Clear(config);\n}\n#endif\n\n/** \\rst\n    Initialize the Python interpreter. No other pybind11 or CPython API functions can be\n    called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The\n    optional `init_signal_handlers` parameter can be used to skip the registration of\n    signal handlers (see the `Python documentation`_ for details). Calling this function\n    again after the interpreter has already been initialized is a fatal error.\n\n    If initializing the Python interpreter fails, then the program is terminated.  (This\n    is controlled by the CPython runtime and is an exception to pybind11's normal behavior\n    of throwing exceptions on errors.)\n\n    The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are\n    used to populate ``sys.argv`` and ``sys.path``.\n    See the |PySys_SetArgvEx documentation|_ for details.\n\n    .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx\n    .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation\n    .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx\n \\endrst */\ninline void initialize_interpreter(bool init_signal_handlers = true,\n                                   int argc = 0,\n                                   const char *const *argv = nullptr,\n                                   bool add_program_dir_to_path = true) {\n#if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\n    detail::initialize_interpreter_pre_pyconfig(\n        init_signal_handlers, argc, argv, add_program_dir_to_path);\n#else\n    PyConfig config;\n    PyConfig_InitPythonConfig(&config);\n    // See PR #4473 for background\n    config.parse_argv = 0;\n\n    config.install_signal_handlers = init_signal_handlers ? 1 : 0;\n    initialize_interpreter(&config, argc, argv, add_program_dir_to_path);\n#endif\n\n    // There is exactly one interpreter alive currently.\n    detail::has_seen_non_main_interpreter() = false;\n}\n\n/** \\rst\n    Shut down the Python interpreter. No pybind11 or CPython API functions can be called\n    after this. In addition, pybind11 objects must not outlive the interpreter:\n\n    .. code-block:: cpp\n\n        { // BAD\n            py::initialize_interpreter();\n            auto hello = py::str(\"Hello, World!\");\n            py::finalize_interpreter();\n        } // <-- BOOM, hello's destructor is called after interpreter shutdown\n\n        { // GOOD\n            py::initialize_interpreter();\n            { // scoped\n                auto hello = py::str(\"Hello, World!\");\n            } // <-- OK, hello is cleaned up properly\n            py::finalize_interpreter();\n        }\n\n        { // BETTER\n            py::scoped_interpreter guard{};\n            auto hello = py::str(\"Hello, World!\");\n        }\n\n    .. warning::\n\n        The interpreter can be restarted by calling `initialize_interpreter` again.\n        Modules created using pybind11 can be safely re-initialized. However, Python\n        itself cannot completely unload binary extension modules and there are several\n        caveats with regard to interpreter restarting. All the details can be found\n        in the CPython documentation. In short, not all interpreter memory may be\n        freed, either due to reference cycles or user-created global data.\n\n \\endrst */\ninline void finalize_interpreter() {\n    // get rid of any thread-local interpreter cache that currently exists\n    if (detail::has_seen_non_main_interpreter()) {\n        detail::get_internals_pp_manager().unref();\n        detail::get_local_internals_pp_manager().unref();\n\n        // We know there can be no other interpreter alive now\n        detail::has_seen_non_main_interpreter() = false;\n    }\n\n    // Re-fetch the internals pointer-to-pointer (but not the internals itself, which might not\n    // exist). It's possible for the  internals to be created during Py_Finalize() (e.g. if a\n    // py::capsule calls `get_internals()` during destruction), so we get the pointer-pointer here\n    // and check it after Py_Finalize().\n    detail::get_internals_pp_manager().get_pp();\n    detail::get_local_internals_pp_manager().get_pp();\n\n    Py_Finalize();\n\n    detail::get_internals_pp_manager().destroy();\n\n    // Local internals contains data managed by the current interpreter, so we must clear them to\n    // avoid undefined behaviors when initializing another interpreter\n    detail::get_local_internals_pp_manager().destroy();\n\n    // We know there is no interpreter alive now, so we can reset the multi-flag\n    detail::has_seen_non_main_interpreter() = false;\n}\n\n/** \\rst\n    Scope guard version of `initialize_interpreter` and `finalize_interpreter`.\n    This a move-only guard and only a single instance can exist.\n\n    See `initialize_interpreter` for a discussion of its constructor arguments.\n\n    .. code-block:: cpp\n\n        #include <pybind11/embed.h>\n\n        int main() {\n            py::scoped_interpreter guard{};\n            py::print(Hello, World!);\n        } // <-- interpreter shutdown\n \\endrst */\nclass scoped_interpreter {\npublic:\n    explicit scoped_interpreter(bool init_signal_handlers = true,\n                                int argc = 0,\n                                const char *const *argv = nullptr,\n                                bool add_program_dir_to_path = true) {\n        initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);\n    }\n\n#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\n    explicit scoped_interpreter(PyConfig *config,\n                                int argc = 0,\n                                const char *const *argv = nullptr,\n                                bool add_program_dir_to_path = true) {\n        initialize_interpreter(config, argc, argv, add_program_dir_to_path);\n    }\n#endif\n\n    scoped_interpreter(const scoped_interpreter &) = delete;\n    scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }\n    scoped_interpreter &operator=(const scoped_interpreter &) = delete;\n    scoped_interpreter &operator=(scoped_interpreter &&) = delete;\n\n    ~scoped_interpreter() {\n        if (is_valid) {\n            finalize_interpreter();\n        }\n    }\n\nprivate:\n    bool is_valid = true;\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/eval.h",
    "content": "/*\n    pybind11/eval.h: Support for evaluating Python expressions and statements\n    from strings and files\n\n    Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and\n                       Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\n#include <utility>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline void ensure_builtins_in_globals(object &global) {\n#if defined(PYPY_VERSION)\n    // Running exec and eval adds `builtins` module under `__builtins__` key to\n    // globals if not yet present.  Python 3.8 made PyRun_String behave\n    // similarly. Let's also do that for older versions, for consistency. This\n    // was missing from PyPy3.8 7.3.7.\n    if (!global.contains(\"__builtins__\"))\n        global[\"__builtins__\"] = module_::import(PYBIND11_BUILTINS_MODULE);\n#else\n    (void) global;\n#endif\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\nenum eval_mode {\n    /// Evaluate a string containing an isolated expression\n    eval_expr,\n\n    /// Evaluate a string containing a single statement. Returns \\c none\n    eval_single_statement,\n\n    /// Evaluate a string containing a sequence of statement. Returns \\c none\n    eval_statements\n};\n\ntemplate <eval_mode mode = eval_expr>\nobject eval(const str &expr, object global = globals(), object local = object()) {\n    if (!local) {\n        local = global;\n    }\n\n    detail::ensure_builtins_in_globals(global);\n\n    /* PyRun_String does not accept a PyObject / encoding specifier,\n       this seems to be the only alternative */\n    std::string buffer = \"# -*- coding: utf-8 -*-\\n\" + (std::string) expr;\n\n    int start = 0;\n    switch (mode) {\n        case eval_expr:\n            start = Py_eval_input;\n            break;\n        case eval_single_statement:\n            start = Py_single_input;\n            break;\n        case eval_statements:\n            start = Py_file_input;\n            break;\n        default:\n            pybind11_fail(\"invalid evaluation mode\");\n    }\n\n    PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());\n    if (!result) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<object>(result);\n}\n\ntemplate <eval_mode mode = eval_expr, size_t N>\nobject eval(const char (&s)[N], object global = globals(), object local = object()) {\n    /* Support raw string literals by removing common leading whitespace */\n    auto expr = (s[0] == '\\n') ? str(module_::import(\"textwrap\").attr(\"dedent\")(s)) : str(s);\n    return eval<mode>(expr, std::move(global), std::move(local));\n}\n\ninline void exec(const str &expr, object global = globals(), object local = object()) {\n    eval<eval_statements>(expr, std::move(global), std::move(local));\n}\n\ntemplate <size_t N>\nvoid exec(const char (&s)[N], object global = globals(), object local = object()) {\n    eval<eval_statements>(s, std::move(global), std::move(local));\n}\n\n#if defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)\ntemplate <eval_mode mode = eval_statements>\nobject eval_file(str, object, object) {\n    pybind11_fail(\"eval_file not supported in this interpreter. Use eval\");\n}\ntemplate <eval_mode mode = eval_statements>\nobject eval_file(str, object) {\n    pybind11_fail(\"eval_file not supported in this interpreter. Use eval\");\n}\ntemplate <eval_mode mode = eval_statements>\nobject eval_file(str) {\n    pybind11_fail(\"eval_file not supported in this interpreter. Use eval\");\n}\n#else\ntemplate <eval_mode mode = eval_statements>\nobject eval_file(str fname, object global = globals(), object local = object()) {\n    if (!local) {\n        local = global;\n    }\n\n    detail::ensure_builtins_in_globals(global);\n\n    int start = 0;\n    switch (mode) {\n        case eval_expr:\n            start = Py_eval_input;\n            break;\n        case eval_single_statement:\n            start = Py_single_input;\n            break;\n        case eval_statements:\n            start = Py_file_input;\n            break;\n        default:\n            pybind11_fail(\"invalid evaluation mode\");\n    }\n\n    int closeFile = 1;\n    std::string fname_str = (std::string) fname;\n    FILE *f =\n#    if PY_VERSION_HEX >= 0x030E0000\n        Py_fopen(fname.ptr(), \"r\");\n#    else\n        _Py_fopen_obj(fname.ptr(), \"r\");\n#    endif\n    if (!f) {\n        PyErr_Clear();\n        pybind11_fail(\"File \\\"\" + fname_str + \"\\\" could not be opened!\");\n    }\n\n    if (!global.contains(\"__file__\")) {\n        global[\"__file__\"] = std::move(fname);\n    }\n\n    PyObject *result\n        = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);\n\n    if (!result) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<object>(result);\n}\n#endif\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/functional.h",
    "content": "/*\n    pybind11/functional.h: std::function<> support\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\n#include <functional>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\nPYBIND11_NAMESPACE_BEGIN(type_caster_std_function_specializations)\n\n// ensure GIL is held during functor destruction\nstruct func_handle {\n    function f;\n#if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))\n    // This triggers a syntax error under very special conditions (very weird indeed).\n    explicit\n#endif\n        func_handle(function &&f_) noexcept\n        : f(std::move(f_)) {\n    }\n    func_handle(const func_handle &f_) { operator=(f_); }\n    func_handle &operator=(const func_handle &f_) {\n        gil_scoped_acquire acq;\n        f = f_.f;\n        return *this;\n    }\n    ~func_handle() {\n        gil_scoped_acquire acq;\n        function kill_f(std::move(f));\n    }\n};\n\n// to emulate 'move initialization capture' in C++11\nstruct func_wrapper_base {\n    func_handle hfunc;\n    explicit func_wrapper_base(func_handle &&hf) noexcept : hfunc(hf) {}\n};\n\ntemplate <typename Return, typename... Args>\nstruct func_wrapper : func_wrapper_base {\n    using func_wrapper_base::func_wrapper_base;\n    Return operator()(Args... args) const { // NOLINT(performance-unnecessary-value-param)\n        gil_scoped_acquire acq;\n        // casts the returned object as a rvalue to the return type\n        return hfunc.f(std::forward<Args>(args)...).template cast<Return>();\n    }\n};\n\nPYBIND11_NAMESPACE_END(type_caster_std_function_specializations)\n\ntemplate <typename Return, typename... Args>\nstruct type_caster<std::function<Return(Args...)>> {\n    using type = std::function<Return(Args...)>;\n    using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;\n    using function_type = Return (*)(Args...);\n\npublic:\n    bool load(handle src, bool convert) {\n        if (src.is_none()) {\n            // Defer accepting None to other overloads (if we aren't in convert mode):\n            if (!convert) {\n                return false;\n            }\n            return true;\n        }\n\n        if (!isinstance<function>(src)) {\n            return false;\n        }\n\n        auto func = reinterpret_borrow<function>(src);\n\n        /*\n           When passing a C++ function as an argument to another C++\n           function via Python, every function call would normally involve\n           a full C++ -> Python -> C++ roundtrip, which can be prohibitive.\n           Here, we try to at least detect the case where the function is\n           stateless (i.e. function pointer or lambda function without\n           captured variables), in which case the roundtrip can be avoided.\n         */\n        if (auto cfunc = func.cpp_function()) {\n            auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());\n            if (cfunc_self == nullptr) {\n                PyErr_Clear();\n            } else {\n                function_record *rec = function_record_ptr_from_PyObject(cfunc_self);\n                while (rec != nullptr) {\n                    if (rec->is_stateless\n                        && same_type(typeid(function_type),\n                                     *reinterpret_cast<const std::type_info *>(rec->data[1]))) {\n                        struct capture {\n                            function_type f;\n\n                            static capture *from_data(void **data) {\n                                return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));\n                            }\n                        };\n                        PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(\n                            std::is_standard_layout<capture>::value);\n                        value = capture::from_data(rec->data)->f;\n                        return true;\n                    }\n                    rec = rec->next;\n                }\n            }\n            // PYPY segfaults here when passing builtin function like sum.\n            // Raising an fail exception here works to prevent the segfault, but only on gcc.\n            // See PR #1413 for full details\n        }\n\n        value = type_caster_std_function_specializations::func_wrapper<Return, Args...>(\n            type_caster_std_function_specializations::func_handle(std::move(func)));\n        return true;\n    }\n\n    template <typename Func>\n    static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {\n        if (!f_) {\n            return none().release();\n        }\n\n        auto result = f_.template target<function_type>();\n        if (result) {\n            return cpp_function(*result, policy).release();\n        }\n        return cpp_function(std::forward<Func>(f_), policy).release();\n    }\n\n    PYBIND11_TYPE_CASTER(\n        type,\n        const_name(\"collections.abc.Callable[[\")\n            + ::pybind11::detail::concat(::pybind11::detail::arg_descr(make_caster<Args>::name)...)\n            + const_name(\"], \") + ::pybind11::detail::return_descr(make_caster<retval_type>::name)\n            + const_name(\"]\"));\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/gil.h",
    "content": "/*\n    pybind11/gil.h: RAII helpers for managing the GIL\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)\n\n#    include \"detail/common.h\"\n#    include \"gil_simple.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nusing gil_scoped_acquire = gil_scoped_acquire_simple;\nusing gil_scoped_release = gil_scoped_release_simple;\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\n#else\n\n#    include \"detail/common.h\"\n#    include \"detail/internals.h\"\n\n#    include <cassert>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_GCC(\"-Wredundant-decls\")\n\n// forward declarations\nPyThreadState *get_thread_state_unchecked();\n\nPYBIND11_WARNING_POP\n\nPYBIND11_NAMESPACE_END(detail)\n\n/* The functions below essentially reproduce the PyGILState_* API using a RAII\n * pattern, but there are a few important differences:\n *\n * 1. When acquiring the GIL from an non-main thread during the finalization\n *    phase, the GILState API blindly terminates the calling thread, which\n *    is often not what is wanted. This API does not do this.\n *\n * 2. The gil_scoped_release function can optionally cut the relationship\n *    of a PyThreadState and its associated thread, which allows moving it to\n *    another thread (this is a fairly rare/advanced use case).\n *\n * 3. The reference count of an acquired thread state can be controlled. This\n *    can be handy to prevent cases where callbacks issued from an external\n *    thread would otherwise constantly construct and destroy thread state data\n *    structures.\n *\n * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an\n * example which uses features 2 and 3 to migrate the Python thread of\n * execution to another thread (to run the event loop on the original thread,\n * in this case).\n */\n\nclass gil_scoped_acquire {\npublic:\n    PYBIND11_NOINLINE gil_scoped_acquire() {\n        auto &internals = detail::get_internals();\n        tstate = internals.tstate.get();\n\n        if (!tstate) {\n            /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if\n               calling from a Python thread). Since we use a different key, this ensures\n               we don't create a new thread state and deadlock in PyEval_AcquireThread\n               below. Note we don't save this state with internals.tstate, since we don't\n               create it we would fail to clear it (its reference count should be > 0). */\n            tstate = PyGILState_GetThisThreadState();\n        }\n\n        if (!tstate) {\n            tstate = PyThreadState_New(internals.istate);\n#    if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            if (!tstate) {\n                pybind11_fail(\"scoped_acquire: could not create thread state!\");\n            }\n#    endif\n            tstate->gilstate_counter = 0;\n            internals.tstate = tstate;\n        } else {\n            release = detail::get_thread_state_unchecked() != tstate;\n        }\n\n        if (release) {\n            PyEval_AcquireThread(tstate);\n        }\n\n        inc_ref();\n    }\n\n    gil_scoped_acquire(const gil_scoped_acquire &) = delete;\n    gil_scoped_acquire &operator=(const gil_scoped_acquire &) = delete;\n\n    void inc_ref() { ++tstate->gilstate_counter; }\n\n    PYBIND11_NOINLINE void dec_ref() {\n        --tstate->gilstate_counter;\n#    if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n        if (detail::get_thread_state_unchecked() != tstate) {\n            pybind11_fail(\"scoped_acquire::dec_ref(): thread state must be current!\");\n        }\n        if (tstate->gilstate_counter < 0) {\n            pybind11_fail(\"scoped_acquire::dec_ref(): reference count underflow!\");\n        }\n#    endif\n        if (tstate->gilstate_counter == 0) {\n#    if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            if (!release) {\n                pybind11_fail(\"scoped_acquire::dec_ref(): internal error!\");\n            }\n#    endif\n            // Make sure that PyThreadState_Clear is not recursively called by finalizers.\n            // See issue #5827\n            ++tstate->gilstate_counter;\n            PyThreadState_Clear(tstate);\n            --tstate->gilstate_counter;\n            if (active) {\n                PyThreadState_DeleteCurrent();\n            }\n            detail::get_internals().tstate.reset();\n            release = false;\n        }\n    }\n\n    /// This method will disable the PyThreadState_DeleteCurrent call and the\n    /// GIL won't be released. This method should be used if the interpreter\n    /// could be shutting down when this is called, as thread deletion is not\n    /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and\n    /// protect subsequent code.\n    PYBIND11_NOINLINE void disarm() { active = false; }\n\n    PYBIND11_NOINLINE ~gil_scoped_acquire() {\n        dec_ref();\n        if (release) {\n            PyEval_SaveThread();\n        }\n    }\n\nprivate:\n    PyThreadState *tstate = nullptr;\n    bool release = true;\n    bool active = true;\n};\n\nclass gil_scoped_release {\npublic:\n    // PRECONDITION: The GIL must be held when this constructor is called.\n    explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {\n        assert(PyGILState_Check());\n        // `get_internals()` must be called here unconditionally in order to initialize\n        // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an\n        // initialization race could occur as multiple threads try `gil_scoped_acquire`.\n        auto &internals = detail::get_internals();\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        tstate = PyEval_SaveThread();\n        if (disassoc) {\n            internals.tstate.reset();\n        }\n    }\n\n    gil_scoped_release(const gil_scoped_release &) = delete;\n    gil_scoped_release &operator=(const gil_scoped_release &) = delete;\n\n    /// This method will disable the PyThreadState_DeleteCurrent call and the\n    /// GIL won't be acquired. This method should be used if the interpreter\n    /// could be shutting down when this is called, as thread deletion is not\n    /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and\n    /// protect subsequent code.\n    PYBIND11_NOINLINE void disarm() { active = false; }\n\n    ~gil_scoped_release() {\n        if (!tstate) {\n            return;\n        }\n        // `PyEval_RestoreThread()` should not be called if runtime is finalizing\n        if (active) {\n            PyEval_RestoreThread(tstate);\n        }\n        if (disassoc) {\n            detail::get_internals().tstate = tstate;\n        }\n    }\n\nprivate:\n    PyThreadState *tstate;\n    bool disassoc;\n    bool active = true;\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\n#endif // !PYBIND11_SIMPLE_GIL_MANAGEMENT\n"
  },
  {
    "path": "include/pybind11/gil_safe_call_once.h",
    "content": "// Copyright (c) 2023 The pybind Community.\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/internals.h\"\n#include \"gil.h\"\n\n#include <cassert>\n#include <mutex>\n\n#if defined(Py_GIL_DISABLED) || defined(PYBIND11_HAS_SUBINTERPRETER_SUPPORT)\n#    include <atomic>\n#endif\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n#    include <cstdint>\n#    include <memory>\n#    include <string>\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n#if defined(Py_GIL_DISABLED) || defined(PYBIND11_HAS_SUBINTERPRETER_SUPPORT)\nusing atomic_bool = std::atomic_bool;\n#else\nusing atomic_bool = bool;\n#endif\nPYBIND11_NAMESPACE_END(detail)\n\n// Use the `gil_safe_call_once_and_store` class below instead of the naive\n//\n//   static auto imported_obj = py::module_::import(\"module_name\"); // BAD, DO NOT USE!\n//\n// which has two serious issues:\n//\n//     1. Py_DECREF() calls potentially after the Python interpreter was finalized already, and\n//     2. deadlocks in multi-threaded processes (because of missing lock ordering).\n//\n// The following alternative avoids both problems:\n//\n//   PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;\n//   auto &imported_obj = storage // Do NOT make this `static`!\n//       .call_once_and_store_result([]() {\n//           return py::module_::import(\"module_name\");\n//       })\n//       .get_stored();\n//\n// The parameter of `call_once_and_store_result()` must be callable. It can make\n// CPython API calls, and in particular, it can temporarily release the GIL.\n//\n// `T` can be any C++ type, it does not have to involve CPython API types.\n//\n// The behavior with regard to signals, e.g. `SIGINT` (`KeyboardInterrupt`),\n// is not ideal. If the main thread is the one to actually run the `Callable`,\n// then a `KeyboardInterrupt` will interrupt it if it is running normal Python\n// code. The situation is different if a non-main thread runs the\n// `Callable`, and then the main thread starts waiting for it to complete:\n// a `KeyboardInterrupt` will not interrupt the non-main thread, but it will\n// get processed only when it is the main thread's turn again and it is running\n// normal Python code. However, this will be unnoticeable for quick call-once\n// functions, which is usually the case.\n//\n// For in-depth background, see docs/advanced/deadlock.md\n#ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n// Subinterpreter support is disabled.\n// In this case, we can store the result globally, because there is only a single interpreter.\n//\n// The life span of the stored result is the entire process lifetime. It is leaked on process\n// termination to avoid destructor calls after the Python interpreter was finalized.\ntemplate <typename T>\nclass gil_safe_call_once_and_store {\npublic:\n    // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called.\n    //\n    // NOTE: The second parameter (finalize callback) is intentionally unused when subinterpreter\n    // support is disabled. In that case, storage is process-global and intentionally leaked to\n    // avoid calling destructors after the Python interpreter has been finalized.\n    template <typename Callable>\n    gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn,\n                                                             void (*)(T &) /*unused*/ = nullptr) {\n        if (!is_initialized_) { // This read is guarded by the GIL.\n            // Multiple threads may enter here, because the GIL is released in the next line and\n            // CPython API calls in the `fn()` call below may release and reacquire the GIL.\n            gil_scoped_release gil_rel; // Needed to establish lock ordering.\n            std::call_once(once_flag_, [&] {\n                // Only one thread will ever enter here.\n                gil_scoped_acquire gil_acq;\n                ::new (storage_) T(fn()); // fn may release, but will reacquire, the GIL.\n                is_initialized_ = true;   // This write is guarded by the GIL.\n            });\n            // All threads will observe `is_initialized_` as true here.\n        }\n        // Intentionally not returning `T &` to ensure the calling code is self-documenting.\n        return *this;\n    }\n\n    // This must only be called after `call_once_and_store_result()` was called.\n    T &get_stored() {\n        assert(is_initialized_);\n        PYBIND11_WARNING_PUSH\n#    if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5\n        // Needed for gcc 4.8.5\n        PYBIND11_WARNING_DISABLE_GCC(\"-Wstrict-aliasing\")\n#    endif\n        return *reinterpret_cast<T *>(storage_);\n        PYBIND11_WARNING_POP\n    }\n\n    constexpr gil_safe_call_once_and_store() = default;\n    // The instance is a global static, so its destructor runs when the process\n    // is terminating. Therefore, do nothing here because the Python interpreter\n    // may have been finalized already.\n    PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default;\n\n    // Disable copy and move operations.\n    gil_safe_call_once_and_store(const gil_safe_call_once_and_store &) = delete;\n    gil_safe_call_once_and_store(gil_safe_call_once_and_store &&) = delete;\n    gil_safe_call_once_and_store &operator=(const gil_safe_call_once_and_store &) = delete;\n    gil_safe_call_once_and_store &operator=(gil_safe_call_once_and_store &&) = delete;\n\nprivate:\n    // The global static storage (per-process) when subinterpreter support is disabled.\n    alignas(T) char storage_[sizeof(T)] = {};\n    std::once_flag once_flag_;\n\n    // The `is_initialized_`-`storage_` pair is very similar to `std::optional`,\n    // but the latter does not have the triviality properties of former,\n    // therefore `std::optional` is not a viable alternative here.\n    detail::atomic_bool is_initialized_{false};\n};\n#else\n// Subinterpreter support is enabled.\n// In this case, we should store the result per-interpreter instead of globally, because each\n// subinterpreter has its own separate state. The cached result may not shareable across\n// interpreters (e.g., imported modules and their members).\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename T>\nstruct call_once_storage {\n    alignas(T) char storage[sizeof(T)] = {};\n    std::once_flag once_flag;\n    void (*finalize)(T &) = nullptr;\n    std::atomic_bool is_initialized{false};\n\n    call_once_storage() = default;\n    ~call_once_storage() {\n        if (is_initialized) {\n            if (finalize != nullptr) {\n                finalize(*reinterpret_cast<T *>(storage));\n            } else {\n                reinterpret_cast<T *>(storage)->~T();\n            }\n        }\n    }\n    call_once_storage(const call_once_storage &) = delete;\n    call_once_storage(call_once_storage &&) = delete;\n    call_once_storage &operator=(const call_once_storage &) = delete;\n    call_once_storage &operator=(call_once_storage &&) = delete;\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n// Prefix for storage keys in the interpreter state dict.\n#    define PYBIND11_CALL_ONCE_STORAGE_KEY_PREFIX PYBIND11_INTERNALS_ID \"_call_once_storage__\"\n\n// The life span of the stored result is the entire interpreter lifetime. An additional\n// `finalize_fn` can be provided to clean up the stored result when the interpreter is destroyed.\ntemplate <typename T>\nclass gil_safe_call_once_and_store {\npublic:\n    // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called.\n    template <typename Callable>\n    gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn,\n                                                             void (*finalize_fn)(T &) = nullptr) {\n        if (!is_last_storage_valid()) {\n            // Multiple threads may enter here, because the GIL is released in the next line and\n            // CPython API calls in the `fn()` call below may release and reacquire the GIL.\n            gil_scoped_release gil_rel; // Needed to establish lock ordering.\n            // There can be multiple threads going through here.\n            storage_type *value = nullptr;\n            {\n                gil_scoped_acquire gil_acq; // Restore lock ordering.\n                // This function is thread-safe under free-threading.\n                value = get_or_create_storage_in_state_dict();\n            }\n            assert(value != nullptr);\n            std::call_once(value->once_flag, [&] {\n                // Only one thread will ever enter here.\n                gil_scoped_acquire gil_acq;\n                // fn may release, but will reacquire, the GIL.\n                ::new (value->storage) T(fn());\n                value->finalize = finalize_fn;\n                value->is_initialized = true;\n                last_storage_ptr_ = reinterpret_cast<T *>(value->storage);\n                is_initialized_by_at_least_one_interpreter_ = true;\n            });\n            // All threads will observe `is_initialized_by_at_least_one_interpreter_` as true here.\n        }\n        // Intentionally not returning `T &` to ensure the calling code is self-documenting.\n        return *this;\n    }\n\n    // This must only be called after `call_once_and_store_result()` was called.\n    T &get_stored() {\n        T *result = last_storage_ptr_;\n        if (!is_last_storage_valid()) {\n            gil_scoped_acquire gil_acq;\n            auto *value = get_or_create_storage_in_state_dict();\n            result = last_storage_ptr_ = reinterpret_cast<T *>(value->storage);\n        }\n        assert(result != nullptr);\n        return *result;\n    }\n\n    constexpr gil_safe_call_once_and_store() = default;\n    // The instance is a global static, so its destructor runs when the process\n    // is terminating. Therefore, do nothing here because the Python interpreter\n    // may have been finalized already.\n    PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default;\n\n    // Disable copy and move operations because the memory address is used as key.\n    gil_safe_call_once_and_store(const gil_safe_call_once_and_store &) = delete;\n    gil_safe_call_once_and_store(gil_safe_call_once_and_store &&) = delete;\n    gil_safe_call_once_and_store &operator=(const gil_safe_call_once_and_store &) = delete;\n    gil_safe_call_once_and_store &operator=(gil_safe_call_once_and_store &&) = delete;\n\nprivate:\n    using storage_type = detail::call_once_storage<T>;\n\n    // Indicator of fast path for single-interpreter case.\n    bool is_last_storage_valid() const {\n        return is_initialized_by_at_least_one_interpreter_\n               && !detail::has_seen_non_main_interpreter();\n    }\n\n    // Get the unique key for this storage instance in the interpreter's state dict.\n    // The return type should not be `py::str` because PyObject is interpreter-dependent.\n    std::string get_storage_key() const {\n        // The instance is expected to be global static, so using its address as unique identifier.\n        // The typical usage is like:\n        //\n        //   PYBIND11_CONSTINIT static gil_safe_call_once_and_store<T> storage;\n        //\n        return PYBIND11_CALL_ONCE_STORAGE_KEY_PREFIX\n               + std::to_string(reinterpret_cast<std::uintptr_t>(this));\n    }\n\n    // Get or create per-storage capsule in the current interpreter's state dict.\n    // The storage is interpreter-dependent and will not be shared across interpreters.\n    storage_type *get_or_create_storage_in_state_dict() {\n        return detail::atomic_get_or_create_in_state_dict<storage_type>(get_storage_key().c_str())\n            .first;\n    }\n\n    // No storage needed when subinterpreter support is enabled.\n    // The actual storage is stored in the per-interpreter state dict via\n    // `get_or_create_storage_in_state_dict()`.\n\n    // Fast local cache to avoid repeated lookups when there are no multiple interpreters.\n    // This is only valid if there is a single interpreter. Otherwise, it is not used.\n    // WARNING: We cannot use thread local cache similar to `internals_pp_manager::internals_p_tls`\n    //          because the thread local storage cannot be explicitly invalidated when interpreters\n    //          are destroyed (unlike `internals_pp_manager` which has explicit hooks for that).\n    T *last_storage_ptr_ = nullptr;\n    // This flag is true if the value has been initialized by any interpreter (may not be the\n    // current one).\n    detail::atomic_bool is_initialized_by_at_least_one_interpreter_{false};\n};\n#endif\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/gil_simple.h",
    "content": "// Copyright (c) 2016-2025 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"detail/common.h\"\n\n#include <cassert>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nclass gil_scoped_acquire_simple {\n    PyGILState_STATE state;\n\npublic:\n    gil_scoped_acquire_simple() : state{PyGILState_Ensure()} {}\n    gil_scoped_acquire_simple(const gil_scoped_acquire_simple &) = delete;\n    gil_scoped_acquire_simple &operator=(const gil_scoped_acquire_simple &) = delete;\n    ~gil_scoped_acquire_simple() { PyGILState_Release(state); }\n};\n\nclass gil_scoped_release_simple {\n    PyThreadState *state;\n\npublic:\n    // PRECONDITION: The GIL must be held when this constructor is called.\n    gil_scoped_release_simple() {\n        assert(PyGILState_Check());\n        state = PyEval_SaveThread();\n    }\n    gil_scoped_release_simple(const gil_scoped_release_simple &) = delete;\n    gil_scoped_release_simple &operator=(const gil_scoped_release_simple &) = delete;\n    ~gil_scoped_release_simple() { PyEval_RestoreThread(state); }\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/iostream.h",
    "content": "/*\n    pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python\n\n    Copyright (c) 2017 Henry F. Schreiner\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n\n    WARNING: The implementation in this file is NOT thread safe. Multiple\n    threads writing to a redirected ostream concurrently cause data races\n    and potentially buffer overflows. Therefore it is currently a requirement\n    that all (possibly) concurrent redirected ostream writes are protected by\n    a mutex.\n    #HelpAppreciated: Work on iostream.h thread safety.\n    For more background see the discussions under\n    https://github.com/pybind/pybind11/pull/2982 and\n    https://github.com/pybind/pybind11/pull/2995.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\n#include <algorithm>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <memory>\n#include <ostream>\n#include <streambuf>\n#include <string>\n#include <utility>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Buffer that writes to Python instead of C++\nclass pythonbuf : public std::streambuf {\nprivate:\n    using traits_type = std::streambuf::traits_type;\n\n    const size_t buf_size;\n    std::unique_ptr<char[]> d_buffer;\n    object pywrite;\n    object pyflush;\n\n    int overflow(int c) override {\n        if (!traits_type::eq_int_type(c, traits_type::eof())) {\n            *pptr() = traits_type::to_char_type(c);\n            pbump(1);\n        }\n        return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();\n    }\n\n    // Computes how many bytes at the end of the buffer are part of an\n    // incomplete sequence of UTF-8 bytes.\n    // Precondition: pbase() < pptr()\n    size_t utf8_remainder() const {\n        const auto rbase = std::reverse_iterator<char *>(pbase());\n        const auto rpptr = std::reverse_iterator<char *>(pptr());\n        auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };\n        auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };\n        auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };\n        auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };\n        // If the last character is ASCII, there are no incomplete code points\n        if (is_ascii(*rpptr)) {\n            return 0;\n        }\n        // Otherwise, work back from the end of the buffer and find the first\n        // UTF-8 leading byte\n        const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;\n        const auto leading = std::find_if(rpptr, rpend, is_leading);\n        if (leading == rbase) {\n            return 0;\n        }\n        const auto dist = static_cast<size_t>(leading - rpptr);\n        size_t remainder = 0;\n\n        if (dist == 0) {\n            remainder = 1; // 1-byte code point is impossible\n        } else if (dist == 1) {\n            remainder = is_leading_2b(*leading) ? 0 : dist + 1;\n        } else if (dist == 2) {\n            remainder = is_leading_3b(*leading) ? 0 : dist + 1;\n        }\n        // else if (dist >= 3), at least 4 bytes before encountering an UTF-8\n        // leading byte, either no remainder or invalid UTF-8.\n        // Invalid UTF-8 will cause an exception later when converting\n        // to a Python string, so that's not handled here.\n        return remainder;\n    }\n\n    // This function must be non-virtual to be called in a destructor.\n    int _sync() {\n        if (pbase() != pptr()) { // If buffer is not empty\n            gil_scoped_acquire tmp;\n            // This subtraction cannot be negative, so dropping the sign.\n            auto size = static_cast<size_t>(pptr() - pbase());\n            size_t remainder = utf8_remainder();\n\n            if (size > remainder) {\n                str line(pbase(), size - remainder);\n                pywrite(std::move(line));\n                pyflush();\n            }\n\n            // Copy the remainder at the end of the buffer to the beginning:\n            if (remainder > 0) {\n                std::memmove(pbase(), pptr() - remainder, remainder);\n            }\n            setp(pbase(), epptr());\n            pbump(static_cast<int>(remainder));\n        }\n        return 0;\n    }\n\n    int sync() override { return _sync(); }\n\npublic:\n    explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)\n        : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr(\"write\")),\n          pyflush(pyostream.attr(\"flush\")) {\n        setp(d_buffer.get(), d_buffer.get() + buf_size - 1);\n    }\n\n    pythonbuf(pythonbuf &&) = default;\n\n    /// Sync before destroy\n    ~pythonbuf() override { _sync(); }\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n/** \\rst\n    This a move-only guard that redirects output.\n\n    .. code-block:: cpp\n\n        #include <pybind11/iostream.h>\n\n        ...\n\n        {\n            py::scoped_ostream_redirect output;\n            std::cout << \"Hello, World!\"; // Python stdout\n        } // <-- return std::cout to normal\n\n    You can explicitly pass the c++ stream and the python object,\n    for example to guard stderr instead.\n\n    .. code-block:: cpp\n\n        {\n            py::scoped_ostream_redirect output{\n                std::cerr, py::module::import(\"sys\").attr(\"stderr\")};\n            std::cout << \"Hello, World!\";\n        }\n \\endrst */\nclass scoped_ostream_redirect {\nprotected:\n    std::streambuf *old;\n    std::ostream &costream;\n    detail::pythonbuf buffer;\n\npublic:\n    explicit scoped_ostream_redirect(std::ostream &costream = std::cout,\n                                     const object &pyostream\n                                     = module_::import(\"sys\").attr(\"stdout\"))\n        : costream(costream), buffer(pyostream) {\n        old = costream.rdbuf(&buffer);\n    }\n\n    ~scoped_ostream_redirect() { costream.rdbuf(old); }\n\n    scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;\n    scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;\n    scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;\n    scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;\n};\n\n/** \\rst\n    Like `scoped_ostream_redirect`, but redirects cerr by default. This class\n    is provided primary to make ``py::call_guard`` easier to make.\n\n    .. code-block:: cpp\n\n     m.def(\"noisy_func\", &noisy_func,\n           py::call_guard<scoped_ostream_redirect,\n                          scoped_estream_redirect>());\n\n\\endrst */\nclass scoped_estream_redirect : public scoped_ostream_redirect {\npublic:\n    explicit scoped_estream_redirect(std::ostream &costream = std::cerr,\n                                     const object &pyostream\n                                     = module_::import(\"sys\").attr(\"stderr\"))\n        : scoped_ostream_redirect(costream, pyostream) {}\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Class to redirect output as a context manager. C++ backend.\nclass OstreamRedirect {\n    bool do_stdout_;\n    bool do_stderr_;\n    std::unique_ptr<scoped_ostream_redirect> redirect_stdout;\n    std::unique_ptr<scoped_estream_redirect> redirect_stderr;\n\npublic:\n    explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)\n        : do_stdout_(do_stdout), do_stderr_(do_stderr) {}\n\n    void enter() {\n        if (do_stdout_) {\n            redirect_stdout.reset(new scoped_ostream_redirect());\n        }\n        if (do_stderr_) {\n            redirect_stderr.reset(new scoped_estream_redirect());\n        }\n    }\n\n    void exit() {\n        redirect_stdout.reset();\n        redirect_stderr.reset();\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n/** \\rst\n    This is a helper function to add a C++ redirect context manager to Python\n    instead of using a C++ guard. To use it, add the following to your binding code:\n\n    .. code-block:: cpp\n\n        #include <pybind11/iostream.h>\n\n        ...\n\n        py::add_ostream_redirect(m, \"ostream_redirect\");\n\n    You now have a Python context manager that redirects your output:\n\n    .. code-block:: python\n\n        with m.ostream_redirect():\n            m.print_to_cout_function()\n\n    This manager can optionally be told which streams to operate on:\n\n    .. code-block:: python\n\n        with m.ostream_redirect(stdout=true, stderr=true):\n            m.noisy_function_with_error_printing()\n\n \\endrst */\ninline class_<detail::OstreamRedirect>\nadd_ostream_redirect(module_ m, const std::string &name = \"ostream_redirect\") {\n    return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())\n        .def(init<bool, bool>(), arg(\"stdout\") = true, arg(\"stderr\") = true)\n        .def(\"__enter__\", &detail::OstreamRedirect::enter)\n        .def(\"__exit__\", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/native_enum.h",
    "content": "// Copyright (c) 2022-2025 The pybind Community.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/native_enum_data.h\"\n#include \"detail/type_caster_base.h\"\n#include \"cast.h\"\n\n#include <cassert>\n#include <limits>\n#include <type_traits>\n#include <typeindex>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\n/// Conversions between Python's native (stdlib) enum types and C++ enums.\ntemplate <typename EnumType>\nclass native_enum : public detail::native_enum_data {\npublic:\n    using Underlying = typename std::underlying_type<EnumType>::type;\n\n    native_enum(handle parent_scope,\n                const char *name,\n                const char *native_type_name,\n                const char *class_doc = \"\")\n        : detail::native_enum_data(\n              parent_scope, name, native_type_name, class_doc, make_record()) {\n        if (detail::get_local_type_info(typeid(EnumType)) != nullptr\n            || detail::get_global_type_info(typeid(EnumType)) != nullptr) {\n            pybind11_fail(\n                \"pybind11::native_enum<...>(\\\"\" + enum_name_encoded\n                + \"\\\") is already registered as a `pybind11::enum_` or `pybind11::class_`!\");\n        }\n        if (detail::global_internals_native_enum_type_map_contains(enum_type_index)) {\n            pybind11_fail(\"pybind11::native_enum<...>(\\\"\" + enum_name_encoded\n                          + \"\\\") is already registered!\");\n        }\n        arm_finalize_check();\n    }\n\n    /// Export enumeration entries into the parent scope\n    native_enum &export_values() {\n        assert(!export_values_flag); // Catch redundant calls.\n        export_values_flag = true;\n        return *this;\n    }\n\n    /// Add an enumeration entry\n    native_enum &value(char const *name, EnumType value, const char *doc = nullptr) {\n        // Disarm for the case that the native_enum_data dtor runs during exception unwinding.\n        disarm_finalize_check(\"value after finalize\");\n        members.append(make_tuple(name, static_cast<Underlying>(value)));\n        if (doc) {\n            member_docs.append(make_tuple(name, doc));\n        }\n        arm_finalize_check(); // There was no exception.\n        return *this;\n    }\n\n    native_enum(const native_enum &) = delete;\n    native_enum &operator=(const native_enum &) = delete;\n\nprivate:\n    static detail::native_enum_record make_record() {\n        detail::native_enum_record ret;\n        ret.cpptype = &typeid(EnumType);\n        ret.size_bytes = sizeof(EnumType);\n        ret.is_signed = std::is_signed<Underlying>::value;\n        return ret;\n    }\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/numpy.h",
    "content": "/*\n    pybind11/numpy.h: Basic NumPy support, vectorize() wrapper\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n#include \"detail/common.h\"\n#include \"complex.h\"\n#include \"gil_safe_call_once.h\"\n#include \"pytypes.h\"\n\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <functional>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <typeindex>\n#include <utility>\n#include <vector>\n\n#ifdef PYBIND11_HAS_SPAN\n#    include <span>\n#endif\n\n#if defined(PYBIND11_NUMPY_1_ONLY)\n#    error \"PYBIND11_NUMPY_1_ONLY is no longer supported (see PR #5595).\"\n#endif\n\n/* This will be true on all flat address space platforms and allows us to reduce the\n   whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size\n   and dimension types (e.g. shape, strides, indexing), instead of inflicting this\n   upon the library user.\n   Note that NumPy 2 now uses ssize_t for `npy_intp` to simplify this. */\nstatic_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), \"ssize_t != Py_intptr_t\");\nstatic_assert(std::is_signed<Py_intptr_t>::value, \"Py_intptr_t must be signed\");\n// We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nclass dtype; // Forward declaration\nclass array; // Forward declaration\n\ntemplate <typename>\nstruct numpy_scalar; // Forward declaration\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <>\nstruct handle_type_name<dtype> {\n    static constexpr auto name = const_name(\"numpy.dtype\");\n};\n\ntemplate <>\nstruct handle_type_name<array> {\n    static constexpr auto name = const_name(\"numpy.ndarray\");\n};\n\ntemplate <typename type, typename SFINAE = void>\nstruct npy_format_descriptor;\n\n/* NumPy 1 proxy (always includes legacy fields) */\nstruct PyArrayDescr1_Proxy {\n    PyObject_HEAD\n    PyObject *typeobj;\n    char kind;\n    char type;\n    char byteorder;\n    char flags;\n    int type_num;\n    int elsize;\n    int alignment;\n    char *subarray;\n    PyObject *fields;\n    PyObject *names;\n};\n\nstruct PyArrayDescr_Proxy {\n    PyObject_HEAD\n    PyObject *typeobj;\n    char kind;\n    char type;\n    char byteorder;\n    char _former_flags;\n    int type_num;\n    /* Additional fields are NumPy version specific. */\n};\n\n/* NumPy 2 proxy, including legacy fields */\nstruct PyArrayDescr2_Proxy {\n    PyObject_HEAD\n    PyObject *typeobj;\n    char kind;\n    char type;\n    char byteorder;\n    char _former_flags;\n    int type_num;\n    std::uint64_t flags;\n    ssize_t elsize;\n    ssize_t alignment;\n    PyObject *metadata;\n    Py_hash_t hash;\n    void *reserved_null[2];\n    /* The following fields only exist if 0 <= type_num < 2056 */\n    char *subarray;\n    PyObject *fields;\n    PyObject *names;\n};\n\nstruct PyArray_Proxy {\n    PyObject_HEAD\n    char *data;\n    int nd;\n    ssize_t *dimensions;\n    ssize_t *strides;\n    PyObject *base;\n    PyObject *descr;\n    int flags;\n};\n\nstruct PyVoidScalarObject_Proxy {\n    PyObject_VAR_HEAD char *obval;\n    PyArrayDescr_Proxy *descr;\n    int flags;\n    PyObject *base;\n};\n\nstruct numpy_type_info {\n    PyObject *dtype_ptr;\n    std::string format_str;\n};\n\nstruct numpy_internals {\n    std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;\n\n    numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {\n        auto it = registered_dtypes.find(std::type_index(tinfo));\n        if (it != registered_dtypes.end()) {\n            return &(it->second);\n        }\n        if (throw_if_missing) {\n            pybind11_fail(std::string(\"NumPy type info missing for \") + tinfo.name());\n        }\n        return nullptr;\n    }\n\n    template <typename T>\n    numpy_type_info *get_type_info(bool throw_if_missing = true) {\n        return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);\n    }\n};\n\nPYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) {\n    ptr = &get_or_create_shared_data<numpy_internals>(\"_numpy_internals\");\n}\n\ninline numpy_internals &get_numpy_internals() {\n    static numpy_internals *ptr = nullptr;\n    if (!ptr) {\n        load_numpy_internals(ptr);\n    }\n    return *ptr;\n}\n\nPYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name) {\n    module_ numpy = module_::import(\"numpy\");\n    str version_string = numpy.attr(\"__version__\");\n    module_ numpy_lib = module_::import(\"numpy.lib\");\n    object numpy_version = numpy_lib.attr(\"NumpyVersion\")(version_string);\n    int major_version = numpy_version.attr(\"major\").cast<int>();\n\n    /* `numpy.core` was renamed to `numpy._core` in NumPy 2.0 as it officially\n        became a private module. */\n    std::string numpy_core_path = major_version >= 2 ? \"numpy._core\" : \"numpy.core\";\n    return module_::import((numpy_core_path + \".\" + submodule_name).c_str());\n}\n\ntemplate <typename T>\nstruct same_size {\n    template <typename U>\n    using as = bool_constant<sizeof(T) == sizeof(U)>;\n};\n\ntemplate <typename Concrete>\nconstexpr int platform_lookup() {\n    return -1;\n}\n\n// Lookup a type according to its size, and return a value corresponding to the NumPy typenum.\ntemplate <typename Concrete, typename T, typename... Ts, typename... Ints>\nconstexpr int platform_lookup(int I, Ints... Is) {\n    return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);\n}\n\nstruct npy_api {\n    // If you change this code, please review `normalized_dtype_num` below.\n    enum constants {\n        NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,\n        NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,\n        NPY_ARRAY_OWNDATA_ = 0x0004,\n        NPY_ARRAY_FORCECAST_ = 0x0010,\n        NPY_ARRAY_ENSUREARRAY_ = 0x0040,\n        NPY_ARRAY_ALIGNED_ = 0x0100,\n        NPY_ARRAY_WRITEABLE_ = 0x0400,\n        NPY_BOOL_ = 0,\n        NPY_BYTE_,\n        NPY_UBYTE_,\n        NPY_SHORT_,\n        NPY_USHORT_,\n        NPY_INT_,\n        NPY_UINT_,\n        NPY_LONG_,\n        NPY_ULONG_,\n        NPY_LONGLONG_,\n        NPY_ULONGLONG_,\n        NPY_FLOAT_,\n        NPY_DOUBLE_,\n        NPY_LONGDOUBLE_,\n        NPY_CFLOAT_,\n        NPY_CDOUBLE_,\n        NPY_CLONGDOUBLE_,\n        NPY_OBJECT_ = 17,\n        NPY_STRING_,\n        NPY_UNICODE_,\n        NPY_VOID_,\n        // Platform-dependent normalization\n        NPY_INT8_ = NPY_BYTE_,\n        NPY_UINT8_ = NPY_UBYTE_,\n        NPY_INT16_ = NPY_SHORT_,\n        NPY_UINT16_ = NPY_USHORT_,\n        // `npy_common.h` defines the integer aliases. In order, it checks:\n        // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR\n        // and assigns the alias to the first matching size, so we should check in this order.\n        NPY_INT32_\n        = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),\n        NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(\n            NPY_ULONG_, NPY_UINT_, NPY_USHORT_),\n        NPY_INT64_\n        = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),\n        NPY_UINT64_\n        = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(\n            NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),\n        NPY_FLOAT32_ = platform_lookup<float, double, float, long double>(\n            NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),\n        NPY_FLOAT64_ = platform_lookup<double, double, float, long double>(\n            NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),\n        NPY_COMPLEX64_\n        = platform_lookup<std::complex<float>,\n                          std::complex<double>,\n                          std::complex<float>,\n                          std::complex<long double>>(NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),\n        NPY_COMPLEX128_\n        = platform_lookup<std::complex<double>,\n                          std::complex<double>,\n                          std::complex<float>,\n                          std::complex<long double>>(NPY_DOUBLE_, NPY_FLOAT_, NPY_LONGDOUBLE_),\n        NPY_CHAR_ = std::is_signed<char>::value ? NPY_BYTE_ : NPY_UBYTE_,\n    };\n\n    unsigned int PyArray_RUNTIME_VERSION_;\n\n    struct PyArray_Dims {\n        Py_intptr_t *ptr;\n        int len;\n    };\n\n    static npy_api &get() {\n        PYBIND11_CONSTINIT static gil_safe_call_once_and_store<npy_api> storage;\n        return storage.call_once_and_store_result(lookup).get_stored();\n    }\n\n    bool PyArray_Check_(PyObject *obj) const {\n        return PyObject_TypeCheck(obj, PyArray_Type_) != 0;\n    }\n    bool PyArrayDescr_Check_(PyObject *obj) const {\n        return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;\n    }\n\n    unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();\n    PyObject *(*PyArray_DescrFromType_)(int);\n    PyObject *(*PyArray_TypeObjectFromType_)(int);\n    PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,\n                                       PyObject *,\n                                       int,\n                                       Py_intptr_t const *,\n                                       Py_intptr_t const *,\n                                       void *,\n                                       int,\n                                       PyObject *);\n    // Unused. Not removed because that affects ABI of the class.\n    PyObject *(*PyArray_DescrNewFromType_)(int);\n    int (*PyArray_CopyInto_)(PyObject *, PyObject *);\n    PyObject *(*PyArray_NewCopy_)(PyObject *, int);\n    PyTypeObject *PyArray_Type_;\n    PyTypeObject *PyVoidArrType_Type_;\n    PyTypeObject *PyArrayDescr_Type_;\n    PyObject *(*PyArray_DescrFromScalar_)(PyObject *);\n    PyObject *(*PyArray_Scalar_)(void *, PyObject *, PyObject *);\n    void (*PyArray_ScalarAsCtype_)(PyObject *, void *);\n    PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);\n    int (*PyArray_DescrConverter_)(PyObject *, PyObject **);\n    bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);\n    PyObject *(*PyArray_Squeeze_)(PyObject *);\n    // Unused. Not removed because that affects ABI of the class.\n    int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);\n    PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);\n    PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);\n    PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);\n\nprivate:\n    enum functions {\n        API_PyArray_GetNDArrayCFeatureVersion = 211,\n        API_PyArray_Type = 2,\n        API_PyArrayDescr_Type = 3,\n        API_PyVoidArrType_Type = 39,\n        API_PyArray_DescrFromType = 45,\n        API_PyArray_TypeObjectFromType = 46,\n        API_PyArray_DescrFromScalar = 57,\n        API_PyArray_Scalar = 60,\n        API_PyArray_ScalarAsCtype = 62,\n        API_PyArray_FromAny = 69,\n        API_PyArray_Resize = 80,\n        // CopyInto was slot 82 and 50 was effectively an alias. NumPy 2 removed 82.\n        API_PyArray_CopyInto = 50,\n        API_PyArray_NewCopy = 85,\n        API_PyArray_NewFromDescr = 94,\n        API_PyArray_DescrNewFromType = 96,\n        API_PyArray_Newshape = 135,\n        API_PyArray_Squeeze = 136,\n        API_PyArray_View = 137,\n        API_PyArray_DescrConverter = 174,\n        API_PyArray_EquivTypes = 182,\n        API_PyArray_SetBaseObject = 282\n    };\n\n    static npy_api lookup() {\n        module_ m = detail::import_numpy_core_submodule(\"multiarray\");\n        auto c = m.attr(\"_ARRAY_API\");\n        void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr);\n        if (api_ptr == nullptr) {\n            raise_from(PyExc_SystemError, \"FAILURE obtaining numpy _ARRAY_API pointer.\");\n            throw error_already_set();\n        }\n        npy_api api;\n#define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];\n        DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);\n        api.PyArray_RUNTIME_VERSION_ = api.PyArray_GetNDArrayCFeatureVersion_();\n        if (api.PyArray_RUNTIME_VERSION_ < 0x7) {\n            pybind11_fail(\"pybind11 numpy support requires numpy >= 1.7.0\");\n        }\n        DECL_NPY_API(PyArray_Type);\n        DECL_NPY_API(PyVoidArrType_Type);\n        DECL_NPY_API(PyArrayDescr_Type);\n        DECL_NPY_API(PyArray_DescrFromType);\n        DECL_NPY_API(PyArray_TypeObjectFromType);\n        DECL_NPY_API(PyArray_DescrFromScalar);\n        DECL_NPY_API(PyArray_Scalar);\n        DECL_NPY_API(PyArray_ScalarAsCtype);\n        DECL_NPY_API(PyArray_FromAny);\n        DECL_NPY_API(PyArray_Resize);\n        DECL_NPY_API(PyArray_CopyInto);\n        DECL_NPY_API(PyArray_NewCopy);\n        DECL_NPY_API(PyArray_NewFromDescr);\n        DECL_NPY_API(PyArray_DescrNewFromType);\n        DECL_NPY_API(PyArray_Newshape);\n        DECL_NPY_API(PyArray_Squeeze);\n        DECL_NPY_API(PyArray_View);\n        DECL_NPY_API(PyArray_DescrConverter);\n        DECL_NPY_API(PyArray_EquivTypes);\n        DECL_NPY_API(PyArray_SetBaseObject);\n\n#undef DECL_NPY_API\n        return api;\n    }\n};\n\ntemplate <typename T>\nstruct is_complex : std::false_type {};\ntemplate <typename T>\nstruct is_complex<std::complex<T>> : std::true_type {};\n\ntemplate <typename T, typename = void>\nstruct npy_format_descriptor_name;\n\ntemplate <typename T>\nstruct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {\n    static constexpr auto name = const_name<std::is_same<T, bool>::value>(\n        const_name(\"numpy.bool\"),\n        const_name<std::is_signed<T>::value>(\"numpy.int\", \"numpy.uint\")\n            + const_name<sizeof(T) * 8>());\n};\n\ntemplate <typename T>\nstruct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {\n    static constexpr auto name = const_name < std::is_same<T, float>::value\n                                 || std::is_same<T, const float>::value\n                                 || std::is_same<T, double>::value\n                                 || std::is_same<T, const double>::value\n                                        > (const_name(\"numpy.float\") + const_name<sizeof(T) * 8>(),\n                                           const_name(\"numpy.longdouble\"));\n};\n\ntemplate <typename T>\nstruct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {\n    static constexpr auto name = const_name < std::is_same<typename T::value_type, float>::value\n                                 || std::is_same<typename T::value_type, const float>::value\n                                 || std::is_same<typename T::value_type, double>::value\n                                 || std::is_same<typename T::value_type, const double>::value\n                                        > (const_name(\"numpy.complex\")\n                                               + const_name<sizeof(typename T::value_type) * 16>(),\n                                           const_name(\"numpy.clongdouble\"));\n};\n\ntemplate <typename T>\nstruct numpy_scalar_info {};\n\n#define PYBIND11_NUMPY_SCALAR_IMPL(ctype_, typenum_)                                              \\\n    template <>                                                                                   \\\n    struct numpy_scalar_info<ctype_> {                                                            \\\n        static constexpr auto name = npy_format_descriptor_name<ctype_>::name;                    \\\n        static constexpr int typenum = npy_api::typenum_##_;                                      \\\n    }\n\n// boolean type\nPYBIND11_NUMPY_SCALAR_IMPL(bool, NPY_BOOL);\n\n// character types\nPYBIND11_NUMPY_SCALAR_IMPL(char, NPY_CHAR);\nPYBIND11_NUMPY_SCALAR_IMPL(signed char, NPY_BYTE);\nPYBIND11_NUMPY_SCALAR_IMPL(unsigned char, NPY_UBYTE);\n\n// signed integer types\nPYBIND11_NUMPY_SCALAR_IMPL(std::int16_t, NPY_INT16);\nPYBIND11_NUMPY_SCALAR_IMPL(std::int32_t, NPY_INT32);\nPYBIND11_NUMPY_SCALAR_IMPL(std::int64_t, NPY_INT64);\n\n// unsigned integer types\nPYBIND11_NUMPY_SCALAR_IMPL(std::uint16_t, NPY_UINT16);\nPYBIND11_NUMPY_SCALAR_IMPL(std::uint32_t, NPY_UINT32);\nPYBIND11_NUMPY_SCALAR_IMPL(std::uint64_t, NPY_UINT64);\n\n// floating point types\nPYBIND11_NUMPY_SCALAR_IMPL(float, NPY_FLOAT);\nPYBIND11_NUMPY_SCALAR_IMPL(double, NPY_DOUBLE);\nPYBIND11_NUMPY_SCALAR_IMPL(long double, NPY_LONGDOUBLE);\n\n// complex types\nPYBIND11_NUMPY_SCALAR_IMPL(std::complex<float>, NPY_CFLOAT);\nPYBIND11_NUMPY_SCALAR_IMPL(std::complex<double>, NPY_CDOUBLE);\nPYBIND11_NUMPY_SCALAR_IMPL(std::complex<long double>, NPY_CLONGDOUBLE);\n\n#undef PYBIND11_NUMPY_SCALAR_IMPL\n\n// This table normalizes typenums by mapping NPY_INT_, NPY_LONG, ... to NPY_INT32_, NPY_INT64, ...\n// This is needed to correctly handle situations where multiple typenums map to the same type,\n// e.g. NPY_LONG_ may be equivalent to NPY_INT_ or NPY_LONGLONG_ despite having a different\n// typenum. The normalized typenum should always match the values used in npy_format_descriptor.\n// If you change this code, please review `enum constants` above.\nstatic constexpr int normalized_dtype_num[npy_api::NPY_VOID_ + 1] = {\n    // NPY_BOOL_ =>\n    npy_api::NPY_BOOL_,\n    // NPY_BYTE_ =>\n    npy_api::NPY_BYTE_,\n    // NPY_UBYTE_ =>\n    npy_api::NPY_UBYTE_,\n    // NPY_SHORT_ =>\n    npy_api::NPY_INT16_,\n    // NPY_USHORT_ =>\n    npy_api::NPY_UINT16_,\n    // NPY_INT_ =>\n    sizeof(int) == sizeof(std::int16_t)   ? npy_api::NPY_INT16_\n    : sizeof(int) == sizeof(std::int32_t) ? npy_api::NPY_INT32_\n    : sizeof(int) == sizeof(std::int64_t) ? npy_api::NPY_INT64_\n                                          : npy_api::NPY_INT_,\n    // NPY_UINT_ =>\n    sizeof(unsigned int) == sizeof(std::uint16_t)   ? npy_api::NPY_UINT16_\n    : sizeof(unsigned int) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_\n    : sizeof(unsigned int) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_\n                                                    : npy_api::NPY_UINT_,\n    // NPY_LONG_ =>\n    sizeof(long) == sizeof(std::int16_t)   ? npy_api::NPY_INT16_\n    : sizeof(long) == sizeof(std::int32_t) ? npy_api::NPY_INT32_\n    : sizeof(long) == sizeof(std::int64_t) ? npy_api::NPY_INT64_\n                                           : npy_api::NPY_LONG_,\n    // NPY_ULONG_ =>\n    sizeof(unsigned long) == sizeof(std::uint16_t)   ? npy_api::NPY_UINT16_\n    : sizeof(unsigned long) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_\n    : sizeof(unsigned long) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_\n                                                     : npy_api::NPY_ULONG_,\n    // NPY_LONGLONG_ =>\n    sizeof(long long) == sizeof(std::int16_t)   ? npy_api::NPY_INT16_\n    : sizeof(long long) == sizeof(std::int32_t) ? npy_api::NPY_INT32_\n    : sizeof(long long) == sizeof(std::int64_t) ? npy_api::NPY_INT64_\n                                                : npy_api::NPY_LONGLONG_,\n    // NPY_ULONGLONG_ =>\n    sizeof(unsigned long long) == sizeof(std::uint16_t)   ? npy_api::NPY_UINT16_\n    : sizeof(unsigned long long) == sizeof(std::uint32_t) ? npy_api::NPY_UINT32_\n    : sizeof(unsigned long long) == sizeof(std::uint64_t) ? npy_api::NPY_UINT64_\n                                                          : npy_api::NPY_ULONGLONG_,\n    // NPY_FLOAT_ =>\n    npy_api::NPY_FLOAT_,\n    // NPY_DOUBLE_ =>\n    npy_api::NPY_DOUBLE_,\n    // NPY_LONGDOUBLE_ =>\n    npy_api::NPY_LONGDOUBLE_,\n    // NPY_CFLOAT_ =>\n    npy_api::NPY_CFLOAT_,\n    // NPY_CDOUBLE_ =>\n    npy_api::NPY_CDOUBLE_,\n    // NPY_CLONGDOUBLE_ =>\n    npy_api::NPY_CLONGDOUBLE_,\n    // NPY_OBJECT_ =>\n    npy_api::NPY_OBJECT_,\n    // NPY_STRING_ =>\n    npy_api::NPY_STRING_,\n    // NPY_UNICODE_ =>\n    npy_api::NPY_UNICODE_,\n    // NPY_VOID_ =>\n    npy_api::NPY_VOID_,\n};\n\ninline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }\n\ninline const PyArray_Proxy *array_proxy(const void *ptr) {\n    return reinterpret_cast<const PyArray_Proxy *>(ptr);\n}\n\ninline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) {\n    return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);\n}\n\ninline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {\n    return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);\n}\n\ninline const PyArrayDescr1_Proxy *array_descriptor1_proxy(const PyObject *ptr) {\n    return reinterpret_cast<const PyArrayDescr1_Proxy *>(ptr);\n}\n\ninline const PyArrayDescr2_Proxy *array_descriptor2_proxy(const PyObject *ptr) {\n    return reinterpret_cast<const PyArrayDescr2_Proxy *>(ptr);\n}\n\ninline bool check_flags(const void *ptr, int flag) {\n    return (flag == (array_proxy(ptr)->flags & flag));\n}\n\ntemplate <typename T>\nstruct is_std_array : std::false_type {};\ntemplate <typename T, size_t N>\nstruct is_std_array<std::array<T, N>> : std::true_type {};\n\ntemplate <typename T>\nstruct array_info_scalar {\n    using type = T;\n    static constexpr bool is_array = false;\n    static constexpr bool is_empty = false;\n    static constexpr auto extents = const_name(\"\");\n    static void append_extents(list & /* shape */) {}\n};\n// Computes underlying type and a comma-separated list of extents for array\n// types (any mix of std::array and built-in arrays). An array of char is\n// treated as scalar because it gets special handling.\ntemplate <typename T>\nstruct array_info : array_info_scalar<T> {};\ntemplate <typename T, size_t N>\nstruct array_info<std::array<T, N>> {\n    using type = typename array_info<T>::type;\n    static constexpr bool is_array = true;\n    static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;\n    static constexpr size_t extent = N;\n\n    // appends the extents to shape\n    static void append_extents(list &shape) {\n        shape.append(N);\n        array_info<T>::append_extents(shape);\n    }\n\n    static constexpr auto extents = const_name<array_info<T>::is_array>(\n        ::pybind11::detail::concat(const_name<N>(), array_info<T>::extents), const_name<N>());\n};\n// For numpy we have special handling for arrays of characters, so we don't include\n// the size in the array extents.\ntemplate <size_t N>\nstruct array_info<char[N]> : array_info_scalar<char[N]> {};\ntemplate <size_t N>\nstruct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};\ntemplate <typename T, size_t N>\nstruct array_info<T[N]> : array_info<std::array<T, N>> {};\ntemplate <typename T>\nusing remove_all_extents_t = typename array_info<T>::type;\n\ntemplate <typename T>\nusing is_pod_struct\n    = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory\n                                         // we need a standard layout type\n#if defined(__GLIBCXX__)                                                                          \\\n    && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623              \\\n        || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)\n             // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after\n             // 5) don't implement is_trivially_copyable, so approximate it\n             std::is_trivially_destructible<T>,\n             satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,\n#else\n             std::is_trivially_copyable<T>,\n#endif\n             satisfies_none_of<T,\n                               std::is_reference,\n                               std::is_array,\n                               is_std_array,\n                               std::is_arithmetic,\n                               is_complex,\n                               std::is_enum>>;\n\n// Replacement for std::is_pod (deprecated in C++20)\ntemplate <typename T>\nusing is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;\n\ntemplate <ssize_t Dim = 0, typename Strides>\nssize_t byte_offset_unsafe(const Strides &) {\n    return 0;\n}\ntemplate <ssize_t Dim = 0, typename Strides, typename... Ix>\nssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {\n    return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);\n}\n\n/**\n * Proxy class providing unsafe, unchecked const access to array data.  This is constructed through\n * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`\n * will be -1 for dimensions determined at runtime.\n */\ntemplate <typename T, ssize_t Dims>\nclass unchecked_reference {\nprotected:\n    static constexpr bool Dynamic = Dims < 0;\n    const unsigned char *data_;\n    // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to\n    // make large performance gains on big, nested loops, but requires compile-time dimensions\n    conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;\n    const ssize_t dims_;\n\n    friend class pybind11::array;\n    // Constructor for compile-time dimensions:\n    template <bool Dyn = Dynamic>\n    unchecked_reference(const void *data,\n                        const ssize_t *shape,\n                        const ssize_t *strides,\n                        enable_if_t<!Dyn, ssize_t>)\n        : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {\n        for (size_t i = 0; i < (size_t) dims_; i++) {\n            shape_[i] = shape[i];\n            strides_[i] = strides[i];\n        }\n    }\n    // Constructor for runtime dimensions:\n    template <bool Dyn = Dynamic>\n    unchecked_reference(const void *data,\n                        const ssize_t *shape,\n                        const ssize_t *strides,\n                        enable_if_t<Dyn, ssize_t> dims)\n        : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},\n          dims_{dims} {}\n\npublic:\n    /**\n     * Unchecked const reference access to data at the given indices.  For a compile-time known\n     * number of dimensions, this requires the correct number of arguments; for run-time\n     * dimensionality, this is not checked (and so is up to the caller to use safely).\n     */\n    template <typename... Ix>\n    const T &operator()(Ix... index) const {\n        static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,\n                      \"Invalid number of indices for unchecked array reference\");\n        return *reinterpret_cast<const T *>(data_\n                                            + byte_offset_unsafe(strides_, ssize_t(index)...));\n    }\n    /**\n     * Unchecked const reference access to data; this operator only participates if the reference\n     * is to a 1-dimensional array.  When present, this is exactly equivalent to `obj(index)`.\n     */\n    template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>\n    const T &operator[](ssize_t index) const {\n        return operator()(index);\n    }\n\n    /// Pointer access to the data at the given indices.\n    template <typename... Ix>\n    const T *data(Ix... ix) const {\n        return &operator()(ssize_t(ix)...);\n    }\n\n    /// Returns the item size, i.e. sizeof(T)\n    constexpr static ssize_t itemsize() { return sizeof(T); }\n\n    /// Returns the shape (i.e. size) of dimension `dim`\n    ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }\n\n    /// Returns the number of dimensions of the array\n    ssize_t ndim() const { return dims_; }\n\n    /// Returns the total number of elements in the referenced array, i.e. the product of the\n    /// shapes\n    template <bool Dyn = Dynamic>\n    enable_if_t<!Dyn, ssize_t> size() const {\n        return std::accumulate(\n            shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());\n    }\n    template <bool Dyn = Dynamic>\n    enable_if_t<Dyn, ssize_t> size() const {\n        return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());\n    }\n\n    /// Returns the total number of bytes used by the referenced data.  Note that the actual span\n    /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a\n    /// slice).\n    ssize_t nbytes() const { return size() * itemsize(); }\n};\n\ntemplate <typename T, ssize_t Dims>\nclass unchecked_mutable_reference : public unchecked_reference<T, Dims> {\n    friend class pybind11::array;\n    using ConstBase = unchecked_reference<T, Dims>;\n    using ConstBase::ConstBase;\n    using ConstBase::Dynamic;\n\npublic:\n    // Bring in const-qualified versions from base class\n    using ConstBase::operator();\n    using ConstBase::operator[];\n\n    /// Mutable, unchecked access to data at the given indices.\n    template <typename... Ix>\n    T &operator()(Ix... index) {\n        static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,\n                      \"Invalid number of indices for unchecked array reference\");\n        return const_cast<T &>(ConstBase::operator()(index...));\n    }\n    /**\n     * Mutable, unchecked access data at the given index; this operator only participates if the\n     * reference is to a 1-dimensional array (or has runtime dimensions).  When present, this is\n     * exactly equivalent to `obj(index)`.\n     */\n    template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>\n    T &operator[](ssize_t index) {\n        return operator()(index);\n    }\n\n    /// Mutable pointer access to the data at the given indices.\n    template <typename... Ix>\n    T *mutable_data(Ix... ix) {\n        return &operator()(ssize_t(ix)...);\n    }\n};\n\ntemplate <typename T, ssize_t Dim>\nstruct type_caster<unchecked_reference<T, Dim>> {\n    static_assert(Dim == 0 && Dim > 0 /* always fail */,\n                  \"unchecked array proxy object is not castable\");\n};\ntemplate <typename T, ssize_t Dim>\nstruct type_caster<unchecked_mutable_reference<T, Dim>>\n    : type_caster<unchecked_reference<T, Dim>> {};\n\ntemplate <typename T>\nstruct type_caster<numpy_scalar<T>> {\n    using value_type = T;\n    using type_info = numpy_scalar_info<T>;\n\n    PYBIND11_TYPE_CASTER(numpy_scalar<T>, type_info::name);\n\n    static handle &target_type() {\n        static handle tp = npy_api::get().PyArray_TypeObjectFromType_(type_info::typenum);\n        return tp;\n    }\n\n    static handle &target_dtype() {\n        static handle tp = npy_api::get().PyArray_DescrFromType_(type_info::typenum);\n        return tp;\n    }\n\n    bool load(handle src, bool) {\n        if (isinstance(src, target_type())) {\n            npy_api::get().PyArray_ScalarAsCtype_(src.ptr(), &value.value);\n            return true;\n        }\n        return false;\n    }\n\n    static handle cast(numpy_scalar<T> src, return_value_policy, handle) {\n        return npy_api::get().PyArray_Scalar_(&src.value, target_dtype().ptr(), nullptr);\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename T>\nstruct numpy_scalar {\n    using value_type = T;\n\n    value_type value;\n\n    numpy_scalar() = default;\n    explicit numpy_scalar(value_type value) : value(value) {}\n\n    explicit operator value_type() const { return value; }\n    numpy_scalar &operator=(value_type value) {\n        this->value = value;\n        return *this;\n    }\n\n    friend bool operator==(const numpy_scalar &a, const numpy_scalar &b) {\n        return a.value == b.value;\n    }\n\n    friend bool operator!=(const numpy_scalar &a, const numpy_scalar &b) { return !(a == b); }\n};\n\ntemplate <typename T>\nnumpy_scalar<T> make_scalar(T value) {\n    return numpy_scalar<T>(value);\n}\n\nclass dtype : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_)\n\n    explicit dtype(const buffer_info &info) {\n        dtype descr(_dtype_from_pep3118()(pybind11::str(info.format)));\n        // If info.itemsize == 0, use the value calculated from the format string\n        m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())\n                    .release()\n                    .ptr();\n    }\n\n    explicit dtype(const pybind11::str &format) : dtype(from_args(format)) {}\n\n    explicit dtype(const std::string &format) : dtype(pybind11::str(format)) {}\n\n    explicit dtype(const char *format) : dtype(pybind11::str(format)) {}\n\n    dtype(list names, list formats, list offsets, ssize_t itemsize) {\n        dict args;\n        args[\"names\"] = std::move(names);\n        args[\"formats\"] = std::move(formats);\n        args[\"offsets\"] = std::move(offsets);\n        args[\"itemsize\"] = pybind11::int_(itemsize);\n        m_ptr = from_args(args).release().ptr();\n    }\n\n    /// Return dtype for the given typenum (one of the NPY_TYPES).\n    /// https://numpy.org/devdocs/reference/c-api/array.html#c.PyArray_DescrFromType\n    explicit dtype(int typenum)\n        : object(detail::npy_api::get().PyArray_DescrFromType_(typenum), stolen_t{}) {\n        if (m_ptr == nullptr) {\n            throw error_already_set();\n        }\n    }\n\n    /// This is essentially the same as calling numpy.dtype(args) in Python.\n    static dtype from_args(const object &args) {\n        PyObject *ptr = nullptr;\n        if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {\n            throw error_already_set();\n        }\n        return reinterpret_steal<dtype>(ptr);\n    }\n\n    /// Return dtype associated with a C++ type.\n    template <typename T>\n    static dtype of() {\n        return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();\n    }\n\n    /// Return the type number associated with a C++ type.\n    /// This is the constexpr equivalent of `dtype::of<T>().num()`.\n    template <typename T>\n    static constexpr int num_of() {\n        return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::value;\n    }\n\n    /// Size of the data type in bytes.\n    ssize_t itemsize() const {\n        if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {\n            return detail::array_descriptor1_proxy(m_ptr)->elsize;\n        }\n        return detail::array_descriptor2_proxy(m_ptr)->elsize;\n    }\n\n    /// Returns true for structured data types.\n    bool has_fields() const {\n        if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {\n            return detail::array_descriptor1_proxy(m_ptr)->names != nullptr;\n        }\n        const auto *proxy = detail::array_descriptor2_proxy(m_ptr);\n        if (proxy->type_num < 0 || proxy->type_num >= 2056) {\n            return false;\n        }\n        return proxy->names != nullptr;\n    }\n\n    /// Single-character code for dtype's kind.\n    /// For example, floating point types are 'f' and integral types are 'i'.\n    char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }\n\n    /// Single-character for dtype's type.\n    /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'.\n    char char_() const {\n        // Note: The signature, `dtype::char_` follows the naming of NumPy's\n        // public Python API (i.e., ``dtype.char``), rather than its internal\n        // C API (``PyArray_Descr::type``).\n        return detail::array_descriptor_proxy(m_ptr)->type;\n    }\n\n    /// Type number of dtype. Note that different values may be returned for equivalent types,\n    /// e.g. even though ``long`` may be equivalent to ``int`` or ``long long``, they still have\n    /// different type numbers. Consider using `normalized_num` to avoid this.\n    int num() const {\n        // Note: The signature, `dtype::num` follows the naming of NumPy's public\n        // Python API (i.e., ``dtype.num``), rather than its internal\n        // C API (``PyArray_Descr::type_num``).\n        return detail::array_descriptor_proxy(m_ptr)->type_num;\n    }\n\n    /// Type number of dtype, normalized to match the return value of `num_of` for equivalent\n    /// types. This function can be used to write switch statements that correctly handle\n    /// equivalent types with different type numbers.\n    int normalized_num() const {\n        int value = num();\n        if (value >= 0 && value <= detail::npy_api::NPY_VOID_) {\n            return detail::normalized_dtype_num[value];\n        }\n        return value;\n    }\n\n    /// Single character for byteorder\n    char byteorder() const { return detail::array_descriptor_proxy(m_ptr)->byteorder; }\n\n    /// Alignment of the data type\n    ssize_t alignment() const {\n        if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {\n            return detail::array_descriptor1_proxy(m_ptr)->alignment;\n        }\n        return detail::array_descriptor2_proxy(m_ptr)->alignment;\n    }\n\n    /// Flags for the array descriptor\n    std::uint64_t flags() const {\n        if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {\n            return (unsigned char) detail::array_descriptor1_proxy(m_ptr)->flags;\n        }\n        return detail::array_descriptor2_proxy(m_ptr)->flags;\n    }\n\nprivate:\n    static object &_dtype_from_pep3118() {\n        PYBIND11_CONSTINIT static gil_safe_call_once_and_store<object> storage;\n        return storage\n            .call_once_and_store_result([]() {\n                return detail::import_numpy_core_submodule(\"_internal\")\n                    .attr(\"_dtype_from_pep3118\");\n            })\n            .get_stored();\n    }\n\n    dtype strip_padding(ssize_t itemsize) {\n        // Recursively strip all void fields with empty names that are generated for\n        // padding fields (as of NumPy v1.11).\n        if (!has_fields()) {\n            return *this;\n        }\n\n        struct field_descr {\n            pybind11::str name;\n            object format;\n            pybind11::int_ offset;\n            field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset)\n                : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {};\n        };\n        auto field_dict = attr(\"fields\").cast<dict>();\n        std::vector<field_descr> field_descriptors;\n        field_descriptors.reserve(field_dict.size());\n\n        for (auto field : field_dict.attr(\"items\")()) {\n            auto spec = field.cast<tuple>();\n            auto name = spec[0].cast<pybind11::str>();\n            auto spec_fo = spec[1].cast<tuple>();\n            auto format = spec_fo[0].cast<dtype>();\n            auto offset = spec_fo[1].cast<pybind11::int_>();\n            if ((len(name) == 0u) && format.kind() == 'V') {\n                continue;\n            }\n            field_descriptors.emplace_back(\n                std::move(name), format.strip_padding(format.itemsize()), std::move(offset));\n        }\n\n        std::sort(field_descriptors.begin(),\n                  field_descriptors.end(),\n                  [](const field_descr &a, const field_descr &b) {\n                      return a.offset.cast<int>() < b.offset.cast<int>();\n                  });\n\n        list names, formats, offsets;\n        for (auto &descr : field_descriptors) {\n            names.append(std::move(descr.name));\n            formats.append(std::move(descr.format));\n            offsets.append(std::move(descr.offset));\n        }\n        return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);\n    }\n};\n\nclass array : public buffer {\npublic:\n    PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)\n\n    enum {\n        c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,\n        f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,\n        forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_\n    };\n\n    array() : array(0, static_cast<const double *>(nullptr)) {}\n\n    using ShapeContainer = detail::any_container<ssize_t>;\n    using StridesContainer = detail::any_container<ssize_t>;\n\n    // Constructs an array taking shape/strides from arbitrary container types\n    array(const pybind11::dtype &dt,\n          ShapeContainer shape,\n          StridesContainer strides,\n          const void *ptr = nullptr,\n          handle base = handle()) {\n\n        if (strides->empty()) {\n            *strides = detail::c_strides(*shape, dt.itemsize());\n        }\n\n        auto ndim = shape->size();\n        if (ndim != strides->size()) {\n            pybind11_fail(\"NumPy: shape ndim doesn't match strides ndim\");\n        }\n        auto descr = dt;\n\n        int flags = 0;\n        if (base && ptr) {\n            if (isinstance<array>(base)) {\n                /* Copy flags from base (except ownership bit) */\n                flags = reinterpret_borrow<array>(base).flags()\n                        & ~detail::npy_api::NPY_ARRAY_OWNDATA_;\n            } else {\n                /* Writable by default, easy to downgrade later on if needed */\n                flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;\n            }\n        }\n\n        auto &api = detail::npy_api::get();\n        auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(\n            api.PyArray_Type_,\n            descr.release().ptr(),\n            (int) ndim,\n            // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)\n            reinterpret_cast<Py_intptr_t *>(shape->data()),\n            reinterpret_cast<Py_intptr_t *>(strides->data()),\n            const_cast<void *>(ptr),\n            flags,\n            nullptr));\n        if (!tmp) {\n            throw error_already_set();\n        }\n        if (ptr) {\n            if (base) {\n                api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());\n            } else {\n                tmp = reinterpret_steal<object>(\n                    api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));\n            }\n        }\n        m_ptr = tmp.release().ptr();\n    }\n\n    array(const pybind11::dtype &dt,\n          ShapeContainer shape,\n          const void *ptr = nullptr,\n          handle base = handle())\n        : array(dt, std::move(shape), {}, ptr, base) {}\n\n    template <typename T,\n              typename\n              = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>\n    array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())\n        : array(dt, {{count}}, ptr, base) {}\n\n    template <typename T>\n    array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())\n        : array(pybind11::dtype::of<T>(),\n                std::move(shape),\n                std::move(strides),\n                reinterpret_cast<const void *>(ptr),\n                base) {}\n\n    template <typename T>\n    array(ShapeContainer shape, const T *ptr, handle base = handle())\n        : array(std::move(shape), {}, ptr, base) {}\n\n    template <typename T>\n    explicit array(ssize_t count, const T *ptr, handle base = handle())\n        : array({count}, {}, ptr, base) {}\n\n    explicit array(const buffer_info &info, handle base = handle())\n        : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {}\n\n    /// Array descriptor (dtype)\n    pybind11::dtype dtype() const {\n        return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);\n    }\n\n    /// Total number of elements\n    ssize_t size() const {\n        return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());\n    }\n\n    /// Byte size of a single element\n    ssize_t itemsize() const { return dtype().itemsize(); }\n\n    /// Total number of bytes\n    ssize_t nbytes() const { return size() * itemsize(); }\n\n    /// Number of dimensions\n    ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }\n\n    /// Base object\n    object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }\n\n    /// Dimensions of the array\n    const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }\n\n#ifdef PYBIND11_HAS_SPAN\n    /// Dimensions of the array as a span\n    std::span<const ssize_t, std::dynamic_extent> shape_span() const {\n        return std::span(shape(), static_cast<std::size_t>(ndim()));\n    }\n#endif\n\n    /// Dimension along a given axis\n    ssize_t shape(ssize_t dim) const {\n        if (dim >= ndim()) {\n            fail_dim_check(dim, \"invalid axis\");\n        }\n        return shape()[dim];\n    }\n\n    /// Strides of the array\n    const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }\n\n#ifdef PYBIND11_HAS_SPAN\n    /// Strides of the array as a span\n    std::span<const ssize_t, std::dynamic_extent> strides_span() const {\n        return std::span(strides(), static_cast<std::size_t>(ndim()));\n    }\n#endif\n\n    /// Stride along a given axis\n    ssize_t strides(ssize_t dim) const {\n        if (dim >= ndim()) {\n            fail_dim_check(dim, \"invalid axis\");\n        }\n        return strides()[dim];\n    }\n\n    /// Return the NumPy array flags\n    int flags() const { return detail::array_proxy(m_ptr)->flags; }\n\n    /// If set, the array is writeable (otherwise the buffer is read-only)\n    bool writeable() const {\n        return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);\n    }\n\n    /// If set, the array owns the data (will be freed when the array is deleted)\n    bool owndata() const {\n        return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);\n    }\n\n    /// Pointer to the contained data. If index is not provided, points to the\n    /// beginning of the buffer. May throw if the index would lead to out of bounds access.\n    template <typename... Ix>\n    const void *data(Ix... index) const {\n        return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));\n    }\n\n    /// Mutable pointer to the contained data. If index is not provided, points to the\n    /// beginning of the buffer. May throw if the index would lead to out of bounds access.\n    /// May throw if the array is not writeable.\n    template <typename... Ix>\n    void *mutable_data(Ix... index) {\n        check_writeable();\n        return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));\n    }\n\n    /// Byte offset from beginning of the array to a given index (full or partial).\n    /// May throw if the index would lead to out of bounds access.\n    template <typename... Ix>\n    ssize_t offset_at(Ix... index) const {\n        if ((ssize_t) sizeof...(index) > ndim()) {\n            fail_dim_check(sizeof...(index), \"too many indices for an array\");\n        }\n        return byte_offset(ssize_t(index)...);\n    }\n\n    ssize_t offset_at() const { return 0; }\n\n    /// Item count from beginning of the array to a given index (full or partial).\n    /// May throw if the index would lead to out of bounds access.\n    template <typename... Ix>\n    ssize_t index_at(Ix... index) const {\n        return offset_at(index...) / itemsize();\n    }\n\n    /**\n     * Returns a proxy object that provides access to the array's data without bounds or\n     * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with\n     * care: the array must not be destroyed or reshaped for the duration of the returned object,\n     * and the caller must take care not to access invalid dimensions or dimension indices.\n     */\n    template <typename T, ssize_t Dims = -1>\n    detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {\n        if (Dims >= 0 && ndim() != Dims) {\n            throw std::domain_error(\"array has incorrect number of dimensions: \"\n                                    + std::to_string(ndim()) + \"; expected \"\n                                    + std::to_string(Dims));\n        }\n        return detail::unchecked_mutable_reference<T, Dims>(\n            mutable_data(), shape(), strides(), ndim());\n    }\n\n    /**\n     * Returns a proxy object that provides const access to the array's data without bounds or\n     * dimensionality checking.  Unlike `mutable_unchecked()`, this does not require that the\n     * underlying array have the `writable` flag.  Use with care: the array must not be destroyed\n     * or reshaped for the duration of the returned object, and the caller must take care not to\n     * access invalid dimensions or dimension indices.\n     */\n    template <typename T, ssize_t Dims = -1>\n    detail::unchecked_reference<T, Dims> unchecked() const & {\n        if (Dims >= 0 && ndim() != Dims) {\n            throw std::domain_error(\"array has incorrect number of dimensions: \"\n                                    + std::to_string(ndim()) + \"; expected \"\n                                    + std::to_string(Dims));\n        }\n        return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());\n    }\n\n    /// Return a new view with all of the dimensions of length 1 removed\n    array squeeze() {\n        auto &api = detail::npy_api::get();\n        return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));\n    }\n\n    /// Resize array to given shape\n    /// If refcheck is true and more that one reference exist to this array\n    /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change\n    void resize(ShapeContainer new_shape, bool refcheck = true) {\n        detail::npy_api::PyArray_Dims d\n            = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)\n               reinterpret_cast<Py_intptr_t *>(new_shape->data()),\n               int(new_shape->size())};\n        // try to resize, set ordering param to -1 cause it's not used anyway\n        auto new_array = reinterpret_steal<object>(\n            detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));\n        if (!new_array) {\n            throw error_already_set();\n        }\n        if (isinstance<array>(new_array)) {\n            *this = std::move(new_array);\n        }\n    }\n\n    /// Optional `order` parameter omitted, to be added as needed.\n    array reshape(ShapeContainer new_shape) {\n        detail::npy_api::PyArray_Dims d\n            = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};\n        auto new_array\n            = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));\n        if (!new_array) {\n            throw error_already_set();\n        }\n        return new_array;\n    }\n\n    /// Create a view of an array in a different data type.\n    /// This function may fundamentally reinterpret the data in the array.\n    /// It is the responsibility of the caller to ensure that this is safe.\n    /// Only supports the `dtype` argument, the `type` argument is omitted,\n    /// to be added as needed.\n    array view(const std::string &dtype) {\n        auto &api = detail::npy_api::get();\n        auto new_view = reinterpret_steal<array>(api.PyArray_View_(\n            m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr));\n        if (!new_view) {\n            throw error_already_set();\n        }\n        return new_view;\n    }\n\n    /// Ensure that the argument is a NumPy array\n    /// In case of an error, nullptr is returned and the Python error is cleared.\n    static array ensure(handle h, int ExtraFlags = 0) {\n        auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));\n        if (!result) {\n            PyErr_Clear();\n        }\n        return result;\n    }\n\nprotected:\n    template <typename, typename>\n    friend struct detail::npy_format_descriptor;\n\n    void fail_dim_check(ssize_t dim, const std::string &msg) const {\n        throw index_error(msg + \": \" + std::to_string(dim) + \" (ndim = \" + std::to_string(ndim())\n                          + ')');\n    }\n\n    template <typename... Ix>\n    ssize_t byte_offset(Ix... index) const {\n        check_dimensions(index...);\n        return detail::byte_offset_unsafe(strides(), ssize_t(index)...);\n    }\n\n    void check_writeable() const {\n        if (!writeable()) {\n            throw std::domain_error(\"array is not writeable\");\n        }\n    }\n\n    template <typename... Ix>\n    void check_dimensions(Ix... index) const {\n        check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);\n    }\n\n    void check_dimensions_impl(ssize_t, const ssize_t *) const {}\n\n    template <typename... Ix>\n    void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {\n        if (i >= *shape) {\n            throw index_error(std::string(\"index \") + std::to_string(i)\n                              + \" is out of bounds for axis \" + std::to_string(axis)\n                              + \" with size \" + std::to_string(*shape));\n        }\n        check_dimensions_impl(axis + 1, shape + 1, index...);\n    }\n\n    /// Create array from any object -- always returns a new reference\n    static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {\n        if (ptr == nullptr) {\n            set_error(PyExc_ValueError, \"cannot create a pybind11::array from a nullptr\");\n            return nullptr;\n        }\n        return detail::npy_api::get().PyArray_FromAny_(\n            ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);\n    }\n};\n\ntemplate <typename T, int ExtraFlags = array::forcecast>\nclass array_t : public array {\nprivate:\n    struct private_ctor {};\n    // Delegating constructor needed when both moving and accessing in the same constructor\n    array_t(private_ctor,\n            ShapeContainer &&shape,\n            StridesContainer &&strides,\n            const T *ptr,\n            handle base)\n        : array(std::move(shape), std::move(strides), ptr, base) {}\n\npublic:\n    static_assert(!detail::array_info<T>::is_array, \"Array types cannot be used with array_t\");\n\n    using value_type = T;\n\n    array_t() : array(0, static_cast<const T *>(nullptr)) {}\n    array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {}\n    array_t(handle h, stolen_t) : array(h, stolen_t{}) {}\n\n    PYBIND11_DEPRECATED(\"Use array_t<T>::ensure() instead\")\n    array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {\n        if (!m_ptr) {\n            PyErr_Clear();\n        }\n        if (!is_borrowed) {\n            Py_XDECREF(h.ptr());\n        }\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {\n        if (!m_ptr) {\n            throw error_already_set();\n        }\n    }\n\n    explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}\n\n    array_t(ShapeContainer shape,\n            StridesContainer strides,\n            const T *ptr = nullptr,\n            handle base = handle())\n        : array(std::move(shape), std::move(strides), ptr, base) {}\n\n    explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())\n        : array_t(private_ctor{},\n                  std::move(shape),\n                  (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())\n                                              : detail::c_strides(*shape, itemsize()),\n                  ptr,\n                  base) {}\n\n    explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())\n        : array({count}, {}, ptr, base) {}\n\n    constexpr ssize_t itemsize() const { return sizeof(T); }\n\n    template <typename... Ix>\n    ssize_t index_at(Ix... index) const {\n        return offset_at(index...) / itemsize();\n    }\n\n    template <typename... Ix>\n    const T *data(Ix... index) const {\n        return static_cast<const T *>(array::data(index...));\n    }\n\n    template <typename... Ix>\n    T *mutable_data(Ix... index) {\n        return static_cast<T *>(array::mutable_data(index...));\n    }\n\n    // Reference to element at a given index\n    template <typename... Ix>\n    const T &at(Ix... index) const {\n        if ((ssize_t) sizeof...(index) != ndim()) {\n            fail_dim_check(sizeof...(index), \"index dimension mismatch\");\n        }\n        return *(static_cast<const T *>(array::data())\n                 + byte_offset(ssize_t(index)...) / itemsize());\n    }\n\n    // Mutable reference to element at a given index\n    template <typename... Ix>\n    T &mutable_at(Ix... index) {\n        if ((ssize_t) sizeof...(index) != ndim()) {\n            fail_dim_check(sizeof...(index), \"index dimension mismatch\");\n        }\n        return *(static_cast<T *>(array::mutable_data())\n                 + byte_offset(ssize_t(index)...) / itemsize());\n    }\n\n    /**\n     * Returns a proxy object that provides access to the array's data without bounds or\n     * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with\n     * care: the array must not be destroyed or reshaped for the duration of the returned object,\n     * and the caller must take care not to access invalid dimensions or dimension indices.\n     */\n    template <ssize_t Dims = -1>\n    detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {\n        return array::mutable_unchecked<T, Dims>();\n    }\n\n    /**\n     * Returns a proxy object that provides const access to the array's data without bounds or\n     * dimensionality checking.  Unlike `mutable_unchecked()`, this does not require that the\n     * underlying array have the `writable` flag.  Use with care: the array must not be destroyed\n     * or reshaped for the duration of the returned object, and the caller must take care not to\n     * access invalid dimensions or dimension indices.\n     */\n    template <ssize_t Dims = -1>\n    detail::unchecked_reference<T, Dims> unchecked() const & {\n        return array::unchecked<T, Dims>();\n    }\n\n    /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert\n    /// it).  In case of an error, nullptr is returned and the Python error is cleared.\n    static array_t ensure(handle h) {\n        auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));\n        if (!result) {\n            PyErr_Clear();\n        }\n        return result;\n    }\n\n    static bool check_(handle h) {\n        const auto &api = detail::npy_api::get();\n        return api.PyArray_Check_(h.ptr())\n               && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,\n                                          dtype::of<T>().ptr())\n               && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));\n    }\n\nprotected:\n    /// Create array from any object -- always returns a new reference\n    static PyObject *raw_array_t(PyObject *ptr) {\n        if (ptr == nullptr) {\n            set_error(PyExc_ValueError, \"cannot create a pybind11::array_t from a nullptr\");\n            return nullptr;\n        }\n        return detail::npy_api::get().PyArray_FromAny_(ptr,\n                                                       dtype::of<T>().release().ptr(),\n                                                       0,\n                                                       0,\n                                                       detail::npy_api::NPY_ARRAY_ENSUREARRAY_\n                                                           | ExtraFlags,\n                                                       nullptr);\n    }\n};\n\ntemplate <typename T>\nstruct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {\n    static std::string format() {\n        return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();\n    }\n};\n\ntemplate <size_t N>\nstruct format_descriptor<char[N]> {\n    static std::string format() { return std::to_string(N) + 's'; }\n};\ntemplate <size_t N>\nstruct format_descriptor<std::array<char, N>> {\n    static std::string format() { return std::to_string(N) + 's'; }\n};\n\ntemplate <typename T>\nstruct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {\n    static std::string format() {\n        return format_descriptor<\n            typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();\n    }\n};\n\ntemplate <typename T>\nstruct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {\n    static std::string format() {\n        using namespace detail;\n        static constexpr auto extents = const_name(\"(\") + array_info<T>::extents + const_name(\")\");\n        return extents.text + format_descriptor<remove_all_extents_t<T>>::format();\n    }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <typename T, int ExtraFlags>\nstruct pyobject_caster<array_t<T, ExtraFlags>> {\n    using type = array_t<T, ExtraFlags>;\n\n    bool load(handle src, bool convert) {\n        if (!convert && !type::check_(src)) {\n            return false;\n        }\n        value = type::ensure(src);\n        return static_cast<bool>(value);\n    }\n\n    static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {\n        return src.inc_ref();\n    }\n    PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);\n};\n\ntemplate <typename T>\nstruct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {\n    static bool compare(const buffer_info &b) {\n        return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());\n    }\n};\n\ntemplate <typename T>\nstruct npy_format_descriptor<\n    T,\n    enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>\n    : npy_format_descriptor_name<T> {\nprivate:\n    // NB: the order here must match the one in common.h\n    constexpr static const int values[15] = {npy_api::NPY_BOOL_,\n                                             npy_api::NPY_BYTE_,\n                                             npy_api::NPY_UBYTE_,\n                                             npy_api::NPY_INT16_,\n                                             npy_api::NPY_UINT16_,\n                                             npy_api::NPY_INT32_,\n                                             npy_api::NPY_UINT32_,\n                                             npy_api::NPY_INT64_,\n                                             npy_api::NPY_UINT64_,\n                                             npy_api::NPY_FLOAT_,\n                                             npy_api::NPY_DOUBLE_,\n                                             npy_api::NPY_LONGDOUBLE_,\n                                             npy_api::NPY_CFLOAT_,\n                                             npy_api::NPY_CDOUBLE_,\n                                             npy_api::NPY_CLONGDOUBLE_};\n\npublic:\n    static constexpr int value = values[detail::is_fmt_numeric<T>::index];\n\n    static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }\n};\n\ntemplate <typename T>\nstruct npy_format_descriptor<\n    T,\n    enable_if_t<is_same_ignoring_cvref<T, PyObject *>::value\n                || ((std::is_same<T, handle>::value || std::is_same<T, object>::value)\n                    && sizeof(T) == sizeof(PyObject *))>> {\n    static constexpr auto name = const_name(\"numpy.object_\");\n\n    static constexpr int value = npy_api::NPY_OBJECT_;\n\n    static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }\n};\n\n#define PYBIND11_DECL_CHAR_FMT                                                                    \\\n    static constexpr auto name = const_name(\"S\") + const_name<N>();                               \\\n    static pybind11::dtype dtype() {                                                              \\\n        return pybind11::dtype(std::string(\"S\") + std::to_string(N));                             \\\n    }\ntemplate <size_t N>\nstruct npy_format_descriptor<char[N]> {\n    PYBIND11_DECL_CHAR_FMT\n};\ntemplate <size_t N>\nstruct npy_format_descriptor<std::array<char, N>> {\n    PYBIND11_DECL_CHAR_FMT\n};\n#undef PYBIND11_DECL_CHAR_FMT\n\ntemplate <typename T>\nstruct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {\nprivate:\n    using base_descr = npy_format_descriptor<typename array_info<T>::type>;\n\npublic:\n    static_assert(!array_info<T>::is_empty, \"Zero-sized arrays are not supported\");\n\n    static constexpr auto name\n        = const_name(\"(\") + array_info<T>::extents + const_name(\")\") + base_descr::name;\n    static pybind11::dtype dtype() {\n        list shape;\n        array_info<T>::append_extents(shape);\n        return pybind11::dtype::from_args(\n            pybind11::make_tuple(base_descr::dtype(), std::move(shape)));\n    }\n};\n\ntemplate <typename T>\nstruct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {\nprivate:\n    using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;\n\npublic:\n    static constexpr auto name = base_descr::name;\n    static pybind11::dtype dtype() { return base_descr::dtype(); }\n};\n\nstruct field_descriptor {\n    const char *name;\n    ssize_t offset;\n    ssize_t size;\n    std::string format;\n    dtype descr;\n};\n\nPYBIND11_NOINLINE void register_structured_dtype(any_container<field_descriptor> fields,\n                                                 const std::type_info &tinfo,\n                                                 ssize_t itemsize,\n                                                 bool (*direct_converter)(PyObject *, void *&)) {\n\n    auto &numpy_internals = get_numpy_internals();\n    if (numpy_internals.get_type_info(tinfo, false)) {\n        pybind11_fail(\"NumPy: dtype is already registered\");\n    }\n\n    // Use ordered fields because order matters as of NumPy 1.14:\n    // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays\n    std::vector<field_descriptor> ordered_fields(std::move(fields));\n    std::sort(\n        ordered_fields.begin(),\n        ordered_fields.end(),\n        [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });\n\n    list names, formats, offsets;\n    for (auto &field : ordered_fields) {\n        if (!field.descr) {\n            pybind11_fail(std::string(\"NumPy: unsupported field dtype: `\") + field.name + \"` @ \"\n                          + tinfo.name());\n        }\n        names.append(pybind11::str(field.name));\n        formats.append(field.descr);\n        offsets.append(pybind11::int_(field.offset));\n    }\n    auto *dtype_ptr\n        = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)\n              .release()\n              .ptr();\n\n    // There is an existing bug in NumPy (as of v1.11): trailing bytes are\n    // not encoded explicitly into the format string. This will supposedly\n    // get fixed in v1.12; for further details, see these:\n    // - https://github.com/numpy/numpy/issues/7797\n    // - https://github.com/numpy/numpy/pull/7798\n    // Because of this, we won't use numpy's logic to generate buffer format\n    // strings and will just do it ourselves.\n    ssize_t offset = 0;\n    std::ostringstream oss;\n    // mark the structure as unaligned with '^', because numpy and C++ don't\n    // always agree about alignment (particularly for complex), and we're\n    // explicitly listing all our padding. This depends on none of the fields\n    // overriding the endianness. Putting the ^ in front of individual fields\n    // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049\n    oss << \"^T{\";\n    for (auto &field : ordered_fields) {\n        if (field.offset > offset) {\n            oss << (field.offset - offset) << 'x';\n        }\n        oss << field.format << ':' << field.name << ':';\n        offset = field.offset + field.size;\n    }\n    if (itemsize > offset) {\n        oss << (itemsize - offset) << 'x';\n    }\n    oss << '}';\n    auto format_str = oss.str();\n\n    // Smoke test: verify that NumPy properly parses our buffer format string\n    auto &api = npy_api::get();\n    auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));\n    if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {\n        pybind11_fail(\"NumPy: invalid buffer descriptor!\");\n    }\n\n    auto tindex = std::type_index(tinfo);\n    numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)};\n    with_internals([tindex, &direct_converter](internals &internals) {\n        internals.direct_conversions[tindex].push_back(direct_converter);\n    });\n}\n\ntemplate <typename T, typename SFINAE>\nstruct npy_format_descriptor {\n    static_assert(is_pod_struct<T>::value,\n                  \"Attempt to use a non-POD or unimplemented POD type as a numpy dtype\");\n\n    static constexpr auto name = make_caster<T>::name;\n\n    static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }\n\n    static std::string format() {\n        static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;\n        return format_str;\n    }\n\n    static void register_dtype(any_container<field_descriptor> fields) {\n        register_structured_dtype(std::move(fields),\n                                  typeid(typename std::remove_cv<T>::type),\n                                  sizeof(T),\n                                  &direct_converter);\n    }\n\nprivate:\n    static PyObject *dtype_ptr() {\n        static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;\n        return ptr;\n    }\n\n    static bool direct_converter(PyObject *obj, void *&value) {\n        auto &api = npy_api::get();\n        if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {\n            return false;\n        }\n        if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {\n            if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {\n                value = ((PyVoidScalarObject_Proxy *) obj)->obval;\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\n#ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)\n#    define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)\n#    define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)\n#else\n\n#    define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name)                                          \\\n        ::pybind11::detail::field_descriptor {                                                    \\\n            Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)),                  \\\n                ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(),       \\\n                ::pybind11::detail::npy_format_descriptor<                                        \\\n                    decltype(std::declval<T>().Field)>::dtype()                                   \\\n        }\n\n// Extract name, offset and format descriptor for a struct field\n#    define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)\n\n// The main idea of this macro is borrowed from https://github.com/swansontec/map-macro\n// (C) William Swanson, Paul Fultz\n#    define PYBIND11_EVAL0(...) __VA_ARGS__\n#    define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))\n#    define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))\n#    define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))\n#    define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))\n#    define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))\n#    define PYBIND11_MAP_END(...)\n#    define PYBIND11_MAP_OUT\n#    define PYBIND11_MAP_COMMA ,\n#    define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END\n#    define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT\n#    define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)\n#    define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)\n#    if defined(_MSC_VER)                                                                         \\\n        && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround\n#        define PYBIND11_MAP_LIST_NEXT1(test, next)                                               \\\n            PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))\n#    else\n#        define PYBIND11_MAP_LIST_NEXT1(test, next)                                               \\\n            PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)\n#    endif\n#    define PYBIND11_MAP_LIST_NEXT(test, next)                                                    \\\n        PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)\n#    define PYBIND11_MAP_LIST0(f, t, x, peek, ...)                                                \\\n        f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)\n#    define PYBIND11_MAP_LIST1(f, t, x, peek, ...)                                                \\\n        f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)\n// PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...\n#    define PYBIND11_MAP_LIST(f, t, ...)                                                          \\\n        PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))\n\n#    define PYBIND11_NUMPY_DTYPE(Type, ...)                                                       \\\n        ::pybind11::detail::npy_format_descriptor<Type>::register_dtype(                          \\\n            ::std::vector<::pybind11::detail::field_descriptor>{                                  \\\n                PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})\n\n#    if defined(_MSC_VER) && !defined(__clang__)\n#        define PYBIND11_MAP2_LIST_NEXT1(test, next)                                              \\\n            PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))\n#    else\n#        define PYBIND11_MAP2_LIST_NEXT1(test, next)                                              \\\n            PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)\n#    endif\n#    define PYBIND11_MAP2_LIST_NEXT(test, next)                                                   \\\n        PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)\n#    define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...)                                          \\\n        f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)\n#    define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...)                                          \\\n        f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)\n// PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...\n#    define PYBIND11_MAP2_LIST(f, t, ...)                                                         \\\n        PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))\n\n#    define PYBIND11_NUMPY_DTYPE_EX(Type, ...)                                                    \\\n        ::pybind11::detail::npy_format_descriptor<Type>::register_dtype(                          \\\n            ::std::vector<::pybind11::detail::field_descriptor>{                                  \\\n                PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})\n\n#endif // __CLION_IDE__\n\nclass common_iterator {\npublic:\n    using container_type = std::vector<ssize_t>;\n    using value_type = container_type::value_type;\n    using size_type = container_type::size_type;\n\n    common_iterator() = default;\n\n    common_iterator(void *ptr, const container_type &strides, const container_type &shape)\n        : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {\n        m_strides.back() = static_cast<value_type>(strides.back());\n        for (size_type i = m_strides.size() - 1; i != 0; --i) {\n            size_type j = i - 1;\n            auto s = static_cast<value_type>(shape[i]);\n            m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;\n        }\n    }\n\n    void increment(size_type dim) { p_ptr += m_strides[dim]; }\n\n    void *data() const { return p_ptr; }\n\nprivate:\n    char *p_ptr{nullptr};\n    container_type m_strides;\n};\n\ntemplate <size_t N>\nclass multi_array_iterator {\npublic:\n    using container_type = std::vector<ssize_t>;\n\n    multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)\n        : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {\n\n        // Manual copy to avoid conversion warning if using std::copy\n        for (size_t i = 0; i < shape.size(); ++i) {\n            m_shape[i] = shape[i];\n        }\n\n        container_type strides(shape.size());\n        for (size_t i = 0; i < N; ++i) {\n            init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);\n        }\n    }\n\n    multi_array_iterator &operator++() {\n        for (size_t j = m_index.size(); j != 0; --j) {\n            size_t i = j - 1;\n            if (++m_index[i] != m_shape[i]) {\n                increment_common_iterator(i);\n                break;\n            }\n            m_index[i] = 0;\n        }\n        return *this;\n    }\n\n    template <size_t K, class T = void>\n    T *data() const {\n        return reinterpret_cast<T *>(m_common_iterator[K].data());\n    }\n\nprivate:\n    using common_iter = common_iterator;\n\n    void init_common_iterator(const buffer_info &buffer,\n                              const container_type &shape,\n                              common_iter &iterator,\n                              container_type &strides) {\n        auto buffer_shape_iter = buffer.shape.rbegin();\n        auto buffer_strides_iter = buffer.strides.rbegin();\n        auto shape_iter = shape.rbegin();\n        auto strides_iter = strides.rbegin();\n\n        while (buffer_shape_iter != buffer.shape.rend()) {\n            if (*shape_iter == *buffer_shape_iter) {\n                *strides_iter = *buffer_strides_iter;\n            } else {\n                *strides_iter = 0;\n            }\n\n            ++buffer_shape_iter;\n            ++buffer_strides_iter;\n            ++shape_iter;\n            ++strides_iter;\n        }\n\n        std::fill(strides_iter, strides.rend(), 0);\n        iterator = common_iter(buffer.ptr, strides, shape);\n    }\n\n    void increment_common_iterator(size_t dim) {\n        for (auto &iter : m_common_iterator) {\n            iter.increment(dim);\n        }\n    }\n\n    container_type m_shape;\n    container_type m_index;\n    std::array<common_iter, N> m_common_iterator;\n};\n\nenum class broadcast_trivial { non_trivial, c_trivial, f_trivial };\n\n// Populates the shape and number of dimensions for the set of buffers.  Returns a\n// broadcast_trivial enum value indicating whether the broadcast is \"trivial\"--that is, has each\n// buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous\n// (`f_trivial`) storage buffer; returns `non_trivial` otherwise.\ntemplate <size_t N>\nbroadcast_trivial\nbroadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {\n    ndim = std::accumulate(\n        buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {\n            return std::max(res, buf.ndim);\n        });\n\n    shape.clear();\n    shape.resize((size_t) ndim, 1);\n\n    // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1\n    // or the full size).\n    for (size_t i = 0; i < N; ++i) {\n        auto res_iter = shape.rbegin();\n        auto end = buffers[i].shape.rend();\n        for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;\n             ++shape_iter, ++res_iter) {\n            const auto &dim_size_in = *shape_iter;\n            auto &dim_size_out = *res_iter;\n\n            // Each input dimension can either be 1 or `n`, but `n` values must match across\n            // buffers\n            if (dim_size_out == 1) {\n                dim_size_out = dim_size_in;\n            } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {\n                pybind11_fail(\"pybind11::vectorize: incompatible size/dimension of inputs!\");\n            }\n        }\n    }\n\n    bool trivial_broadcast_c = true;\n    bool trivial_broadcast_f = true;\n    for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {\n        if (buffers[i].size == 1) {\n            continue;\n        }\n\n        // Require the same number of dimensions:\n        if (buffers[i].ndim != ndim) {\n            return broadcast_trivial::non_trivial;\n        }\n\n        // Require all dimensions be full-size:\n        if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {\n            return broadcast_trivial::non_trivial;\n        }\n\n        // Check for C contiguity (but only if previous inputs were also C contiguous)\n        if (trivial_broadcast_c) {\n            ssize_t expect_stride = buffers[i].itemsize;\n            auto end = buffers[i].shape.crend();\n            for (auto shape_iter = buffers[i].shape.crbegin(),\n                      stride_iter = buffers[i].strides.crbegin();\n                 trivial_broadcast_c && shape_iter != end;\n                 ++shape_iter, ++stride_iter) {\n                if (expect_stride == *stride_iter) {\n                    expect_stride *= *shape_iter;\n                } else {\n                    trivial_broadcast_c = false;\n                }\n            }\n        }\n\n        // Check for Fortran contiguity (if previous inputs were also F contiguous)\n        if (trivial_broadcast_f) {\n            ssize_t expect_stride = buffers[i].itemsize;\n            auto end = buffers[i].shape.cend();\n            for (auto shape_iter = buffers[i].shape.cbegin(),\n                      stride_iter = buffers[i].strides.cbegin();\n                 trivial_broadcast_f && shape_iter != end;\n                 ++shape_iter, ++stride_iter) {\n                if (expect_stride == *stride_iter) {\n                    expect_stride *= *shape_iter;\n                } else {\n                    trivial_broadcast_f = false;\n                }\n            }\n        }\n    }\n\n    return trivial_broadcast_c   ? broadcast_trivial::c_trivial\n           : trivial_broadcast_f ? broadcast_trivial::f_trivial\n                                 : broadcast_trivial::non_trivial;\n}\n\ntemplate <typename T>\nstruct vectorize_arg {\n    static_assert(!std::is_rvalue_reference<T>::value,\n                  \"Functions with rvalue reference arguments cannot be vectorized\");\n    // The wrapped function gets called with this type:\n    using call_type = remove_reference_t<T>;\n    // Is this a vectorized argument?\n    static constexpr bool vectorize\n        = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value\n          && satisfies_none_of<call_type,\n                               std::is_pointer,\n                               std::is_array,\n                               is_std_array,\n                               std::is_enum>::value\n          && (!std::is_reference<T>::value\n              || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));\n    // Accept this type: an array for vectorized types, otherwise the type as-is:\n    using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;\n};\n\n// py::vectorize when a return type is present\ntemplate <typename Func, typename Return, typename... Args>\nstruct vectorize_returned_array {\n    using Type = array_t<Return>;\n\n    static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {\n        if (trivial == broadcast_trivial::f_trivial) {\n            return array_t<Return, array::f_style>(shape);\n        }\n        return array_t<Return>(shape);\n    }\n\n    static Return *mutable_data(Type &array) { return array.mutable_data(); }\n\n    static Return call(Func &f, Args &...args) { return f(args...); }\n\n    static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }\n};\n\n// py::vectorize when a return type is not present\ntemplate <typename Func, typename... Args>\nstruct vectorize_returned_array<Func, void, Args...> {\n    using Type = none;\n\n    static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }\n\n    static void *mutable_data(Type &) { return nullptr; }\n\n    static detail::void_type call(Func &f, Args &...args) {\n        f(args...);\n        return {};\n    }\n\n    static void call(void *, size_t, Func &f, Args &...args) { f(args...); }\n};\n\ntemplate <typename Func, typename Return, typename... Args>\nstruct vectorize_helper {\n\n// NVCC for some reason breaks if NVectorized is private\n#ifdef __CUDACC__\npublic:\n#else\nprivate:\n#endif\n\n    static constexpr size_t N = sizeof...(Args);\n    static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);\n    static_assert(\n        NVectorized >= 1,\n        \"pybind11::vectorize(...) requires a function with at least one vectorizable argument\");\n\npublic:\n    template <typename T,\n              // SFINAE to prevent shadowing the copy constructor.\n              typename = detail::enable_if_t<\n                  !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>>\n    explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}\n\n    object operator()(typename vectorize_arg<Args>::type... args) {\n        return run(args...,\n                   make_index_sequence<N>(),\n                   select_indices<vectorize_arg<Args>::vectorize...>(),\n                   make_index_sequence<NVectorized>());\n    }\n\nprivate:\n    remove_reference_t<Func> f;\n\n    // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling\n    // with \"/permissive-\" flag when arg_call_types is manually inlined.\n    using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;\n    template <size_t Index>\n    using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;\n\n    using returned_array = vectorize_returned_array<Func, Return, Args...>;\n\n    // Runs a vectorized function given arguments tuple and three index sequences:\n    //     - Index is the full set of 0 ... (N-1) argument indices;\n    //     - VIndex is the subset of argument indices with vectorized parameters, letting us access\n    //       vectorized arguments (anything not in this sequence is passed through)\n    //     - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that\n    //       we can store vectorized buffer_infos in an array (argument VIndex has its buffer at\n    //       index BIndex in the array).\n    template <size_t... Index, size_t... VIndex, size_t... BIndex>\n    object run(typename vectorize_arg<Args>::type &...args,\n               index_sequence<Index...> i_seq,\n               index_sequence<VIndex...> vi_seq,\n               index_sequence<BIndex...> bi_seq) {\n\n        // Pointers to values the function was called with; the vectorized ones set here will start\n        // out as array_t<T> pointers, but they will be changed them to T pointers before we make\n        // call the wrapped function.  Non-vectorized pointers are left as-is.\n        std::array<void *, N> params{{reinterpret_cast<void *>(&args)...}};\n\n        // The array of `buffer_info`s of vectorized arguments:\n        std::array<buffer_info, NVectorized> buffers{\n            {reinterpret_cast<array *>(params[VIndex])->request()...}};\n\n        /* Determine dimensions parameters of output array */\n        ssize_t nd = 0;\n        std::vector<ssize_t> shape(0);\n        auto trivial = broadcast(buffers, nd, shape);\n        auto ndim = (size_t) nd;\n\n        size_t size\n            = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());\n\n        // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.\n        // not wrapped in an array).\n        if (size == 1 && ndim == 0) {\n            PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);\n            return cast(\n                returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));\n        }\n\n        auto result = returned_array::create(trivial, shape);\n\n        PYBIND11_WARNING_PUSH\n#ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING\n        PYBIND11_WARNING_DISABLE_CLANG(\"-Wreturn-std-move\")\n#endif\n\n        if (size == 0) {\n            return result;\n        }\n\n        /* Call the function */\n        auto *mutable_data = returned_array::mutable_data(result);\n        if (trivial == broadcast_trivial::non_trivial) {\n            apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);\n        } else {\n            apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);\n        }\n\n        return result;\n        PYBIND11_WARNING_POP\n    }\n\n    template <size_t... Index, size_t... VIndex, size_t... BIndex>\n    void apply_trivial(std::array<buffer_info, NVectorized> &buffers,\n                       std::array<void *, N> &params,\n                       Return *out,\n                       size_t size,\n                       index_sequence<Index...>,\n                       index_sequence<VIndex...>,\n                       index_sequence<BIndex...>) {\n\n        // Initialize an array of mutable byte references and sizes with references set to the\n        // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size\n        // (except for singletons, which get an increment of 0).\n        std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{\n            {std::pair<unsigned char *&, const size_t>(\n                reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),\n                buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};\n\n        for (size_t i = 0; i < size; ++i) {\n            returned_array::call(\n                out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);\n            for (auto &x : vecparams) {\n                x.first += x.second;\n            }\n        }\n    }\n\n    template <size_t... Index, size_t... VIndex, size_t... BIndex>\n    void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,\n                         std::array<void *, N> &params,\n                         Return *out,\n                         size_t size,\n                         const std::vector<ssize_t> &output_shape,\n                         index_sequence<Index...>,\n                         index_sequence<VIndex...>,\n                         index_sequence<BIndex...>) {\n\n        multi_array_iterator<NVectorized> input_iter(buffers, output_shape);\n\n        for (size_t i = 0; i < size; ++i, ++input_iter) {\n            PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));\n            returned_array::call(\n                out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);\n        }\n    }\n};\n\ntemplate <typename Func, typename Return, typename... Args>\nvectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {\n    return detail::vectorize_helper<Func, Return, Args...>(f);\n}\n\ntemplate <typename T, int Flags>\nstruct handle_type_name<array_t<T, Flags>> {\n    static constexpr auto name\n        = io_name(\"typing.Annotated[numpy.typing.ArrayLike, \", \"numpy.typing.NDArray[\")\n          + npy_format_descriptor<T>::name + const_name(\"]\");\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n// Vanilla pointer vectorizer:\ntemplate <typename Return, typename... Args>\ndetail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {\n    return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);\n}\n\n// lambda vectorizer:\ntemplate <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>\nauto vectorize(Func &&f)\n    -> decltype(detail::vectorize_extractor(std::forward<Func>(f),\n                                            (detail::function_signature_t<Func> *) nullptr)) {\n    return detail::vectorize_extractor(std::forward<Func>(f),\n                                       (detail::function_signature_t<Func> *) nullptr);\n}\n\n// Vectorize a class method (non-const):\ntemplate <typename Return,\n          typename Class,\n          typename... Args,\n          typename Helper = detail::vectorize_helper<\n              decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),\n              Return,\n              Class *,\n              Args...>>\nHelper vectorize(Return (Class::*f)(Args...)) {\n    return Helper(std::mem_fn(f));\n}\n\n// Vectorize a class method (const):\ntemplate <typename Return,\n          typename Class,\n          typename... Args,\n          typename Helper = detail::vectorize_helper<\n              decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),\n              Return,\n              const Class *,\n              Args...>>\nHelper vectorize(Return (Class::*f)(Args...) const) {\n    return Helper(std::mem_fn(f));\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/operators.h",
    "content": "/*\n    pybind11/operator.h: Metatemplates for operator overloading\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/// Enumeration with all supported operator types\nenum op_id : int {\n    op_add,\n    op_sub,\n    op_mul,\n    op_div,\n    op_mod,\n    op_divmod,\n    op_pow,\n    op_lshift,\n    op_rshift,\n    op_and,\n    op_xor,\n    op_or,\n    op_neg,\n    op_pos,\n    op_abs,\n    op_invert,\n    op_int,\n    op_long,\n    op_float,\n    op_str,\n    op_cmp,\n    op_gt,\n    op_ge,\n    op_lt,\n    op_le,\n    op_eq,\n    op_ne,\n    op_iadd,\n    op_isub,\n    op_imul,\n    op_idiv,\n    op_imod,\n    op_ilshift,\n    op_irshift,\n    op_iand,\n    op_ixor,\n    op_ior,\n    op_complex,\n    op_bool,\n    op_nonzero,\n    op_repr,\n    op_truediv,\n    op_itruediv,\n    op_hash\n};\n\nenum op_type : int {\n    op_l, /* base type on left */\n    op_r, /* base type on right */\n    op_u  /* unary operator */\n};\n\nstruct self_t {};\nstatic const self_t self = self_t();\n\n/// Type for an unused type slot\nstruct undefined_t {};\n\n/// Don't warn about an unused variable\ninline self_t __self() { return self; }\n\n/// base template of operator implementations\ntemplate <op_id, op_type, typename B, typename L, typename R>\nstruct op_impl {};\n\n/// Operator implementation generator\ntemplate <op_id id, op_type ot, typename L, typename R>\nstruct op_ {\n    static constexpr bool op_enable_if_hook = true;\n    template <typename Class, typename... Extra>\n    void execute(Class &cl, const Extra &...extra) const {\n        using Base = typename Class::type;\n        using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;\n        using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;\n        using op = op_impl<id, ot, Base, L_type, R_type>;\n        cl.def(op::name(), &op::execute, is_operator(), extra...);\n    }\n    template <typename Class, typename... Extra>\n    void execute_cast(Class &cl, const Extra &...extra) const {\n        using Base = typename Class::type;\n        using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;\n        using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;\n        using op = op_impl<id, ot, Base, L_type, R_type>;\n        cl.def(op::name(), &op::execute_cast, is_operator(), extra...);\n    }\n};\n\n#define PYBIND11_BINARY_OPERATOR(id, rid, op, expr)                                               \\\n    template <typename B, typename L, typename R>                                                 \\\n    struct op_impl<op_##id, op_l, B, L, R> {                                                      \\\n        static char const *name() { return \"__\" #id \"__\"; }                                       \\\n        static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); }          \\\n        static B execute_cast(const L &l, const R &r) { return B(expr); }                         \\\n    };                                                                                            \\\n    template <typename B, typename L, typename R>                                                 \\\n    struct op_impl<op_##id, op_r, B, L, R> {                                                      \\\n        static char const *name() { return \"__\" #rid \"__\"; }                                      \\\n        static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); }          \\\n        static B execute_cast(const R &r, const L &l) { return B(expr); }                         \\\n    };                                                                                            \\\n    inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) {                \\\n        return op_<op_##id, op_l, self_t, self_t>();                                              \\\n    }                                                                                             \\\n    template <typename T>                                                                         \\\n    op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) {                                 \\\n        return op_<op_##id, op_l, self_t, T>();                                                   \\\n    }                                                                                             \\\n    template <typename T>                                                                         \\\n    op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) {                                 \\\n        return op_<op_##id, op_r, T, self_t>();                                                   \\\n    }\n\n#define PYBIND11_INPLACE_OPERATOR(id, op, expr)                                                   \\\n    template <typename B, typename L, typename R>                                                 \\\n    struct op_impl<op_##id, op_l, B, L, R> {                                                      \\\n        static char const *name() { return \"__\" #id \"__\"; }                                       \\\n        static auto execute(L &l, const R &r) -> decltype(expr) { return expr; }                  \\\n        static B execute_cast(L &l, const R &r) { return B(expr); }                               \\\n    };                                                                                            \\\n    template <typename T>                                                                         \\\n    op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) {                                 \\\n        return op_<op_##id, op_l, self_t, T>();                                                   \\\n    }\n\n#define PYBIND11_UNARY_OPERATOR(id, op, expr)                                                     \\\n    template <typename B, typename L>                                                             \\\n    struct op_impl<op_##id, op_u, B, L, undefined_t> {                                            \\\n        static char const *name() { return \"__\" #id \"__\"; }                                       \\\n        static auto execute(const L &l) -> decltype(expr) { return expr; }                        \\\n        static B execute_cast(const L &l) { return B(expr); }                                     \\\n    };                                                                                            \\\n    inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) {                           \\\n        return op_<op_##id, op_u, self_t, undefined_t>();                                         \\\n    }\n\nPYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)\nPYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)\nPYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l *r)\nPYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)\nPYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)\nPYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)\nPYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)\nPYBIND11_BINARY_OPERATOR(and, rand, operator&, l &r)\nPYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)\nPYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)\nPYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)\nPYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)\nPYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)\nPYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)\nPYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)\nPYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)\n// PYBIND11_BINARY_OPERATOR(pow,       rpow,         pow,          std::pow(l,  r))\nPYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)\nPYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)\nPYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)\nPYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)\nPYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)\nPYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)\nPYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)\nPYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)\nPYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)\nPYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)\nPYBIND11_UNARY_OPERATOR(neg, operator-, -l)\nPYBIND11_UNARY_OPERATOR(pos, operator+, +l)\n// WARNING: This usage of `abs` should only be done for existing STL overloads.\n// Adding overloads directly in to the `std::` namespace is advised against:\n// https://en.cppreference.com/w/cpp/language/extending_std\nPYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))\nPYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))\nPYBIND11_UNARY_OPERATOR(invert, operator~, (~l))\nPYBIND11_UNARY_OPERATOR(bool, operator!, !!l)\nPYBIND11_UNARY_OPERATOR(int, int_, (int) l)\nPYBIND11_UNARY_OPERATOR(float, float_, (double) l)\n\n#undef PYBIND11_BINARY_OPERATOR\n#undef PYBIND11_INPLACE_OPERATOR\n#undef PYBIND11_UNARY_OPERATOR\nPYBIND11_NAMESPACE_END(detail)\n\nusing detail::self;\n// Add named operators so that they are accessible via `py::`.\nusing detail::hash;\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/options.h",
    "content": "/*\n    pybind11/options.h: global settings that are configurable at runtime.\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nclass options {\npublic:\n    // Default RAII constructor, which leaves settings as they currently are.\n    options() : previous_state(global_state()) {}\n\n    // Class is non-copyable.\n    options(const options &) = delete;\n    options &operator=(const options &) = delete;\n\n    // Destructor, which restores settings that were in effect before.\n    ~options() { global_state() = previous_state; }\n\n    // Setter methods (affect the global state):\n\n    options &disable_user_defined_docstrings() & {\n        global_state().show_user_defined_docstrings = false;\n        return *this;\n    }\n\n    options &enable_user_defined_docstrings() & {\n        global_state().show_user_defined_docstrings = true;\n        return *this;\n    }\n\n    options &disable_function_signatures() & {\n        global_state().show_function_signatures = false;\n        return *this;\n    }\n\n    options &enable_function_signatures() & {\n        global_state().show_function_signatures = true;\n        return *this;\n    }\n\n    options &disable_enum_members_docstring() & {\n        global_state().show_enum_members_docstring = false;\n        return *this;\n    }\n\n    options &enable_enum_members_docstring() & {\n        global_state().show_enum_members_docstring = true;\n        return *this;\n    }\n\n    // Getter methods (return the global state):\n\n    static bool show_user_defined_docstrings() {\n        return global_state().show_user_defined_docstrings;\n    }\n\n    static bool show_function_signatures() { return global_state().show_function_signatures; }\n\n    static bool show_enum_members_docstring() {\n        return global_state().show_enum_members_docstring;\n    }\n\n    // This type is not meant to be allocated on the heap.\n    void *operator new(size_t) = delete;\n\nprivate:\n    struct state {\n        bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.\n        bool show_function_signatures = true;     //< Include auto-generated function signatures\n                                                  //  in docstrings.\n        bool show_enum_members_docstring = true;  //< Include auto-generated member list in enum\n                                                  //  docstrings.\n    };\n\n    static state &global_state() {\n        static state instance;\n        return instance;\n    }\n\n    state previous_state;\n};\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/pybind11.h",
    "content": "/*\n    pybind11/pybind11.h: Main header file of the C++11 python\n    binding generator library\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n#include \"detail/class.h\"\n#include \"detail/dynamic_raw_ptr_cast_if_possible.h\"\n#include \"detail/exception_translation.h\"\n#include \"detail/function_record_pyobject.h\"\n#include \"detail/function_ref.h\"\n#include \"detail/init.h\"\n#include \"detail/native_enum_data.h\"\n#include \"detail/using_smart_holder.h\"\n#include \"attr.h\"\n#include \"gil.h\"\n#include \"gil_safe_call_once.h\"\n#include \"options.h\"\n#include \"trampoline_self_life_support.h\"\n#include \"typing.h\"\n\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <memory>\n#include <new>\n#include <stack>\n#include <string>\n#include <utility>\n#include <vector>\n\n// See PR #5448. This warning suppression is needed for the PYBIND11_OVERRIDE macro family.\n// NOTE that this is NOT embedded in a push/pop pair because that is very difficult to achieve.\n#if defined(__clang_major__) && __clang_major__ < 14\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wgnu-zero-variadic-macro-arguments\")\n#endif\n\n#if defined(__GNUG__) && !defined(__clang__)\n#    include <cxxabi.h>\n#endif\n\n#if defined(__cpp_if_constexpr) && __cpp_if_constexpr >= 201606\n#    define PYBIND11_MAYBE_CONSTEXPR constexpr\n#else\n#    define PYBIND11_MAYBE_CONSTEXPR\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\n/* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning\n   This warning is about ABI compatibility, not code health.\n   It is only actually needed in a couple places, but apparently GCC 7 \"generates this warning if\n   and only if the first template instantiation ... involves noexcept\" [stackoverflow], therefore\n   it could get triggered from seemingly random places, depending on user code.\n   No other GCC version generates this warning.\n */\n#if defined(__GNUC__) && __GNUC__ == 7\nPYBIND11_WARNING_DISABLE_GCC(\"-Wnoexcept-type\")\n#endif\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline std::string replace_newlines_and_squash(const char *text) {\n    const char *whitespaces = \" \\t\\n\\r\\f\\v\";\n    std::string result(text);\n    bool previous_is_whitespace = false;\n\n    if (result.size() >= 2) {\n        // Do not modify string representations\n        char first_char = result[0];\n        char last_char = result[result.size() - 1];\n        if (first_char == last_char && first_char == '\\'') {\n            return result;\n        }\n    }\n    result.clear();\n\n    // Replace characters in whitespaces array with spaces and squash consecutive spaces\n    while (*text != '\\0') {\n        if (std::strchr(whitespaces, *text)) {\n            if (!previous_is_whitespace) {\n                result += ' ';\n                previous_is_whitespace = true;\n            }\n        } else {\n            result += *text;\n            previous_is_whitespace = false;\n        }\n        ++text;\n    }\n\n    // Strip leading and trailing whitespaces\n    const size_t str_begin = result.find_first_not_of(whitespaces);\n    if (str_begin == std::string::npos) {\n        return \"\";\n    }\n\n    const size_t str_end = result.find_last_not_of(whitespaces);\n    const size_t str_range = str_end - str_begin + 1;\n\n    return result.substr(str_begin, str_range);\n}\n\n/* Generate a proper function signature */\ninline std::string generate_function_signature(const char *type_caster_name_field,\n                                               detail::function_record *func_rec,\n                                               const std::type_info *const *types,\n                                               size_t &type_index,\n                                               size_t &arg_index) {\n    std::string signature;\n    bool is_starred = false;\n    // `is_return_value.top()` is true if we are currently inside the return type of the\n    // signature. Using `@^`/`@$` we can force types to be arg/return types while `@!` pops\n    // back to the previous state.\n    std::stack<bool> is_return_value({false});\n    // The following characters have special meaning in the signature parsing. Literals\n    // containing these are escaped with `!`.\n    std::string special_chars(\"!@%{}-\");\n    for (const auto *pc = type_caster_name_field; *pc != '\\0'; ++pc) {\n        const auto c = *pc;\n        if (c == '{') {\n            // Write arg name for everything except *args and **kwargs.\n            // Detect {@*args...} or {@**kwargs...}\n            is_starred = *(pc + 1) == '@' && *(pc + 2) == '*';\n            if (is_starred) {\n                continue;\n            }\n            // Separator for keyword-only arguments, placed before the kw\n            // arguments start (unless we are already putting an *args)\n            if (!func_rec->has_args && arg_index == func_rec->nargs_pos) {\n                signature += \"*, \";\n            }\n            if (arg_index < func_rec->args.size() && func_rec->args[arg_index].name) {\n                signature += func_rec->args[arg_index].name;\n            } else if (arg_index == 0 && func_rec->is_method) {\n                signature += \"self\";\n            } else {\n                signature += \"arg\" + std::to_string(arg_index - (func_rec->is_method ? 1 : 0));\n            }\n            signature += \": \";\n        } else if (c == '}') {\n            // Write default value if available.\n            if (!is_starred && arg_index < func_rec->args.size()\n                && func_rec->args[arg_index].descr) {\n                signature += \" = \";\n                signature += detail::replace_newlines_and_squash(func_rec->args[arg_index].descr);\n            }\n            // Separator for positional-only arguments (placed after the\n            // argument, rather than before like *\n            if (func_rec->nargs_pos_only > 0 && (arg_index + 1) == func_rec->nargs_pos_only) {\n                signature += \", /\";\n            }\n            if (!is_starred) {\n                arg_index++;\n            }\n        } else if (c == '%') {\n            const std::type_info *t = types[type_index++];\n            if (!t) {\n                pybind11_fail(\"Internal error while parsing type signature (1)\");\n            }\n            if (auto *tinfo = detail::get_type_info(*t)) {\n                handle th(reinterpret_cast<PyObject *>(tinfo->type));\n                signature += th.attr(\"__module__\").cast<std::string>() + \".\"\n                             + th.attr(\"__qualname__\").cast<std::string>();\n            } else if (auto th = detail::global_internals_native_enum_type_map_get_item(*t)) {\n                signature += th.attr(\"__module__\").cast<std::string>() + \".\"\n                             + th.attr(\"__qualname__\").cast<std::string>();\n            } else if (func_rec->is_new_style_constructor && arg_index == 0) {\n                // A new-style `__init__` takes `self` as `value_and_holder`.\n                // Rewrite it to the proper class type.\n                signature += func_rec->scope.attr(\"__module__\").cast<std::string>() + \".\"\n                             + func_rec->scope.attr(\"__qualname__\").cast<std::string>();\n            } else {\n                signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));\n            }\n        } else if (c == '!' && special_chars.find(*(pc + 1)) != std::string::npos) {\n            // typing::Literal escapes special characters with !\n            signature += *++pc;\n        } else if (c == '@') {\n            // `@^ ... @!` and `@$ ... @!` are used to force arg/return value type (see\n            // typing::Callable/detail::arg_descr/detail::return_descr)\n            if (*(pc + 1) == '^') {\n                is_return_value.emplace(false);\n                ++pc;\n                continue;\n            }\n            if (*(pc + 1) == '$') {\n                is_return_value.emplace(true);\n                ++pc;\n                continue;\n            }\n            if (*(pc + 1) == '!') {\n                is_return_value.pop();\n                ++pc;\n                continue;\n            }\n            // Handle types that differ depending on whether they appear\n            // in an argument or a return value position (see io_name<text1, text2>).\n            // For named arguments (py::arg()) with noconvert set, return value type is used.\n            ++pc;\n            if (!is_return_value.top()\n                && (!(arg_index < func_rec->args.size() && !func_rec->args[arg_index].convert))) {\n                while (*pc != '\\0' && *pc != '@') {\n                    signature += *pc++;\n                }\n                if (*pc == '@') {\n                    ++pc;\n                }\n                while (*pc != '\\0' && *pc != '@') {\n                    ++pc;\n                }\n            } else {\n                while (*pc != '\\0' && *pc != '@') {\n                    ++pc;\n                }\n                if (*pc == '@') {\n                    ++pc;\n                }\n                while (*pc != '\\0' && *pc != '@') {\n                    signature += *pc++;\n                }\n            }\n        } else {\n            if (c == '-' && *(pc + 1) == '>') {\n                is_return_value.emplace(true);\n            }\n            signature += c;\n        }\n    }\n    return signature;\n}\n\ntemplate <typename T>\ninline std::string generate_type_signature() {\n    static constexpr auto caster_name_field = make_caster<T>::name;\n    PYBIND11_DESCR_CONSTEXPR auto descr_types = decltype(caster_name_field)::types();\n    // Create a default function_record to ensure the function signature has the proper\n    // configuration e.g. no_convert.\n    auto func_rec = function_record();\n    size_t type_index = 0;\n    size_t arg_index = 0;\n    return generate_function_signature(\n        caster_name_field.text, &func_rec, descr_types.data(), type_index, arg_index);\n}\n\n#if defined(_MSC_VER)\n#    define PYBIND11_COMPAT_STRDUP _strdup\n#else\n#    define PYBIND11_COMPAT_STRDUP strdup\n#endif\n\n#define PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR                                                 \\\n    detail::const_name(\"(\") + cast_in::arg_names + detail::const_name(\") -> \") + cast_out::name\n\n// We factor out readable function signatures to a specific template\n// so that they don't get duplicated across different instantiations of\n// cpp_function::initialize (which is templated on more types).\ntemplate <typename cast_in, typename cast_out>\nclass ReadableFunctionSignature {\npublic:\n    using sig_type = decltype(PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR);\n\nprivate:\n    // We have to repeat PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR in decltype()\n    // because C++11 doesn't allow functions to return `auto`. (We don't\n    // know the type because it's some variant of detail::descr<N> with\n    // unknown N.)\n    static constexpr sig_type sig() { return PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR; }\n\npublic:\n    static constexpr sig_type kSig = sig();\n    // We can only stash the result of detail::descr::types() in a\n    // constexpr variable if we aren't on MSVC (see\n    // PYBIND11_DESCR_CONSTEXPR).\n#if !defined(_MSC_VER)\n    using types_type = decltype(sig_type::types());\n    static constexpr types_type kTypes = sig_type::types();\n#endif\n};\n#undef PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR\n\n// Prior to C++17, we don't have inline variables, so we have to\n// provide an out-of-line definition of the class member.\n#if !defined(PYBIND11_CPP17)\ntemplate <typename cast_in, typename cast_out>\nconstexpr typename ReadableFunctionSignature<cast_in, cast_out>::sig_type\n    ReadableFunctionSignature<cast_in, cast_out>::kSig;\n#    if !defined(_MSC_VER)\ntemplate <typename cast_in, typename cast_out>\nconstexpr typename ReadableFunctionSignature<cast_in, cast_out>::types_type\n    ReadableFunctionSignature<cast_in, cast_out>::kTypes;\n#    endif\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object\nclass cpp_function : public function {\npublic:\n    cpp_function() = default;\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(std::nullptr_t) {}\n    cpp_function(std::nullptr_t, const is_setter &) {}\n\n    /// Construct a cpp_function from a vanilla function pointer\n    template <typename Return, typename... Args, typename... Extra>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Return (*f)(Args...), const Extra &...extra) {\n        initialize(f, f, extra...);\n    }\n\n    /// Construct a cpp_function from a lambda function (possibly with internal state)\n    template <typename Func,\n              typename... Extra,\n              typename = detail::enable_if_t<detail::is_lambda<Func>::value>>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Func &&f, const Extra &...extra) {\n        initialize(\n            std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);\n    }\n\n    /// Construct a cpp_function from a class method (non-const, no ref-qualifier)\n    template <typename Return, typename Class, typename... Arg, typename... Extra>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {\n        initialize(\n            [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },\n            (Return (*)(Class *, Arg...)) nullptr,\n            extra...);\n    }\n\n    /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)\n    /// A copy of the overload for non-const functions without explicit ref-qualifier\n    /// but with an added `&`.\n    template <typename Return, typename Class, typename... Arg, typename... Extra>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {\n        initialize(\n            [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },\n            (Return (*)(Class *, Arg...)) nullptr,\n            extra...);\n    }\n\n    /// Construct a cpp_function from a class method (const, no ref-qualifier)\n    template <typename Return, typename Class, typename... Arg, typename... Extra>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {\n        initialize([f](const Class *c,\n                       Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },\n                   (Return (*)(const Class *, Arg...)) nullptr,\n                   extra...);\n    }\n\n    /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)\n    /// A copy of the overload for const functions without explicit ref-qualifier\n    /// but with an added `&`.\n    template <typename Return, typename Class, typename... Arg, typename... Extra>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {\n        initialize([f](const Class *c,\n                       Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },\n                   (Return (*)(const Class *, Arg...)) nullptr,\n                   extra...);\n    }\n\n    /// Return the function name\n    object name() const { return attr(\"__name__\"); }\n\nprotected:\n    struct InitializingFunctionRecordDeleter {\n        // `destruct(function_record, false)`: `initialize_generic` copies strings and\n        // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.\n        void operator()(detail::function_record *rec) { destruct(rec, false); }\n    };\n    using unique_function_record\n        = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;\n\n    /// Space optimization: don't inline this frequently instantiated fragment\n    PYBIND11_NOINLINE unique_function_record make_function_record() {\n        return unique_function_record(new detail::function_record());\n    }\n\nprivate:\n    // This is outlined from the dispatch lambda in initialize to save\n    // on code size. Crucially, we use function_ref to type-erase the\n    // actual function lambda so that we can get code reuse for\n    // functions with the same Return, Args, and Guard.\n    template <typename Return, typename Guard, typename ArgsConverter, typename... Args>\n    static handle call_impl(detail::function_call &call, detail::function_ref<Return(Args...)> f) {\n        using namespace detail;\n        // Static assertion: function_ref must be trivially copyable to ensure safe pass-by-value.\n        // Lifetime safety: The function_ref is created from cap->f which lives in the capture\n        // object stored in the function record, and is only used synchronously within this\n        // function call. It is never stored beyond the scope of call_impl.\n        static_assert(std::is_trivially_copyable<detail::function_ref<Return(Args...)>>::value,\n                      \"function_ref must be trivially copyable for safe pass-by-value usage\");\n        using cast_out\n            = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;\n\n        ArgsConverter args_converter;\n        if (!args_converter.load_args(call)) {\n            return PYBIND11_TRY_NEXT_OVERLOAD;\n        }\n\n        /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */\n        return_value_policy policy\n            = return_value_policy_override<Return>::policy(call.func.policy);\n\n        /* Perform the function call */\n        handle result;\n        if (call.func.is_setter) {\n            (void) std::move(args_converter).template call<Return, Guard>(f);\n            result = none().release();\n        } else {\n            result = cast_out::cast(\n                std::move(args_converter).template call<Return, Guard>(f), policy, call.parent);\n        }\n\n        return result;\n    }\n\nprotected:\n    /// Special internal constructor for functors, lambda functions, etc.\n    template <typename Func, typename Return, typename... Args, typename... Extra>\n    void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {\n        using namespace detail;\n        struct capture {\n            remove_reference_t<Func> f;\n\n            static capture *from_data(void **data) {\n                return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));\n            }\n        };\n\n        /* Store the function including any extra state it might have (e.g. a lambda capture\n         * object) */\n        // The unique_ptr makes sure nothing is leaked in case of an exception.\n        auto unique_rec = make_function_record();\n        auto *rec = unique_rec.get();\n\n        /* Store the capture object directly in the function record if there is enough space */\n        if (sizeof(capture) <= sizeof(rec->data)) {\n            /* Without these pragmas, GCC warns that there might not be\n               enough space to use the placement new operator. However, the\n               'if' statement above ensures that this is the case. */\n            PYBIND11_WARNING_PUSH\n\n#if defined(__GNUG__) && __GNUC__ >= 6\n            PYBIND11_WARNING_DISABLE_GCC(\"-Wplacement-new\")\n#endif\n\n            new (capture::from_data(rec->data)) capture{std::forward<Func>(f)};\n\n#if !PYBIND11_HAS_STD_LAUNDER\n            PYBIND11_WARNING_DISABLE_GCC(\"-Wstrict-aliasing\")\n#endif\n\n            // UB without std::launder, but without breaking ABI and/or\n            // a significant refactoring it's \"impossible\" to solve.\n            if (!std::is_trivially_destructible<capture>::value) {\n                rec->free_data = [](function_record *r) {\n                    auto data = capture::from_data(r->data);\n                    (void) data; // suppress \"unused variable\" warnings\n                    data->~capture();\n                };\n            }\n            PYBIND11_WARNING_POP\n        } else {\n            rec->data[0] = new capture{std::forward<Func>(f)};\n            rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };\n        }\n\n        /* Type casters for the function arguments and return value */\n        using cast_in = argument_loader<Args...>;\n        using cast_out\n            = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;\n\n        static_assert(\n            expected_num_args<Extra...>(\n                sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),\n            \"The number of argument annotations does not match the number of function arguments\");\n\n        /* Dispatch code which converts function arguments and performs the actual function call */\n        rec->impl = [](function_call &call) -> handle {\n            /* Invoke call policy pre-call hook */\n            process_attributes<Extra...>::precall(call);\n\n            /* Get a pointer to the capture object */\n            const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data\n                                                                          : call.func.data[0]);\n            auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));\n\n            auto result = call_impl<Return,\n                                    /* Function scope guard -- defaults to the compile-to-nothing\n                                       `void_type` */\n                                    extract_guard_t<Extra...>,\n                                    cast_in>(call, detail::function_ref<Return(Args...)>(cap->f));\n\n            /* Invoke call policy post-call hook */\n            process_attributes<Extra...>::postcall(call, result);\n\n            return result;\n        };\n\n        rec->nargs_pos = cast_in::args_pos >= 0\n                             ? static_cast<std::uint16_t>(cast_in::args_pos)\n                             : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if\n                                                                      // we have a kw_only\n        rec->has_args = cast_in::args_pos >= 0;\n        rec->has_kwargs = cast_in::has_kwargs;\n\n        /* Process any user-provided function attributes */\n        process_attributes<Extra...>::init(extra..., rec);\n\n        {\n            constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,\n                           has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,\n                           has_arg_annotations = any_of<is_keyword<Extra>...>::value;\n            constexpr bool has_is_method = any_of<std::is_same<is_method, Extra>...>::value;\n            // The implicit `self` argument is not present and not counted in method definitions.\n            constexpr bool has_args = cast_in::args_pos >= 0;\n            constexpr bool is_method_with_self_arg_only = has_is_method && !has_args;\n            static_assert(has_arg_annotations || !has_kw_only_args,\n                          \"py::kw_only requires the use of argument annotations\");\n            static_assert(((/* Need `py::arg(\"arg_name\")` annotation in function/method. */\n                            has_arg_annotations)\n                           || (/* Allow methods with no arguments `def method(self, /): ...`.\n                                * A method has at least one argument `self`. There can be no\n                                * `py::arg` annotation. E.g. `class.def(\"method\", py::pos_only())`.\n                                */\n                               is_method_with_self_arg_only))\n                              || !has_pos_only_args,\n                          \"py::pos_only requires the use of argument annotations (for docstrings \"\n                          \"and aligning the annotations to the argument)\");\n\n            static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,\n                          \"py::kw_only may be specified only once\");\n            static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,\n                          \"py::pos_only may be specified only once\");\n            constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();\n            constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();\n            static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,\n                          \"py::pos_only must come before py::kw_only\");\n        }\n\n        /* Generate a readable signature describing the function's arguments and return\n           value types */\n        static constexpr const auto &signature\n            = detail::ReadableFunctionSignature<cast_in, cast_out>::kSig;\n#if !defined(_MSC_VER)\n        static constexpr const auto &types\n            = detail::ReadableFunctionSignature<cast_in, cast_out>::kTypes;\n#else\n        PYBIND11_DESCR_CONSTEXPR auto types = std::decay<decltype(signature)>::type::types();\n#endif\n\n        /* Register the function with Python from generic (non-templated) code */\n        // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.\n        initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));\n\n        /* Stash some additional information used by an important optimization in 'functional.h' */\n        using FunctionType = Return (*)(Args...);\n        constexpr bool is_function_ptr\n            = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);\n        PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(\n            !is_function_ptr || std::is_standard_layout<capture>::value);\n        if (is_function_ptr) {\n            rec->is_stateless = true;\n            rec->data[1]\n                = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));\n        }\n    }\n\n    // Utility class that keeps track of all duplicated strings, and cleans them up in its\n    // destructor, unless they are released. Basically a RAII-solution to deal with exceptions\n    // along the way.\n    class strdup_guard {\n    public:\n        strdup_guard() = default;\n        strdup_guard(const strdup_guard &) = delete;\n        strdup_guard &operator=(const strdup_guard &) = delete;\n\n        ~strdup_guard() {\n            for (auto *s : strings) {\n                std::free(s);\n            }\n        }\n        char *operator()(const char *s) {\n            auto *t = PYBIND11_COMPAT_STRDUP(s);\n            strings.push_back(t);\n            return t;\n        }\n        void release() { strings.clear(); }\n\n    private:\n        std::vector<char *> strings;\n    };\n\n    /// Register a function call with Python (generic non-templated code goes here)\n    void initialize_generic(unique_function_record &&unique_rec,\n                            const char *text,\n                            const std::type_info *const *types,\n                            size_t args) {\n        // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,\n        // we do not want this to destruct the pointer. `initialize` (the caller) still relies on\n        // the pointee being alive after this call. Only move out if a `capsule` is going to keep\n        // it alive.\n        auto *rec = unique_rec.get();\n\n        // Keep track of strdup'ed strings, and clean them up as long as the function's capsule\n        // has not taken ownership yet (when `unique_rec.release()` is called).\n        // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the\n        // strings are only referenced before strdup'ing. So only *after* the following block could\n        // `destruct` safely be called, but even then, `repr` could still throw in the middle of\n        // copying all strings.\n        strdup_guard guarded_strdup;\n\n        /* Create copies of all referenced C-style strings */\n        rec->name = guarded_strdup(rec->name ? rec->name : \"\");\n        if (rec->doc) {\n            rec->doc = guarded_strdup(rec->doc);\n        }\n        for (auto &a : rec->args) {\n            if (a.name) {\n                a.name = guarded_strdup(a.name);\n            }\n            if (a.descr) {\n                a.descr = guarded_strdup(a.descr);\n            } else if (a.value) {\n                a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());\n            }\n        }\n\n        rec->is_constructor = (std::strcmp(rec->name, \"__init__\") == 0)\n                              || (std::strcmp(rec->name, \"__setstate__\") == 0);\n\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)\n        if (rec->is_constructor && !rec->is_new_style_constructor) {\n            const auto class_name\n                = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());\n            const auto func_name = std::string(rec->name);\n            PyErr_WarnEx(PyExc_FutureWarning,\n                         (\"pybind11-bound class '\" + class_name\n                          + \"' is using an old-style \"\n                            \"placement-new '\"\n                          + func_name\n                          + \"' which has been deprecated. See \"\n                            \"the upgrade guide in pybind11's docs. This message is only visible \"\n                            \"when compiled in debug mode.\")\n                             .c_str(),\n                         0);\n        }\n#endif\n\n        size_t type_index = 0, arg_index = 0;\n        std::string signature\n            = detail::generate_function_signature(text, rec, types, type_index, arg_index);\n\n        if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {\n            pybind11_fail(\"Internal error while parsing type signature (2)\");\n        }\n\n        rec->signature = guarded_strdup(signature.c_str());\n        rec->args.shrink_to_fit();\n        rec->nargs = static_cast<std::uint16_t>(args);\n\n        if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {\n            rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());\n        }\n\n        detail::function_record *chain = nullptr, *chain_start = rec;\n        if (rec->sibling) {\n            if (PyCFunction_Check(rec->sibling.ptr())) {\n                auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());\n                if (self == nullptr) {\n                    pybind11_fail(\n                        \"initialize_generic: Unexpected nullptr from PyCFunction_GET_SELF\");\n                }\n                chain = detail::function_record_ptr_from_PyObject(self);\n                if (chain && !chain->scope.is(rec->scope)) {\n                    /* Never append a method to an overload chain of a parent class;\n                       instead, hide the parent's overloads in this case */\n                    chain = nullptr;\n                }\n            }\n            // Don't trigger for things like the default __init__, which are wrapper_descriptors\n            // that we are intentionally replacing\n            else if (!rec->sibling.is_none() && rec->name[0] != '_') {\n                pybind11_fail(\"Cannot overload existing non-function object \\\"\"\n                              + std::string(rec->name) + \"\\\" with a function of the same name\");\n            }\n        }\n\n        if (!chain) {\n            /* No existing overload was found, create a new function object */\n            rec->def = new PyMethodDef();\n            std::memset(rec->def, 0, sizeof(PyMethodDef));\n            rec->def->ml_name = rec->name;\n            rec->def->ml_meth\n                = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));\n            rec->def->ml_flags = METH_FASTCALL | METH_KEYWORDS;\n\n            object py_func_rec = detail::function_record_PyObject_New();\n            (reinterpret_cast<detail::function_record_PyObject *>(py_func_rec.ptr()))->cpp_func_rec\n                = unique_rec.release();\n            guarded_strdup.release();\n\n            object scope_module = detail::get_scope_module(rec->scope);\n            m_ptr = PyCFunction_NewEx(rec->def, py_func_rec.ptr(), scope_module.ptr());\n            if (!m_ptr) {\n                pybind11_fail(\"cpp_function::cpp_function(): Could not allocate function object\");\n            }\n        } else {\n            /* Append at the beginning or end of the overload chain */\n            m_ptr = rec->sibling.ptr();\n            inc_ref();\n            if (chain->is_method != rec->is_method) {\n                pybind11_fail(\n                    \"overloading a method with both static and instance methods is not supported; \"\n#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                    \"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more \"\n                    \"details\"\n#else\n                    \"error while attempting to bind \"\n                    + std::string(rec->is_method ? \"instance\" : \"static\") + \" method \"\n                    + std::string(pybind11::str(rec->scope.attr(\"__name__\"))) + \".\"\n                    + std::string(rec->name) + signature\n#endif\n                );\n            }\n\n            if (rec->prepend) {\n                // Beginning of chain; we need to replace the capsule's current head-of-the-chain\n                // pointer with this one, then make this one point to the previous head of the\n                // chain.\n                chain_start = rec;\n                rec->next = chain;\n                auto *py_func_rec = reinterpret_cast<detail::function_record_PyObject *>(\n                    PyCFunction_GET_SELF(m_ptr));\n                py_func_rec->cpp_func_rec = unique_rec.release();\n                guarded_strdup.release();\n            } else {\n                // Or end of chain (normal behavior)\n                chain_start = chain;\n                while (chain->next) {\n                    chain = chain->next;\n                }\n                chain->next = unique_rec.release();\n                guarded_strdup.release();\n            }\n        }\n\n        std::string signatures;\n        int index = 0;\n        /* Create a nice pydoc rec including all signatures and\n           docstrings of the functions in the overload chain */\n        if (chain && options::show_function_signatures()\n            && std::strcmp(rec->name, \"_pybind11_conduit_v1_\") != 0) {\n            // First a generic signature\n            signatures += rec->name;\n            signatures += \"(*args, **kwargs)\\n\";\n            signatures += \"Overloaded function.\\n\\n\";\n        }\n        // Then specific overload signatures\n        bool first_user_def = true;\n        for (auto *it = chain_start; it != nullptr; it = it->next) {\n            if (options::show_function_signatures()\n                && std::strcmp(rec->name, \"_pybind11_conduit_v1_\") != 0) {\n                if (index > 0) {\n                    signatures += '\\n';\n                }\n                if (chain) {\n                    signatures += std::to_string(++index) + \". \";\n                }\n                signatures += rec->name;\n                signatures += it->signature;\n                signatures += '\\n';\n            }\n            if (it->doc && it->doc[0] != '\\0' && options::show_user_defined_docstrings()) {\n                // If we're appending another docstring, and aren't printing function signatures,\n                // we need to append a newline first:\n                if (!options::show_function_signatures()) {\n                    if (first_user_def) {\n                        first_user_def = false;\n                    } else {\n                        signatures += '\\n';\n                    }\n                }\n                if (options::show_function_signatures()) {\n                    signatures += '\\n';\n                }\n                signatures += it->doc;\n                if (options::show_function_signatures()) {\n                    signatures += '\\n';\n                }\n            }\n        }\n\n        auto *func = reinterpret_cast<PyCFunctionObject *>(m_ptr);\n        // Install docstring if it's non-empty (when at least one option is enabled)\n        auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());\n        std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func)));\n        PYBIND11_PYCFUNCTION_SET_DOC(func, doc);\n\n        if (rec->is_method) {\n            m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());\n            if (!m_ptr) {\n                pybind11_fail(\n                    \"cpp_function::cpp_function(): Could not allocate instance method object\");\n            }\n            Py_DECREF(func);\n        }\n    }\n\n    friend void detail::function_record_PyTypeObject_methods::tp_dealloc_impl(PyObject *);\n\n    /// When a cpp_function is GCed, release any memory allocated by pybind11\n    static void destruct(detail::function_record *rec, bool free_strings = true) {\n// If on Python 3.9, check the interpreter \"MICRO\" (patch) version.\n// If this is running on 3.9.0, we have to work around a bug.\n#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9\n        static bool is_zero = Py_GetVersion()[4] == '0';\n#endif\n\n        while (rec) {\n            detail::function_record *next = rec->next;\n            if (rec->free_data) {\n                rec->free_data(rec);\n            }\n            // During initialization, these strings might not have been copied yet,\n            // so they cannot be freed. Once the function has been created, they can.\n            // Check `make_function_record` for more details.\n            if (free_strings) {\n                std::free(rec->name);\n                std::free(rec->doc);\n                std::free(rec->signature);\n                for (auto &arg : rec->args) {\n                    std::free(const_cast<char *>(arg.name));\n                    std::free(const_cast<char *>(arg.descr));\n                }\n            }\n            for (auto &arg : rec->args) {\n                arg.value.dec_ref();\n            }\n            if (rec->def) {\n                std::free(const_cast<char *>(rec->def->ml_doc));\n// Python 3.9.0 decref's these in the wrong order; rec->def\n// If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)\n// See https://github.com/python/cpython/pull/22670\n#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9\n                if (!is_zero) {\n                    delete rec->def;\n                }\n#else\n                delete rec->def;\n#endif\n            }\n            delete rec;\n            rec = next;\n        }\n    }\n\n    /// Main dispatch logic for calls to functions bound using pybind11\n    static PyObject *\n    dispatcher(PyObject *self, PyObject *const *args_in_arr, size_t nargsf, PyObject *kwnames_in) {\n        using namespace detail;\n        const function_record *overloads = function_record_ptr_from_PyObject(self);\n        assert(overloads != nullptr);\n\n        /* Iterator over the list of potentially admissible overloads */\n        const function_record *current_overload = overloads;\n\n        /* Need to know how many arguments + keyword arguments there are to pick the right\n           overload */\n        const auto n_args_in = static_cast<size_t>(PyVectorcall_NARGS(nargsf));\n\n        handle parent = n_args_in > 0 ? args_in_arr[0] : nullptr,\n               result = PYBIND11_TRY_NEXT_OVERLOAD;\n\n        auto self_value_and_holder = value_and_holder();\n        if (overloads->is_constructor) {\n            if (!parent\n                || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {\n                set_error(PyExc_TypeError,\n                          \"__init__(self, ...) called with invalid or missing `self` argument\");\n                return nullptr;\n            }\n\n            auto *const tinfo\n                = get_type_info(reinterpret_cast<PyTypeObject *>(overloads->scope.ptr()));\n            auto *const pi = reinterpret_cast<instance *>(parent.ptr());\n            self_value_and_holder = pi->get_value_and_holder(tinfo, true);\n\n            // If this value is already registered it must mean __init__ is invoked multiple times;\n            // we really can't support that in C++, so just ignore the second __init__.\n            if (self_value_and_holder.instance_registered()) {\n                return none().release().ptr();\n            }\n        }\n\n        try {\n            // We do this in two passes: in the first pass, we load arguments with `convert=false`;\n            // in the second, we allow conversion (except for arguments with an explicit\n            // py::arg().noconvert()).  This lets us prefer calls without conversion, with\n            // conversion as a fallback.\n            std::vector<function_call> second_pass;\n\n            // However, if there are no overloads, we can just skip the no-convert pass entirely\n            const bool overloaded\n                = current_overload != nullptr && current_overload->next != nullptr;\n\n            for (; current_overload != nullptr; current_overload = current_overload->next) {\n\n                /* For each overload:\n                   1. Copy all positional arguments we were given, also checking to make sure that\n                      named positional arguments weren't *also* specified via kwarg.\n                   2. If we weren't given enough, try to make up the omitted ones by checking\n                      whether they were provided by a kwarg matching the `py::arg(\"name\")` name. If\n                      so, use it (and remove it from kwargs); if not, see if the function binding\n                      provided a default that we can use.\n                   3. Ensure that either all keyword arguments were \"consumed\", or that the\n                   function takes a kwargs argument to accept unconsumed kwargs.\n                   4. Any positional arguments still left get put into a tuple (for args), and any\n                      leftover kwargs get put into a dict.\n                   5. Pack everything into a vector; if we have py::args or py::kwargs, they are an\n                      extra tuple or dict at the end of the positional arguments.\n                   6. Call the function call dispatcher (function_record::impl)\n\n                   If one of these fail, move on to the next overload and keep trying until we get\n                   a result other than PYBIND11_TRY_NEXT_OVERLOAD.\n                 */\n\n                const function_record &func = *current_overload;\n                size_t num_args = func.nargs; // Number of positional arguments that we need\n                if (func.has_args) {\n                    --num_args; // (but don't count py::args\n                }\n                if (func.has_kwargs) {\n                    --num_args; //  or py::kwargs)\n                }\n                size_t pos_args = func.nargs_pos;\n\n                if (!func.has_args && n_args_in > pos_args) {\n                    continue; // Too many positional arguments for this overload\n                }\n\n                if (n_args_in < pos_args && func.args.size() < pos_args) {\n                    continue; // Not enough positional arguments given, and not enough defaults to\n                              // fill in the blanks\n                }\n\n                function_call call(func, parent);\n\n                // Protect std::min with parentheses\n                size_t args_to_copy = (std::min) (pos_args, n_args_in);\n                size_t args_copied = 0;\n\n                // 0. Inject new-style `self` argument\n                if (func.is_new_style_constructor) {\n                    // The `value` may have been preallocated by an old-style `__init__`\n                    // if it was a preceding candidate for overload resolution.\n                    if (self_value_and_holder) {\n                        self_value_and_holder.type->dealloc(self_value_and_holder);\n                    }\n\n                    call.init_self = args_in_arr[0];\n                    call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));\n                    call.args_convert.push_back(false);\n                    ++args_copied;\n                }\n\n                // 1. Copy any position arguments given.\n                bool bad_arg = false;\n                for (; args_copied < args_to_copy; ++args_copied) {\n                    const argument_record *arg_rec\n                        = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;\n\n                    /* if the argument is listed in the call site's kwargs, but the argument is\n                    also fulfilled positionally, then the call can't match this overload. for\n                    example, the call site is: foo(0, key=1) but our overload is foo(key:int) then\n                    this call can't be for us, because it would be invalid.\n                    */\n                    if (kwnames_in && arg_rec && arg_rec->name\n                        && keyword_index(kwnames_in, arg_rec->name) >= 0) {\n                        bad_arg = true;\n                        break;\n                    }\n\n                    handle arg(args_in_arr[args_copied]);\n                    if (arg_rec && !arg_rec->none && arg.is_none()) {\n                        bad_arg = true;\n                        break;\n                    }\n\n                    call.args.push_back(arg);\n                    call.args_convert.push_back(arg_rec ? arg_rec->convert : true);\n                }\n                if (bad_arg) {\n                    continue; // Maybe it was meant for another overload (issue #688)\n                }\n\n                // Keep track of how many position args we copied out in case we need to come back\n                // to copy the rest into a py::args argument.\n                size_t positional_args_copied = args_copied;\n\n                // 1.5. Fill in any missing pos_only args from defaults if they exist\n                if (args_copied < func.nargs_pos_only) {\n                    for (; args_copied < func.nargs_pos_only; ++args_copied) {\n                        const auto &arg_rec = func.args[args_copied];\n                        if (arg_rec.value) {\n                            call.args.push_back(arg_rec.value);\n                            call.args_convert.push_back(arg_rec.convert);\n                        } else {\n                            break;\n                        }\n                    }\n\n                    if (args_copied < func.nargs_pos_only) {\n                        continue; // Not enough defaults to fill the positional arguments\n                    }\n                }\n\n                // 2. Check kwargs and, failing that, defaults that may help complete the list\n                small_vector<bool, arg_vector_small_size> used_kwargs(\n                    kwnames_in ? static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)) : 0, false);\n                size_t used_kwargs_count = 0;\n                if (args_copied < num_args) {\n                    for (; args_copied < num_args; ++args_copied) {\n                        const auto &arg_rec = func.args[args_copied];\n\n                        handle value;\n                        if (kwnames_in && arg_rec.name) {\n                            ssize_t i = keyword_index(kwnames_in, arg_rec.name);\n                            if (i >= 0) {\n                                value = args_in_arr[n_args_in + static_cast<size_t>(i)];\n                                used_kwargs.set(static_cast<size_t>(i), true);\n                                used_kwargs_count++;\n                            }\n                        }\n\n                        if (!value) {\n                            value = arg_rec.value;\n                            if (!value) {\n                                break;\n                            }\n                        }\n\n                        if (!arg_rec.none && value.is_none()) {\n                            break;\n                        }\n\n                        // If we're at the py::args index then first insert a stub for it to be\n                        // replaced later\n                        if (func.has_args && call.args.size() == func.nargs_pos) {\n                            call.args.push_back(none());\n                        }\n\n                        call.args.push_back(value);\n                        call.args_convert.push_back(arg_rec.convert);\n                    }\n\n                    if (args_copied < num_args) {\n                        continue; // Not enough arguments, defaults, or kwargs to fill the\n                                  // positional arguments\n                    }\n                }\n\n                // 3. Check everything was consumed (unless we have a kwargs arg)\n                if (!func.has_kwargs && used_kwargs_count < used_kwargs.size()) {\n                    continue; // Unconsumed kwargs, but no py::kwargs argument to accept them\n                }\n\n                // 4a. If we have a py::args argument, create a new tuple with leftovers\n                if (func.has_args) {\n                    if (positional_args_copied >= n_args_in) {\n                        call.args_ref = tuple(0);\n                    } else {\n                        size_t args_size = n_args_in - positional_args_copied;\n                        tuple extra_args(args_size);\n                        for (size_t i = 0; i < args_size; ++i) {\n                            extra_args[i] = args_in_arr[positional_args_copied + i];\n                        }\n                        call.args_ref = std::move(extra_args);\n                    }\n                    if (call.args.size() <= func.nargs_pos) {\n                        call.args.push_back(call.args_ref);\n                    } else {\n                        call.args[func.nargs_pos] = call.args_ref;\n                    }\n                    call.args_convert.push_back(false);\n                }\n\n                // 4b. If we have a py::kwargs, pass on any remaining kwargs\n                if (func.has_kwargs) {\n                    dict kwargs;\n                    for (size_t i = 0; i < used_kwargs.size(); ++i) {\n                        if (!used_kwargs[i]) {\n                            // Cast values into handles before indexing into kwargs to ensure\n                            // well-defined evaluation order (MSVC C4866).\n                            handle arg_in_arr = args_in_arr[n_args_in + i],\n                                   kwname = PyTuple_GET_ITEM(kwnames_in, i);\n                            kwargs[kwname] = arg_in_arr;\n                        }\n                    }\n                    call.args.push_back(kwargs);\n                    call.args_convert.push_back(false);\n                    call.kwargs_ref = std::move(kwargs);\n                }\n\n                // 5. Put everything in a vector.  Not technically step 5, we've been building it\n                // in `call.args` all along.\n\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n                if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {\n                    pybind11_fail(\"Internal error: function call dispatcher inserted wrong number \"\n                                  \"of arguments!\");\n                }\n#endif\n\n                args_convert_vector<arg_vector_small_size> second_pass_convert;\n                if (overloaded) {\n                    // We're in the first no-convert pass, so swap out the conversion flags for a\n                    // set of all-false flags.  If the call fails, we'll swap the flags back in for\n                    // the conversion-allowed call below.\n                    second_pass_convert = std::move(call.args_convert);\n                    call.args_convert\n                        = args_convert_vector<arg_vector_small_size>(func.nargs, false);\n                }\n\n                // 6. Call the function.\n                try {\n                    loader_life_support guard{};\n                    result = func.impl(call);\n                } catch (reference_cast_error &) {\n                    result = PYBIND11_TRY_NEXT_OVERLOAD;\n                }\n\n                if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {\n                    break;\n                }\n\n                if (overloaded) {\n                    // The (overloaded) call failed; if the call has at least one argument that\n                    // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)\n                    // then add this call to the list of second pass overloads to try.\n                    for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {\n                        if (second_pass_convert[i]) {\n                            // Found one: swap the converting flags back in and store the call for\n                            // the second pass.\n                            call.args_convert.swap(second_pass_convert);\n                            second_pass.push_back(std::move(call));\n                            break;\n                        }\n                    }\n                }\n            }\n\n            if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {\n                // The no-conversion pass finished without success, try again with conversion\n                // allowed\n                for (auto &call : second_pass) {\n                    try {\n                        loader_life_support guard{};\n                        result = call.func.impl(call);\n                    } catch (reference_cast_error &) {\n                        result = PYBIND11_TRY_NEXT_OVERLOAD;\n                    }\n\n                    if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {\n                        // The error reporting logic below expects 'current_overload' to be valid,\n                        // as it would be if we'd encountered this failure in the first-pass loop.\n                        if (!result) {\n                            current_overload = &call.func;\n                        }\n                        break;\n                    }\n                }\n            }\n        } catch (error_already_set &e) {\n            e.restore();\n            return nullptr;\n#ifdef __GLIBCXX__\n        } catch (abi::__forced_unwind &) {\n            throw;\n#endif\n        } catch (...) {\n            try_translate_exceptions();\n            return nullptr;\n        }\n\n        auto append_note_if_missing_header_is_suspected = [](std::string &msg) {\n            if (msg.find(\"std::\") != std::string::npos) {\n                msg += \"\\n\\n\"\n                       \"Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\\n\"\n                       \"<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\\n\"\n                       \"conversions are optional and require extra headers to be included\\n\"\n                       \"when compiling your pybind11 module.\";\n            }\n        };\n\n        if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {\n            if (overloads->is_operator) {\n                return handle(Py_NotImplemented).inc_ref().ptr();\n            }\n\n            std::string msg = std::string(overloads->name) + \"(): incompatible \"\n                              + std::string(overloads->is_constructor ? \"constructor\" : \"function\")\n                              + \" arguments. The following argument types are supported:\\n\";\n\n            int ctr = 0;\n            for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {\n                msg += \"    \" + std::to_string(++ctr) + \". \";\n\n                bool wrote_sig = false;\n                if (overloads->is_constructor) {\n                    // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as\n                    // `Object(arg0, ...)`\n                    std::string sig = it2->signature;\n                    size_t start = sig.find('(') + 7; // skip \"(self: \"\n                    if (start < sig.size()) {\n                        // End at the , for the next argument\n                        size_t end = sig.find(\", \"), next = end + 2;\n                        size_t ret = sig.rfind(\" -> \");\n                        // Or the ), if there is no comma:\n                        if (end >= sig.size()) {\n                            next = end = sig.find(')');\n                        }\n                        if (start < end && next < sig.size()) {\n                            msg.append(sig, start, end - start);\n                            msg += '(';\n                            msg.append(sig, next, ret - next);\n                            wrote_sig = true;\n                        }\n                    }\n                }\n                if (!wrote_sig) {\n                    msg += it2->signature;\n                }\n\n                msg += '\\n';\n            }\n            msg += \"\\nInvoked with: \";\n            bool some_args = false;\n            for (size_t ti = overloads->is_constructor ? 1 : 0; ti < n_args_in; ++ti) {\n                if (!some_args) {\n                    some_args = true;\n                } else {\n                    msg += \", \";\n                }\n                try {\n                    msg += pybind11::repr(args_in_arr[ti]);\n                } catch (const error_already_set &) {\n                    msg += \"<repr raised Error>\";\n                }\n            }\n            if (kwnames_in && PyTuple_GET_SIZE(kwnames_in) > 0) {\n                if (some_args) {\n                    msg += \"; \";\n                }\n                msg += \"kwargs: \";\n                bool first = true;\n                for (size_t i = 0; i < static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)); ++i) {\n                    if (first) {\n                        first = false;\n                    } else {\n                        msg += \", \";\n                    }\n                    msg += reinterpret_borrow<pybind11::str>(PyTuple_GET_ITEM(kwnames_in, i));\n                    msg += '=';\n                    try {\n                        msg += pybind11::repr(args_in_arr[n_args_in + i]);\n                    } catch (const error_already_set &) {\n                        msg += \"<repr raised Error>\";\n                    }\n                }\n            }\n\n            append_note_if_missing_header_is_suspected(msg);\n            // Attach additional error info to the exception if supported\n            if (PyErr_Occurred()) {\n                // #HelpAppreciated: unit test coverage for this branch.\n                raise_from(PyExc_TypeError, msg.c_str());\n                return nullptr;\n            }\n            set_error(PyExc_TypeError, msg.c_str());\n            return nullptr;\n        }\n        if (!result) {\n            std::string msg = \"Unable to convert function return value to a \"\n                              \"Python type! The signature was\\n\\t\";\n            assert(current_overload != nullptr);\n            msg += current_overload->signature;\n            append_note_if_missing_header_is_suspected(msg);\n            // Attach additional error info to the exception if supported\n            if (PyErr_Occurred()) {\n                raise_from(PyExc_TypeError, msg.c_str());\n                return nullptr;\n            }\n            set_error(PyExc_TypeError, msg.c_str());\n            return nullptr;\n        }\n        if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {\n            auto *pi = reinterpret_cast<instance *>(parent.ptr());\n            self_value_and_holder.type->init_instance(pi, nullptr);\n        }\n        return result.ptr();\n    }\n\n    static ssize_t keyword_index(PyObject *haystack, char const *needle) {\n        /* kwargs is usually very small (<= 5 entries).  The arg strings are typically interned.\n         * CPython itself implements the search this way, first comparing all pointers ... which is\n         * cheap and will work if the strings are interned.  If it fails, then it falls back to a\n         * second lexicographic check. This is wildly expensive for huge argument lists, but those\n         * are incredibly rare so we optimize for the vastly common case of just a couple of args.\n         */\n        auto n = PyTuple_GET_SIZE(haystack);\n        auto s = reinterpret_steal<pybind11::str>(PyUnicode_InternFromString(needle));\n        for (ssize_t i = 0; i < n; ++i) {\n            if (PyTuple_GET_ITEM(haystack, i) == s.ptr()) {\n                return i;\n            }\n        }\n        for (ssize_t i = 0; i < n; ++i) {\n            if (PyUnicode_Compare(PyTuple_GET_ITEM(haystack, i), s.ptr()) == 0) {\n                return i;\n            }\n        }\n        return -1;\n    }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nPYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)\n\n// This implementation needs the definition of `class cpp_function`.\ninline void tp_dealloc_impl(PyObject *self) {\n    auto *py_func_rec = reinterpret_cast<function_record_PyObject *>(self);\n    cpp_function::destruct(py_func_rec->cpp_func_rec);\n    py_func_rec->cpp_func_rec = nullptr;\n}\n\nPYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)\n\ntemplate <>\nstruct handle_type_name<cpp_function> {\n    static constexpr auto name = const_name(\"collections.abc.Callable\");\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n// Use to activate Py_MOD_GIL_NOT_USED.\nclass mod_gil_not_used {\npublic:\n    explicit mod_gil_not_used(bool flag = true) : flag_(flag) {}\n    bool flag() const { return flag_; }\n\nprivate:\n    bool flag_;\n};\n\nclass multiple_interpreters {\npublic:\n    enum class level {\n        not_supported,      /// Use to activate Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED\n        shared_gil,         /// Use to activate Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED\n        per_interpreter_gil /// Use to activate Py_MOD_PER_INTERPRETER_GIL_SUPPORTED\n    };\n\n    static multiple_interpreters not_supported() {\n        return multiple_interpreters(level::not_supported);\n    }\n    static multiple_interpreters shared_gil() { return multiple_interpreters(level::shared_gil); }\n    static multiple_interpreters per_interpreter_gil() {\n        return multiple_interpreters(level::per_interpreter_gil);\n    }\n\n    explicit constexpr multiple_interpreters(level l) : level_(l) {}\n    level value() const { return level_; }\n\nprivate:\n    level level_;\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline bool gil_not_used_option() { return false; }\ntemplate <typename F, typename... O>\nbool gil_not_used_option(F &&, O &&...o);\ntemplate <typename... O>\ninline bool gil_not_used_option(mod_gil_not_used f, O &&...o) {\n    return f.flag() || gil_not_used_option(o...);\n}\ntemplate <typename F, typename... O>\ninline bool gil_not_used_option(F &&, O &&...o) {\n    return gil_not_used_option(o...);\n}\n\n#ifdef Py_mod_multiple_interpreters\ninline void *multi_interp_slot() { return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED; }\ntemplate <typename... O>\ninline void *multi_interp_slot(multiple_interpreters mi, O &&...o) {\n    switch (mi.value()) {\n        case multiple_interpreters::level::per_interpreter_gil:\n            return Py_MOD_PER_INTERPRETER_GIL_SUPPORTED;\n        case multiple_interpreters::level::shared_gil:\n            return Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;\n        case multiple_interpreters::level::not_supported:\n            return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED;\n    }\n    // silence warnings with this unreachable line:\n    return multi_interp_slot(o...);\n}\ntemplate <typename F, typename... O>\ninline void *multi_interp_slot(F &&, O &&...o) {\n    return multi_interp_slot(o...);\n}\n#endif\n\n/*\nReturn a borrowed reference to the named module if it has been successfully initialized within this\ninterpreter before. nullptr if it has not been successfully initialized.\n*/\ninline PyObject *get_cached_module(pybind11::str const &nameobj) {\n    dict state = detail::get_python_state_dict();\n    if (!state.contains(\"__pybind11_module_cache\")) {\n        return nullptr;\n    }\n    dict cache = state[\"__pybind11_module_cache\"];\n    if (!cache.contains(nameobj)) {\n        return nullptr;\n    }\n    return cache[nameobj].ptr();\n}\n\n/*\nAdd successfully initialized a module object to the internal cache.\n\nThe module must have a __spec__ attribute with a name attribute.\n*/\ninline void cache_completed_module(pybind11::object const &mod) {\n    dict state = detail::get_python_state_dict();\n    if (!state.contains(\"__pybind11_module_cache\")) {\n        state[\"__pybind11_module_cache\"] = dict();\n    }\n    state[\"__pybind11_module_cache\"][mod.attr(\"__spec__\").attr(\"name\")] = mod;\n}\n\n/*\nA Py_mod_create slot function which will return the previously created module from the cache if one\nexists, and otherwise will create a new module object.\n*/\ninline PyObject *cached_create_module(PyObject *spec, PyModuleDef *) {\n    (void) &cache_completed_module; // silence unused-function warnings, it is used in a macro\n\n    auto nameobj = getattr(reinterpret_borrow<object>(spec), \"name\", none());\n    if (nameobj.is_none()) {\n        set_error(PyExc_ImportError, \"module spec is missing a name\");\n        return nullptr;\n    }\n\n    auto *mod = get_cached_module(nameobj);\n    if (mod) {\n        Py_INCREF(mod);\n    } else {\n        mod = PyModule_NewObject(nameobj.ptr());\n    }\n    return mod;\n}\n\n/// Must be a POD type, and must hold enough entries for all of the possible slots PLUS ONE for\n/// the sentinel (0) end slot.\nusing slots_array = std::array<PyModuleDef_Slot, 5>;\n\n/// Initialize an array of slots based on the supplied exec slot and options.\ntemplate <typename... Options>\ninline slots_array init_slots(int (*exec_fn)(PyObject *), Options &&...options) noexcept {\n    /* NOTE: slots_array MUST be large enough to hold all possible options.  If you add an option\n    here, you MUST also increase the size of slots_array in the type alias above! */\n    slots_array mod_def_slots;\n    size_t next_slot = 0;\n\n    mod_def_slots[next_slot++] = {Py_mod_create, reinterpret_cast<void *>(&cached_create_module)};\n\n    if (exec_fn != nullptr) {\n        mod_def_slots[next_slot++] = {Py_mod_exec, reinterpret_cast<void *>(exec_fn)};\n    }\n\n#ifdef Py_mod_multiple_interpreters\n    mod_def_slots[next_slot++] = {Py_mod_multiple_interpreters, multi_interp_slot(options...)};\n#endif\n\n    if (gil_not_used_option(options...)) {\n#if defined(Py_mod_gil) && defined(Py_GIL_DISABLED)\n        mod_def_slots[next_slot++] = {Py_mod_gil, Py_MOD_GIL_NOT_USED};\n#endif\n    }\n\n    // slots must have a zero end sentinel\n    mod_def_slots[next_slot++] = {0, nullptr};\n\n    return mod_def_slots;\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Wrapper for Python extension modules\nclass module_ : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)\n\n    /// Create a new top-level Python module with the given name and docstring\n    PYBIND11_DEPRECATED(\"Use PYBIND11_MODULE or module_::create_extension_module instead\")\n    explicit module_(const char *name, const char *doc = nullptr) {\n        *this = create_extension_module(name, doc, new PyModuleDef());\n    }\n\n    /** \\rst\n        Create Python binding for a new function within the module scope. ``Func``\n        can be a plain C++ function, a function pointer, or a lambda function. For\n        details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.\n    \\endrst */\n    template <typename Func, typename... Extra>\n    module_ &def(const char *name_, Func &&f, const Extra &...extra) {\n        cpp_function func(std::forward<Func>(f),\n                          name(name_),\n                          scope(*this),\n                          sibling(getattr(*this, name_, none())),\n                          extra...);\n        // NB: allow overwriting here because cpp_function sets up a chain with the intention of\n        // overwriting (and has already checked internally that it isn't overwriting\n        // non-functions).\n        add_object(name_, func, true /* overwrite */);\n        return *this;\n    }\n\n    /** \\rst\n        Create and return a new Python submodule with the given name and docstring.\n        This also works recursively, i.e.\n\n        .. code-block:: cpp\n\n            py::module_ m(\"example\", \"pybind11 example plugin\");\n            py::module_ m2 = m.def_submodule(\"sub\", \"A submodule of 'example'\");\n            py::module_ m3 = m2.def_submodule(\"subsub\", \"A submodule of 'example.sub'\");\n    \\endrst */\n    module_ def_submodule(const char *name, const char *doc = nullptr) {\n        const char *this_name = PyModule_GetName(m_ptr);\n        if (this_name == nullptr) {\n            throw error_already_set();\n        }\n        std::string full_name = std::string(this_name) + '.' + name;\n        handle submodule = PyImport_AddModule(full_name.c_str());\n        if (!submodule) {\n            throw error_already_set();\n        }\n        auto result = reinterpret_borrow<module_>(submodule);\n        if (doc && options::show_user_defined_docstrings()) {\n            result.attr(\"__doc__\") = pybind11::str(doc);\n        }\n\n#if defined(GRAALVM_PYTHON) && (!defined(GRAALPY_VERSION_NUM) || GRAALPY_VERSION_NUM < 0x190000)\n        // GraalPy doesn't support PyModule_GetFilenameObject,\n        // so getting by attribute (see PR #5584)\n        handle this_module = m_ptr;\n        if (object this_file = getattr(this_module, \"__file__\", none())) {\n            result.attr(\"__file__\") = this_file;\n        }\n#else\n        handle this_file = PyModule_GetFilenameObject(m_ptr);\n        if (this_file) {\n            result.attr(\"__file__\") = this_file;\n        } else if (PyErr_ExceptionMatches(PyExc_SystemError) != 0) {\n            PyErr_Clear();\n        } else {\n            throw error_already_set();\n        }\n#endif\n        attr(name) = result;\n        return result;\n    }\n\n    /// Import and return a module or throws `error_already_set`.\n    static module_ import(const char *name) {\n        PyObject *obj = PyImport_ImportModule(name);\n        if (!obj) {\n            throw error_already_set();\n        }\n        return reinterpret_steal<module_>(obj);\n    }\n\n    /// Reload the module or throws `error_already_set`.\n    void reload() {\n        PyObject *obj = PyImport_ReloadModule(ptr());\n        if (!obj) {\n            throw error_already_set();\n        }\n        *this = reinterpret_steal<module_>(obj);\n    }\n\n    /** \\rst\n        Adds an object to the module using the given name.  Throws if an object with the given name\n        already exists.\n\n        ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11\n        has established will, in most cases, break things.\n    \\endrst */\n    PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {\n        if (!overwrite && hasattr(*this, name)) {\n            pybind11_fail(\n                \"Error during initialization: multiple incompatible definitions with name \\\"\"\n                + std::string(name) + \"\\\"\");\n        }\n\n        PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);\n    }\n\n    // DEPRECATED (since PR #5688): Use PyModuleDef directly instead.\n    using module_def = PyModuleDef;\n\n    /** \\rst\n        Create a new top-level module that can be used as the main module of a C extension.\n\n        ``def`` should point to a statically allocated PyModuleDef.\n    \\endrst */\n    static module_ create_extension_module(const char *name,\n                                           const char *doc,\n                                           PyModuleDef *def,\n                                           mod_gil_not_used gil_not_used\n                                           = mod_gil_not_used(false)) {\n        // Placement new (not an allocation).\n        new (def) PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,\n                              /* m_name */ name,\n                              /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,\n                              /* m_size */ -1,\n                              /* m_methods */ nullptr,\n                              /* m_slots */ nullptr,\n                              /* m_traverse */ nullptr,\n                              /* m_clear */ nullptr,\n                              /* m_free */ nullptr};\n        auto *m = PyModule_Create(def);\n        if (m == nullptr) {\n            if (PyErr_Occurred()) {\n                throw error_already_set();\n            }\n            pybind11_fail(\"Internal error in module_::create_extension_module()\");\n        }\n        if (gil_not_used.flag()) {\n#ifdef Py_GIL_DISABLED\n            PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n#endif\n        }\n        // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when\n        //       returned from PyInit_...\n        //       For Python 2, reinterpret_borrow was correct.\n        return reinterpret_borrow<module_>(m);\n    }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <>\nstruct handle_type_name<module_> {\n    static constexpr auto name = const_name(\"types.ModuleType\");\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\n// When inside a namespace (or anywhere as long as it's not the first item on a line),\n// C++20 allows \"module\" to be used. This is provided for backward compatibility, and for\n// simplicity, if someone wants to use py::module for example, that is perfectly safe.\nusing module = module_;\n\n/// \\ingroup python_builtins\n/// Return a dictionary representing the global variables in the current execution frame,\n/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).\ninline dict globals() {\n#if PY_VERSION_HEX >= 0x030d0000\n    PyObject *p = PyEval_GetFrameGlobals();\n    return p ? reinterpret_steal<dict>(p)\n             : reinterpret_borrow<dict>(module_::import(\"__main__\").attr(\"__dict__\").ptr());\n#else\n    PyObject *p = PyEval_GetGlobals();\n    return reinterpret_borrow<dict>(p ? p : module_::import(\"__main__\").attr(\"__dict__\").ptr());\n#endif\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n/// Generic support for creating new Python heap types\nclass generic_type : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)\nprotected:\n    void initialize(const type_record &rec) {\n        if (rec.scope && hasattr(rec.scope, \"__dict__\")\n            && rec.scope.attr(\"__dict__\").contains(rec.name)) {\n            pybind11_fail(\"generic_type: cannot initialize type \\\"\" + std::string(rec.name)\n                          + \"\\\": an object with that name is already defined\");\n        }\n\n        if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))\n            != nullptr) {\n            pybind11_fail(\"generic_type: type \\\"\" + std::string(rec.name)\n                          + \"\\\" is already registered!\");\n        }\n\n        m_ptr = make_new_python_type(rec);\n\n        /* Register supplemental type information in C++ dict */\n        auto *tinfo = new detail::type_info();\n        tinfo->type = reinterpret_cast<PyTypeObject *>(m_ptr);\n        tinfo->cpptype = rec.type;\n        tinfo->type_size = rec.type_size;\n        tinfo->type_align = rec.type_align;\n        tinfo->operator_new = rec.operator_new;\n        tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);\n        tinfo->init_instance = rec.init_instance;\n        tinfo->dealloc = rec.dealloc;\n        tinfo->get_trampoline_self_life_support = rec.get_trampoline_self_life_support;\n        tinfo->simple_type = true;\n        tinfo->simple_ancestors = true;\n        tinfo->module_local = rec.module_local;\n        tinfo->holder_enum_v = rec.holder_enum_v;\n\n        with_internals([&](internals &internals) {\n            auto tindex = std::type_index(*rec.type);\n            tinfo->direct_conversions = &internals.direct_conversions[tindex];\n            auto &local_internals = get_local_internals();\n            if (rec.module_local) {\n                local_internals.registered_types_cpp[rec.type] = tinfo;\n            } else {\n                internals.registered_types_cpp[tindex] = tinfo;\n#if PYBIND11_INTERNALS_VERSION >= 12\n                internals.registered_types_cpp_fast[rec.type] = tinfo;\n#endif\n            }\n\n            PYBIND11_WARNING_PUSH\n#if defined(__GNUC__) && __GNUC__ == 12\n            // When using GCC 12 these warnings are disabled as they trigger\n            // false positive warnings.  Discussed here:\n            // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115824.\n            PYBIND11_WARNING_DISABLE_GCC(\"-Warray-bounds\")\n            PYBIND11_WARNING_DISABLE_GCC(\"-Wstringop-overread\")\n#endif\n            internals.registered_types_py[reinterpret_cast<PyTypeObject *>(m_ptr)] = {tinfo};\n            PYBIND11_WARNING_POP\n        });\n\n        if (rec.bases.size() > 1 || rec.multiple_inheritance) {\n            mark_parents_nonsimple(tinfo->type);\n            tinfo->simple_ancestors = false;\n        } else if (rec.bases.size() == 1) {\n            auto *parent_tinfo\n                = get_type_info(reinterpret_cast<PyTypeObject *>(rec.bases[0].ptr()));\n            assert(parent_tinfo != nullptr);\n            bool parent_simple_ancestors = parent_tinfo->simple_ancestors;\n            tinfo->simple_ancestors = parent_simple_ancestors;\n            // The parent can no longer be a simple type if it has MI and has a child\n            parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;\n        }\n\n        if (rec.module_local) {\n            // Stash the local typeinfo and loader so that external modules can access it.\n            tinfo->module_local_load = &type_caster_generic::local_load;\n            setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));\n        }\n    }\n\n    /// Helper function which tags all parents of a type using mult. inheritance\n    void mark_parents_nonsimple(PyTypeObject *value) {\n        auto t = reinterpret_borrow<tuple>(value->tp_bases);\n        for (handle h : t) {\n            auto *tinfo2 = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()));\n            if (tinfo2) {\n                tinfo2->simple_type = false;\n            }\n            mark_parents_nonsimple(reinterpret_cast<PyTypeObject *>(h.ptr()));\n        }\n    }\n\n    void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),\n                              void *get_buffer_data) {\n        auto *type = reinterpret_cast<PyHeapTypeObject *>(m_ptr);\n        auto *tinfo = detail::get_type_info(&type->ht_type);\n\n        if (!type->ht_type.tp_as_buffer) {\n            pybind11_fail(\"To be able to register buffer protocol support for the type '\"\n                          + get_fully_qualified_tp_name(tinfo->type)\n                          + \"' the associated class<>(..) invocation must \"\n                            \"include the pybind11::buffer_protocol() annotation!\");\n        }\n\n        tinfo->get_buffer = get_buffer;\n        tinfo->get_buffer_data = get_buffer_data;\n    }\n\n    // rec_func must be set for either fget or fset.\n    void def_property_static_impl(const char *name,\n                                  handle fget,\n                                  handle fset,\n                                  detail::function_record *rec_func) {\n        const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);\n        const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)\n                             && pybind11::options::show_user_defined_docstrings();\n        auto property = handle(reinterpret_cast<PyObject *>(\n            is_static ? get_internals().static_property_type : &PyProperty_Type));\n        attr(name) = property(fget.ptr() ? fget : none(),\n                              fset.ptr() ? fset : none(),\n                              /*deleter*/ none(),\n                              pybind11::str(has_doc ? rec_func->doc : \"\"));\n    }\n};\n\n/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.\ntemplate <typename T,\n          typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>\nvoid set_operator_new(type_record *r) {\n    r->operator_new = &T::operator new;\n}\n\ntemplate <typename>\nvoid set_operator_new(...) {}\n\ntemplate <typename T, typename SFINAE = void>\nstruct has_operator_delete : std::false_type {};\ntemplate <typename T>\nstruct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>\n    : std::true_type {};\ntemplate <typename T, typename SFINAE = void>\nstruct has_operator_delete_size : std::false_type {};\ntemplate <typename T>\nstruct has_operator_delete_size<\n    T,\n    void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {\n};\n/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.\ntemplate <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>\nvoid call_operator_delete(T *p, size_t, size_t) {\n    T::operator delete(p);\n}\ntemplate <typename T,\n          enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>\n          = 0>\nvoid call_operator_delete(T *p, size_t s, size_t) {\n    T::operator delete(p, s);\n}\n\ninline void call_operator_delete(void *p, size_t s, size_t a) {\n    (void) s;\n    (void) a;\n#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)\n    if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {\n#    ifdef __cpp_sized_deallocation\n        ::operator delete(p, s, std::align_val_t(a));\n#    else\n        ::operator delete(p, std::align_val_t(a));\n#    endif\n        return;\n    }\n#endif\n#ifdef __cpp_sized_deallocation\n    ::operator delete(p, s);\n#else\n    ::operator delete(p);\n#endif\n}\n\ninline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {\n    cls.attr(cf.name()) = cf;\n    if (std::strcmp(name_, \"__eq__\") == 0 && !cls.attr(\"__dict__\").contains(\"__hash__\")) {\n        cls.attr(\"__hash__\") = none();\n    }\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Given a pointer to a member function, cast it to its `Derived` version.\n/// Forward everything else unchanged.\ntemplate <typename /*Derived*/, typename F>\nauto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {\n    return std::forward<F>(f);\n}\n\ntemplate <typename Derived, typename Return, typename Class, typename... Args>\nauto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {\n    static_assert(\n        detail::is_accessible_base_of<Class, Derived>::value,\n        \"Cannot bind an inaccessible base class method; use a lambda definition instead\");\n    return pmf;\n}\n\ntemplate <typename Derived, typename Return, typename Class, typename... Args>\nauto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {\n    static_assert(\n        detail::is_accessible_base_of<Class, Derived>::value,\n        \"Cannot bind an inaccessible base class method; use a lambda definition instead\");\n    return pmf;\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Helper for the property_cpp_function static member functions below.\n// The only purpose of these functions is to support .def_readonly & .def_readwrite.\n// In this context, the PM template parameter is certain to be a Pointer to a Member.\n// The main purpose of must_be_member_function_pointer is to make this obvious, and to guard\n// against accidents. As a side-effect, it also explains why the syntactical overhead for\n// perfect forwarding is not needed.\ntemplate <typename PM>\nusing must_be_member_function_pointer = enable_if_t<std::is_member_pointer<PM>::value, int>;\n\n// Note that property_cpp_function is intentionally in the main pybind11 namespace,\n// because user-defined specializations could be useful.\n\n// Classic (non-smart_holder) implementations for .def_readonly and .def_readwrite\n// getter and setter functions.\n// WARNING: This classic implementation can lead to dangling pointers for raw pointer members.\n// See test_ptr() in tests/test_class_sh_property.py\n// However, this implementation works as-is (and safely) for smart_holder std::shared_ptr members.\ntemplate <typename T, typename D>\nstruct property_cpp_function_classic {\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function readonly(PM pm, const handle &hdl) {\n        return cpp_function([pm](const T &c) -> const D & { return c.*pm; }, is_method(hdl));\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function read(PM pm, const handle &hdl) {\n        return readonly(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function write(PM pm, const handle &hdl) {\n        return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename T, typename D, typename SFINAE = void>\nstruct property_cpp_function : detail::property_cpp_function_classic<T, D> {};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename T, typename D, typename SFINAE = void>\nstruct both_t_and_d_use_type_caster_base : std::false_type {};\n\n// `T` is assumed to be equivalent to `intrinsic_t<T>`.\n// `D` is may or may not be equivalent to `intrinsic_t<D>`.\ntemplate <typename T, typename D>\nstruct both_t_and_d_use_type_caster_base<\n    T,\n    D,\n    enable_if_t<all_of<std::is_base_of<type_caster_base<T>, type_caster<T>>,\n                       std::is_base_of<type_caster_base<intrinsic_t<D>>, make_caster<D>>>::value>>\n    : std::true_type {};\n\n// Specialization for raw pointer members, using smart_holder if that is the class_ holder,\n// or falling back to the classic implementation if not.\n// WARNING: Like the classic implementation, this implementation can lead to dangling pointers.\n// See test_ptr() in tests/test_class_sh_property.py\n// However, the read functions return a shared_ptr to the member, emulating the PyCLIF approach:\n// https://github.com/google/clif/blob/c371a6d4b28d25d53a16e6d2a6d97305fb1be25a/clif/python/instance.h#L233\n// This prevents disowning of the Python object owning the raw pointer member.\ntemplate <typename T, typename D>\nstruct property_cpp_function_sh_raw_ptr_member {\n    using drp = typename std::remove_pointer<D>::type;\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function readonly(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function(\n                [pm](handle c_hdl) -> std::shared_ptr<drp> {\n                    std::shared_ptr<T> c_sp\n                        = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(\n                            c_hdl);\n                    D ptr = (*c_sp).*pm;\n                    return std::shared_ptr<drp>(c_sp, ptr);\n                },\n                is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::readonly(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function read(PM pm, const handle &hdl) {\n        return readonly(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function write(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function([pm](T &c, D value) { c.*pm = std::forward<D>(std::move(value)); },\n                                is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::write(pm, hdl);\n    }\n};\n\n// Specialization for members held by-value, using smart_holder if that is the class_ holder,\n// or falling back to the classic implementation if not.\n// The read functions return a shared_ptr to the member, emulating the PyCLIF approach:\n// https://github.com/google/clif/blob/c371a6d4b28d25d53a16e6d2a6d97305fb1be25a/clif/python/instance.h#L233\n// This prevents disowning of the Python object owning the member.\ntemplate <typename T, typename D>\nstruct property_cpp_function_sh_member_held_by_value {\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function readonly(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function(\n                [pm](handle c_hdl) -> std::shared_ptr<typename std::add_const<D>::type> {\n                    std::shared_ptr<T> c_sp\n                        = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(\n                            c_hdl);\n                    return std::shared_ptr<typename std::add_const<D>::type>(c_sp,\n                                                                             &(c_sp.get()->*pm));\n                },\n                is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::readonly(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function read(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function(\n                [pm](handle c_hdl) -> std::shared_ptr<D> {\n                    std::shared_ptr<T> c_sp\n                        = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(\n                            c_hdl);\n                    return std::shared_ptr<D>(c_sp, &(c_sp.get()->*pm));\n                },\n                is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::read(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function write(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::write(pm, hdl);\n    }\n};\n\n// Specialization for std::unique_ptr members, using smart_holder if that is the class_ holder,\n// or falling back to the classic implementation if not.\n// read disowns the member unique_ptr.\n// write disowns the passed Python object.\n// readonly is disabled (static_assert) because there is no safe & intuitive way to make the member\n// accessible as a Python object without disowning the member unique_ptr. A .def_readonly disowning\n// the unique_ptr member is deemed highly prone to misunderstandings.\ntemplate <typename T, typename D>\nstruct property_cpp_function_sh_unique_ptr_member {\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function readonly(PM, const handle &) {\n        static_assert(!is_instantiation<std::unique_ptr, D>::value,\n                      \"def_readonly cannot be used for std::unique_ptr members.\");\n        return cpp_function{}; // Unreachable.\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function read(PM pm, const handle &hdl) {\n        type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);\n        if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {\n            return cpp_function(\n                [pm](handle c_hdl) -> D {\n                    std::shared_ptr<T> c_sp\n                        = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(\n                            c_hdl);\n                    return D{std::move(c_sp.get()->*pm)};\n                },\n                is_method(hdl));\n        }\n        return property_cpp_function_classic<T, D>::read(pm, hdl);\n    }\n\n    template <typename PM, must_be_member_function_pointer<PM> = 0>\n    static cpp_function write(PM pm, const handle &hdl) {\n        return cpp_function([pm](T &c, D &&value) { c.*pm = std::move(value); }, is_method(hdl));\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename T, typename D>\nstruct property_cpp_function<\n    T,\n    D,\n    detail::enable_if_t<detail::all_of<std::is_pointer<D>,\n                                       detail::both_t_and_d_use_type_caster_base<T, D>>::value>>\n    : detail::property_cpp_function_sh_raw_ptr_member<T, D> {};\n\ntemplate <typename T, typename D>\nstruct property_cpp_function<T,\n                             D,\n                             detail::enable_if_t<detail::all_of<\n                                 detail::none_of<std::is_pointer<D>,\n                                                 std::is_array<D>,\n                                                 detail::is_instantiation<std::unique_ptr, D>,\n                                                 detail::is_instantiation<std::shared_ptr, D>>,\n                                 detail::both_t_and_d_use_type_caster_base<T, D>>::value>>\n    : detail::property_cpp_function_sh_member_held_by_value<T, D> {};\n\ntemplate <typename T, typename D>\nstruct property_cpp_function<\n    T,\n    D,\n    detail::enable_if_t<detail::all_of<\n        detail::is_instantiation<std::unique_ptr, D>,\n        detail::both_t_and_d_use_type_caster_base<T, typename D::element_type>>::value>>\n    : detail::property_cpp_function_sh_unique_ptr_member<T, D> {};\n\n#ifdef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE\n// NOTE: THIS IS MEANT FOR STRESS-TESTING OR TRIAGING ONLY!\n//       Running the pybind11 unit tests with smart_holder as the default holder is to ensure\n//       that `py::smart_holder` / `py::classh` is backward-compatible with all pre-existing\n//       functionality.\n//       Be careful not to link translation units compiled with different default holders, because\n//       this will cause ODR violations (https://en.wikipedia.org/wiki/One_Definition_Rule).\ntemplate <typename>\nusing default_holder_type = smart_holder;\n#else\ntemplate <typename T>\nusing default_holder_type = std::unique_ptr<T>;\n#endif\n\ntemplate <typename type_, typename... options>\nclass class_ : public detail::generic_type {\n    template <typename T>\n    using is_holder = detail::is_holder_type<type_, T>;\n    template <typename T>\n    using is_subtype = detail::is_strict_base_of<type_, T>;\n    template <typename T>\n    using is_base = detail::is_strict_base_of<T, type_>;\n    // struct instead of using here to help MSVC:\n    template <typename T>\n    struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};\n\npublic:\n    using type = type_;\n    using type_alias = detail::exactly_one_t<is_subtype, void, options...>;\n    constexpr static bool has_alias = !std::is_void<type_alias>::value;\n    using holder_type = detail::exactly_one_t<is_holder, default_holder_type<type>, options...>;\n\n    static_assert(detail::all_of<is_valid_class_option<options>...>::value,\n                  \"Unknown/invalid class_ template parameters provided\");\n\n    static_assert(!has_alias || std::is_polymorphic<type>::value,\n                  \"Cannot use an alias class (aka trampoline) with a non-polymorphic type\");\n\n#ifndef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE\n    static_assert(!has_alias || !detail::is_smart_holder<holder_type>::value\n                      || std::is_base_of<trampoline_self_life_support, type_alias>::value,\n                  \"Alias class (aka trampoline) must inherit from\"\n                  \" pybind11::trampoline_self_life_support if used in combination with\"\n                  \" pybind11::smart_holder\");\n#endif\n    static_assert(!has_alias || detail::is_smart_holder<holder_type>::value\n                      || !std::is_base_of<trampoline_self_life_support, type_alias>::value,\n                  \"pybind11::trampoline_self_life_support is a smart_holder feature, therefore\"\n                  \" an alias class (aka trampoline) should inherit from\"\n                  \" pybind11::trampoline_self_life_support only if used in combination with\"\n                  \" pybind11::smart_holder\");\n\n    PYBIND11_OBJECT(class_, generic_type, PyType_Check)\n\n    template <typename... Extra>\n    class_(handle scope, const char *name, const Extra &...extra) {\n        using namespace detail;\n\n        // MI can only be specified via class_ template options, not constructor parameters\n        static_assert(\n            none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:\n                (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base\n                 constexpr_sum(is_base<options>::value...) == 0 &&   // no template option bases\n                 // no multiple_inheritance attr\n                 none_of<std::is_same<multiple_inheritance, Extra>...>::value),\n            \"Error: multiple inheritance bases must be specified via class_ template options\");\n\n        type_record record;\n        record.scope = scope;\n        record.name = name;\n        record.type = &typeid(type);\n        record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);\n        record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);\n        record.holder_size = sizeof(holder_type);\n        record.init_instance = init_instance;\n\n        if (detail::is_instantiation<std::unique_ptr, holder_type>::value) {\n            record.holder_enum_v = detail::holder_enum_t::std_unique_ptr;\n        } else if (detail::is_instantiation<std::shared_ptr, holder_type>::value) {\n            record.holder_enum_v = detail::holder_enum_t::std_shared_ptr;\n        } else if (std::is_same<holder_type, smart_holder>::value) {\n            record.holder_enum_v = detail::holder_enum_t::smart_holder;\n        } else {\n            record.holder_enum_v = detail::holder_enum_t::custom_holder;\n        }\n\n        set_operator_new<type>(&record);\n\n        /* Register base classes specified via template arguments to class_, if any */\n        PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));\n\n        /* Process optional arguments, if any */\n        process_attributes<Extra...>::init(extra..., &record);\n\n        if (record.release_gil_before_calling_cpp_dtor) {\n            record.dealloc = dealloc_release_gil_before_calling_cpp_dtor;\n        } else {\n            record.dealloc = dealloc_without_manipulating_gil;\n        }\n\n        if (std::is_base_of<trampoline_self_life_support, type_alias>::value) {\n            // Store a cross-DSO-safe getter.\n            // This lambda is defined in the same DSO that instantiates\n            // class_<type, alias_type>, but it can be called safely from any other DSO.\n            record.get_trampoline_self_life_support = [](void *type_ptr) {\n                return dynamic_raw_ptr_cast_if_possible<trampoline_self_life_support>(\n                    static_cast<type *>(type_ptr));\n            };\n        }\n\n        generic_type::initialize(record);\n\n        if (has_alias) {\n            with_internals([&](internals &internals) {\n                auto &local_internals = get_local_internals();\n                if (record.module_local) {\n                    local_internals.registered_types_cpp[&typeid(type_alias)]\n                        = local_internals.registered_types_cpp[&typeid(type)];\n                } else {\n                    type_info *const val\n                        = internals.registered_types_cpp[std::type_index(typeid(type))];\n                    internals.registered_types_cpp[std::type_index(typeid(type_alias))] = val;\n#if PYBIND11_INTERNALS_VERSION >= 12\n                    internals.registered_types_cpp_fast[&typeid(type_alias)] = val;\n#endif\n                }\n            });\n        }\n        def(\"_pybind11_conduit_v1_\", cpp_conduit_method);\n    }\n\n    template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>\n    static void add_base(detail::type_record &rec) {\n        rec.add_base(typeid(Base), [](void *src) -> void * {\n            return static_cast<Base *>(reinterpret_cast<type *>(src));\n        });\n    }\n\n    template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>\n    static void add_base(detail::type_record &) {}\n\n    template <typename Func, typename... Extra>\n    PYBIND11_ALWAYS_INLINE class_ &def(const char *name_, Func &&f, const Extra &...extra) {\n        cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),\n                        name(name_),\n                        is_method(*this),\n                        sibling(getattr(*this, name_, none())),\n                        extra...);\n        add_class_method(*this, name_, cf);\n        return *this;\n    }\n\n    template <typename Func, typename... Extra>\n    class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {\n        static_assert(!std::is_member_function_pointer<Func>::value,\n                      \"def_static(...) called with a non-static member function pointer\");\n        cpp_function cf(std::forward<Func>(f),\n                        name(name_),\n                        scope(*this),\n                        sibling(getattr(*this, name_, none())),\n                        extra...);\n        auto cf_name = cf.name();\n        attr(std::move(cf_name)) = staticmethod(std::move(cf));\n        return *this;\n    }\n\n    template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>\n    class_ &def(const T &op, const Extra &...extra) {\n        op.execute(*this, extra...);\n        return *this;\n    }\n\n    template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>\n    class_ &def_cast(const T &op, const Extra &...extra) {\n        op.execute_cast(*this, extra...);\n        return *this;\n    }\n\n    template <typename... Args, typename... Extra>\n    class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);\n        init.execute(*this, extra...);\n        return *this;\n    }\n\n    template <typename... Args, typename... Extra>\n    class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {\n        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);\n        init.execute(*this, extra...);\n        return *this;\n    }\n\n    template <typename... Args, typename... Extra>\n    class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {\n        std::move(init).execute(*this, extra...);\n        return *this;\n    }\n\n    template <typename... Args, typename... Extra>\n    class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {\n        std::move(pf).execute(*this, extra...);\n        return *this;\n    }\n\n    template <typename Func>\n    class_ &def_buffer(Func &&func) {\n        struct capture {\n            Func func;\n        };\n        auto *ptr = new capture{std::forward<Func>(func)};\n        install_buffer_funcs(\n            [](PyObject *obj, void *ptr) -> buffer_info * {\n                detail::make_caster<type> caster;\n                if (!caster.load(obj, false)) {\n                    return nullptr;\n                }\n                return new buffer_info(((capture *) ptr)->func(std::move(caster)));\n            },\n            ptr);\n        weakref(m_ptr, cpp_function([ptr](handle wr) {\n                    delete ptr;\n                    wr.dec_ref();\n                }))\n            .release();\n        return *this;\n    }\n\n    template <typename Return, typename Class, typename... Args>\n    class_ &def_buffer(Return (Class::*func)(Args...)) {\n        return def_buffer([func](type &obj) { return (obj.*func)(); });\n    }\n\n    template <typename Return, typename Class, typename... Args>\n    class_ &def_buffer(Return (Class::*func)(Args...) const) {\n        return def_buffer([func](const type &obj) { return (obj.*func)(); });\n    }\n\n    template <typename C, typename D, typename... Extra>\n    class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {\n        static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,\n                      \"def_readwrite() requires a class member (or base class member)\");\n        def_property(name,\n                     property_cpp_function<type, D>::read(pm, *this),\n                     property_cpp_function<type, D>::write(pm, *this),\n                     return_value_policy::reference_internal,\n                     extra...);\n        return *this;\n    }\n\n    template <typename C, typename D, typename... Extra>\n    class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {\n        static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,\n                      \"def_readonly() requires a class member (or base class member)\");\n        def_property_readonly(name,\n                              property_cpp_function<type, D>::readonly(pm, *this),\n                              return_value_policy::reference_internal,\n                              extra...);\n        return *this;\n    }\n\n    template <typename D, typename... Extra>\n    class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {\n        cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),\n            fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));\n        def_property_static(name, fget, fset, return_value_policy::reference, extra...);\n        return *this;\n    }\n\n    template <typename D, typename... Extra>\n    class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {\n        cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));\n        def_property_readonly_static(name, fget, return_value_policy::reference, extra...);\n        return *this;\n    }\n\n    /// Uses return_value_policy::reference_internal by default\n    template <typename Getter, typename... Extra>\n    class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {\n        return def_property_readonly(name,\n                                     cpp_function(method_adaptor<type>(fget)),\n                                     return_value_policy::reference_internal,\n                                     extra...);\n    }\n\n    /// Uses cpp_function's return_value_policy by default\n    template <typename... Extra>\n    class_ &\n    def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {\n        return def_property(name, fget, nullptr, extra...);\n    }\n\n    /// Uses return_value_policy::reference by default\n    template <typename Getter, typename... Extra>\n    class_ &\n    def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {\n        return def_property_readonly_static(\n            name, cpp_function(fget), return_value_policy::reference, extra...);\n    }\n\n    /// Uses cpp_function's return_value_policy by default\n    template <typename... Extra>\n    class_ &def_property_readonly_static(const char *name,\n                                         const cpp_function &fget,\n                                         const Extra &...extra) {\n        return def_property_static(name, fget, nullptr, extra...);\n    }\n\n    /// Uses return_value_policy::reference_internal by default\n    template <typename Getter, typename Setter, typename... Extra>\n    class_ &\n    def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {\n        return def_property(\n            name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);\n    }\n    template <typename Getter, typename... Extra>\n    class_ &def_property(const char *name,\n                         const Getter &fget,\n                         const cpp_function &fset,\n                         const Extra &...extra) {\n        return def_property(name,\n                            cpp_function(method_adaptor<type>(fget)),\n                            fset,\n                            return_value_policy::reference_internal,\n                            extra...);\n    }\n\n    /// Uses cpp_function's return_value_policy by default\n    template <typename... Extra>\n    class_ &def_property(const char *name,\n                         const cpp_function &fget,\n                         const cpp_function &fset,\n                         const Extra &...extra) {\n        return def_property_static(name, fget, fset, is_method(*this), extra...);\n    }\n\n    /// Uses return_value_policy::reference by default\n    template <typename Getter, typename... Extra>\n    class_ &def_property_static(const char *name,\n                                const Getter &fget,\n                                const cpp_function &fset,\n                                const Extra &...extra) {\n        return def_property_static(\n            name, cpp_function(fget), fset, return_value_policy::reference, extra...);\n    }\n\n    /// Uses cpp_function's return_value_policy by default\n    template <typename... Extra>\n    class_ &def_property_static(const char *name,\n                                const cpp_function &fget,\n                                const cpp_function &fset,\n                                const Extra &...extra) {\n        static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),\n                      \"Argument annotations are not allowed for properties\");\n        static_assert(0 == detail::constexpr_sum(detail::is_call_guard<Extra>::value...),\n                      \"def_property family does not currently support call_guard. Use a \"\n                      \"py::cpp_function instead.\");\n        static_assert(0 == detail::constexpr_sum(detail::is_keep_alive<Extra>::value...),\n                      \"def_property family does not currently support keep_alive. Use a \"\n                      \"py::cpp_function instead.\");\n        auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);\n        auto *rec_active = rec_fget;\n        if (rec_fget) {\n            char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific\n                                               documentation string */\n            detail::process_attributes<Extra...>::init(extra..., rec_fget);\n            if (rec_fget->doc && rec_fget->doc != doc_prev) {\n                std::free(doc_prev);\n                rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);\n            }\n        }\n        if (rec_fset) {\n            char *doc_prev = rec_fset->doc;\n            detail::process_attributes<Extra...>::init(extra..., rec_fset);\n            if (rec_fset->doc && rec_fset->doc != doc_prev) {\n                std::free(doc_prev);\n                rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);\n            }\n            if (!rec_active) {\n                rec_active = rec_fset;\n            }\n        }\n        def_property_static_impl(name, fget, fset, rec_active);\n        return *this;\n    }\n\nprivate:\n    /// Initialize holder object, variant 1: object derives from enable_shared_from_this\n    template <typename T>\n    static void init_holder(detail::instance *inst,\n                            detail::value_and_holder &v_h,\n                            const holder_type * /* unused */,\n                            const std::enable_shared_from_this<T> * /* dummy */) {\n\n        auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(\n            detail::try_get_shared_from_this(v_h.value_ptr<type>()));\n        if (sh) {\n            new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));\n            v_h.set_holder_constructed();\n        }\n\n        if (!v_h.holder_constructed() && inst->owned) {\n            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());\n            v_h.set_holder_constructed();\n        }\n    }\n\n    static void init_holder_from_existing(const detail::value_and_holder &v_h,\n                                          const holder_type *holder_ptr,\n                                          std::true_type /*is_copy_constructible*/) {\n        new (std::addressof(v_h.holder<holder_type>())) holder_type(*holder_ptr);\n    }\n\n    static void init_holder_from_existing(const detail::value_and_holder &v_h,\n                                          const holder_type *holder_ptr,\n                                          std::false_type /*is_copy_constructible*/) {\n        new (std::addressof(v_h.holder<holder_type>()))\n            holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));\n    }\n\n    /// Initialize holder object, variant 2: try to construct from existing holder object, if\n    /// possible\n    static void init_holder(detail::instance *inst,\n                            detail::value_and_holder &v_h,\n                            const holder_type *holder_ptr,\n                            const void * /* dummy -- not enable_shared_from_this<T>) */) {\n        if (holder_ptr) {\n            init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());\n            v_h.set_holder_constructed();\n        } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {\n            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());\n            v_h.set_holder_constructed();\n        }\n    }\n\n    /// Performs instance initialization including constructing a holder and registering the known\n    /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes\n    /// an optional pointer to an existing holder to use; if not specified and the instance is\n    /// `.owned`, a new holder will be constructed to manage the value pointer.\n    template <typename H = holder_type,\n              detail::enable_if_t<!detail::is_smart_holder<H>::value, int> = 0>\n    static void init_instance(detail::instance *inst, const void *holder_ptr) {\n        auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));\n        if (!v_h.instance_registered()) {\n            register_instance(inst, v_h.value_ptr(), v_h.type);\n            v_h.set_instance_registered();\n        }\n        init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());\n    }\n\n    template <typename WrappedType>\n    static bool try_initialization_using_shared_from_this(holder_type *, WrappedType *, ...) {\n        return false;\n    }\n\n    // Adopting existing approach used by type_caster_base, although it leads to somewhat fuzzy\n    // ownership semantics: if we detected via shared_from_this that a shared_ptr exists already,\n    // it is reused, irrespective of the return_value_policy in effect.\n    // \"SomeBaseOfWrappedType\" is needed because std::enable_shared_from_this is not necessarily a\n    // direct base of WrappedType.\n    template <typename WrappedType, typename SomeBaseOfWrappedType>\n    static bool try_initialization_using_shared_from_this(\n        holder_type *uninitialized_location,\n        WrappedType *value_ptr_w_t,\n        const std::enable_shared_from_this<SomeBaseOfWrappedType> *) {\n        auto shd_ptr = std::dynamic_pointer_cast<WrappedType>(\n            detail::try_get_shared_from_this(value_ptr_w_t));\n        if (!shd_ptr) {\n            return false;\n        }\n        // Note: inst->owned ignored.\n        new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr));\n        return true;\n    }\n\n    template <typename H = holder_type,\n              detail::enable_if_t<detail::is_smart_holder<H>::value, int> = 0>\n    static void init_instance(detail::instance *inst, const void *holder_const_void_ptr) {\n        // Need for const_cast is a consequence of the type_info::init_instance type:\n        // void (*init_instance)(instance *, const void *);\n        auto *holder_void_ptr = const_cast<void *>(holder_const_void_ptr);\n\n        auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));\n        if (!v_h.instance_registered()) {\n            register_instance(inst, v_h.value_ptr(), v_h.type);\n            v_h.set_instance_registered();\n        }\n        auto *uninitialized_location = std::addressof(v_h.holder<holder_type>());\n        auto *value_ptr_w_t = v_h.value_ptr<type>();\n        // Try downcast from `type` to `type_alias`:\n        inst->is_alias\n            = detail::dynamic_raw_ptr_cast_if_possible<type_alias>(value_ptr_w_t) != nullptr;\n        if (holder_void_ptr) {\n            // Note: inst->owned ignored.\n            auto *holder_ptr = static_cast<holder_type *>(holder_void_ptr);\n            new (uninitialized_location) holder_type(std::move(*holder_ptr));\n        } else if (!try_initialization_using_shared_from_this(\n                       uninitialized_location, value_ptr_w_t, value_ptr_w_t)) {\n            if (inst->owned) {\n                new (uninitialized_location) holder_type(holder_type::from_raw_ptr_take_ownership(\n                    value_ptr_w_t, /*void_cast_raw_ptr*/ inst->is_alias));\n            } else {\n                new (uninitialized_location)\n                    holder_type(holder_type::from_raw_ptr_unowned(value_ptr_w_t));\n            }\n        }\n        v_h.set_holder_constructed();\n    }\n\n    // Deallocates an instance; via holder, if constructed; otherwise via operator delete.\n    // NOTE: The Python error indicator needs to cleared BEFORE this function is called.\n    // This is because we could be deallocating while cleaning up after a Python exception.\n    // If the error indicator is not cleared but the C++ destructor code makes Python C API\n    // calls, those calls are likely to generate a new exception, and pybind11 will then\n    // throw `error_already_set` from the C++ destructor. This is forbidden and will\n    // trigger std::terminate().\n    static void dealloc_impl(detail::value_and_holder &v_h) {\n        if (v_h.holder_constructed()) {\n            v_h.holder<holder_type>().~holder_type();\n            v_h.set_holder_constructed(false);\n        } else {\n            detail::call_operator_delete(\n                v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);\n        }\n        v_h.value_ptr() = nullptr;\n    }\n\n    static void dealloc_without_manipulating_gil(detail::value_and_holder &v_h) {\n        error_scope scope;\n        dealloc_impl(v_h);\n    }\n\n    static void dealloc_release_gil_before_calling_cpp_dtor(detail::value_and_holder &v_h) {\n        error_scope scope;\n        // Intentionally not using `gil_scoped_release` because the non-simple\n        // version unconditionally calls `get_internals()`.\n        // `Py_BEGIN_ALLOW_THREADS`, `Py_END_ALLOW_THREADS` cannot be used\n        // because those macros include `{` and `}`.\n        PyThreadState *py_ts = PyEval_SaveThread();\n        try {\n            dealloc_impl(v_h);\n        } catch (...) {\n            // This code path is expected to be unreachable unless there is a\n            // bug in pybind11 itself.\n            // An alternative would be to mark this function, or\n            // `dealloc_impl()`, with `nothrow`, but that would be a subtle\n            // behavior change and could make debugging more difficult.\n            PyEval_RestoreThread(py_ts);\n            throw;\n        }\n        PyEval_RestoreThread(py_ts);\n    }\n\n    static detail::function_record *get_function_record(handle h) {\n        h = detail::get_function(h);\n        if (!h) {\n            return nullptr;\n        }\n\n        handle func_self = PyCFunction_GET_SELF(h.ptr());\n        if (!func_self) {\n            throw error_already_set();\n        }\n        return detail::function_record_ptr_from_PyObject(func_self.ptr());\n    }\n};\n\n// Supports easier switching between py::class_<T> and py::class_<T, py::smart_holder>:\n// users can simply replace the `_` in `class_` with `h` or vice versa.\ntemplate <typename type_, typename... options>\nusing classh = class_<type_, smart_holder, options...>;\n\n/// Binds an existing constructor taking arguments Args...\ntemplate <typename... Args>\ndetail::initimpl::constructor<Args...> init() {\n    return {};\n}\n/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even\n/// when not inheriting on the Python side).\ntemplate <typename... Args>\ndetail::initimpl::alias_constructor<Args...> init_alias() {\n    return {};\n}\n\n/// Binds a factory function as a constructor\ntemplate <typename Func, typename Ret = detail::initimpl::factory<Func>>\nRet init(Func &&f) {\n    return {std::forward<Func>(f)};\n}\n\n/// Dual-argument factory function: the first function is called when no alias is needed, the\n/// second when an alias is needed (i.e. due to python-side inheritance).  Arguments must be\n/// identical.\ntemplate <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>\nRet init(CFunc &&c, AFunc &&a) {\n    return {std::forward<CFunc>(c), std::forward<AFunc>(a)};\n}\n\n/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type\n/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.\ntemplate <typename GetState, typename SetState>\ndetail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {\n    return {std::forward<GetState>(g), std::forward<SetState>(s)};\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline str enum_name(handle arg) {\n    dict entries = type::handle_of(arg).attr(\"__entries\");\n    for (auto kv : entries) {\n        if (handle(kv.second[int_(0)]).equal(arg)) {\n            return pybind11::str(kv.first);\n        }\n    }\n    return \"???\";\n}\n\nstruct enum_base {\n    enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}\n\n    PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {\n        m_base.attr(\"__entries\") = dict();\n        auto property = handle(reinterpret_cast<PyObject *>(&PyProperty_Type));\n        auto static_property\n            = handle(reinterpret_cast<PyObject *>(get_internals().static_property_type));\n\n        m_base.attr(\"__repr__\") = cpp_function(\n            [](const object &arg) -> str {\n                handle type = type::handle_of(arg);\n                object type_name = type.attr(\"__name__\");\n                return pybind11::str(\"<{}.{}: {}>\")\n                    .format(std::move(type_name), enum_name(arg), int_(arg));\n            },\n            name(\"__repr__\"),\n            is_method(m_base),\n            pos_only());\n\n        m_base.attr(\"name\")\n            = property(cpp_function(&enum_name, name(\"name\"), is_method(m_base), pos_only()));\n\n        m_base.attr(\"__str__\") = cpp_function(\n            [](handle arg) -> str {\n                object type_name = type::handle_of(arg).attr(\"__name__\");\n                return pybind11::str(\"{}.{}\").format(std::move(type_name), enum_name(arg));\n            },\n            name(\"__str__\"),\n            is_method(m_base),\n            pos_only());\n\n        if (options::show_enum_members_docstring()) {\n            m_base.attr(\"__doc__\") = static_property(\n                cpp_function(\n                    [](handle arg) -> std::string {\n                        std::string docstring;\n                        dict entries = arg.attr(\"__entries\");\n                        if ((reinterpret_cast<PyTypeObject *>(arg.ptr()))->tp_doc) {\n                            docstring += std::string(\n                                reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);\n                            docstring += \"\\n\\n\";\n                        }\n                        docstring += \"Members:\";\n                        for (auto kv : entries) {\n                            auto key = std::string(pybind11::str(kv.first));\n                            auto comment = kv.second[int_(1)];\n                            docstring += \"\\n\\n  \";\n                            docstring += key;\n                            if (!comment.is_none()) {\n                                docstring += \" : \";\n                                docstring += pybind11::str(comment).cast<std::string>();\n                            }\n                        }\n                        return docstring;\n                    },\n                    name(\"__doc__\")),\n                none(),\n                none(),\n                \"\");\n        }\n\n        m_base.attr(\"__members__\") = static_property(cpp_function(\n                                                         [](handle arg) -> dict {\n                                                             dict entries = arg.attr(\"__entries\"),\n                                                                  m;\n                                                             for (auto kv : entries) {\n                                                                 m[kv.first] = kv.second[int_(0)];\n                                                             }\n                                                             return m;\n                                                         },\n                                                         name(\"__members__\")),\n                                                     none(),\n                                                     none(),\n                                                     \"\");\n\n#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                                        \\\n    m_base.attr(op) = cpp_function(                                                               \\\n        [](const object &a, const object &b) {                                                    \\\n            if (!type::handle_of(a).is(type::handle_of(b)))                                       \\\n                strict_behavior; /* NOLINT(bugprone-macro-parentheses) */                         \\\n            return expr;                                                                          \\\n        },                                                                                        \\\n        name(op),                                                                                 \\\n        is_method(m_base),                                                                        \\\n        arg(\"other\"),                                                                             \\\n        pos_only())\n\n#define PYBIND11_ENUM_OP_CONV(op, expr)                                                           \\\n    m_base.attr(op) = cpp_function(                                                               \\\n        [](const object &a_, const object &b_) {                                                  \\\n            int_ a(a_), b(b_);                                                                    \\\n            return expr;                                                                          \\\n        },                                                                                        \\\n        name(op),                                                                                 \\\n        is_method(m_base),                                                                        \\\n        arg(\"other\"),                                                                             \\\n        pos_only())\n\n#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)                                                       \\\n    m_base.attr(op) = cpp_function(                                                               \\\n        [](const object &a_, const object &b) {                                                   \\\n            int_ a(a_);                                                                           \\\n            return expr;                                                                          \\\n        },                                                                                        \\\n        name(op),                                                                                 \\\n        is_method(m_base),                                                                        \\\n        arg(\"other\"),                                                                             \\\n        pos_only())\n\n        if (is_convertible) {\n            if (is_arithmetic) {\n                m_base.attr(\"__invert__\")\n                    = cpp_function([](const object &arg) { return ~(int_(arg)); },\n                                   name(\"__invert__\"),\n                                   is_method(m_base),\n                                   pos_only());\n            }\n        }\n\n#undef PYBIND11_ENUM_OP_CONV_LHS\n#undef PYBIND11_ENUM_OP_CONV\n#undef PYBIND11_ENUM_OP_STRICT\n\n        m_base.attr(\"__getstate__\") = cpp_function([](const object &arg) { return int_(arg); },\n                                                   name(\"__getstate__\"),\n                                                   is_method(m_base),\n                                                   pos_only());\n\n        m_base.attr(\"__hash__\") = cpp_function([](const object &arg) { return int_(arg); },\n                                               name(\"__hash__\"),\n                                               is_method(m_base),\n                                               pos_only());\n    }\n\n    PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {\n        dict entries = m_base.attr(\"__entries\");\n        str name(name_);\n        if (entries.contains(name)) {\n            std::string type_name = std::string(str(m_base.attr(\"__name__\")));\n            throw value_error(std::move(type_name) + \": element \\\"\" + std::string(name_)\n                              + \"\\\" already exists!\");\n        }\n\n        entries[name] = pybind11::make_tuple(value, doc);\n        m_base.attr(std::move(name)) = std::move(value);\n    }\n\n    PYBIND11_NOINLINE void export_values() {\n        dict entries = m_base.attr(\"__entries\");\n        for (auto kv : entries) {\n            m_parent.attr(kv.first) = kv.second[int_(0)];\n        }\n    }\n\n    handle m_base;\n    handle m_parent;\n};\n\ntemplate <bool is_signed, size_t length>\nstruct equivalent_integer {};\ntemplate <>\nstruct equivalent_integer<true, 1> {\n    using type = int8_t;\n};\ntemplate <>\nstruct equivalent_integer<false, 1> {\n    using type = uint8_t;\n};\ntemplate <>\nstruct equivalent_integer<true, 2> {\n    using type = int16_t;\n};\ntemplate <>\nstruct equivalent_integer<false, 2> {\n    using type = uint16_t;\n};\ntemplate <>\nstruct equivalent_integer<true, 4> {\n    using type = int32_t;\n};\ntemplate <>\nstruct equivalent_integer<false, 4> {\n    using type = uint32_t;\n};\ntemplate <>\nstruct equivalent_integer<true, 8> {\n    using type = int64_t;\n};\ntemplate <>\nstruct equivalent_integer<false, 8> {\n    using type = uint64_t;\n};\n\ntemplate <typename IntLike>\nusing equivalent_integer_t =\n    typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Binds C++ enumerations and enumeration classes to Python\ntemplate <typename Type>\nclass enum_ : public class_<Type> {\npublic:\n    using Base = class_<Type>;\n    using Base::attr;\n    using Base::def;\n    using Base::def_property_readonly;\n    using Base::def_property_readonly_static;\n    using Underlying = typename std::underlying_type<Type>::type;\n    // Scalar is the integer representation of underlying type\n    using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,\n                                                        std::is_same<Underlying, bool>>::value,\n                                         detail::equivalent_integer_t<Underlying>,\n                                         Underlying>;\n\n    template <typename... Extra>\n    enum_(const handle &scope, const char *name, const Extra &...extra)\n        : class_<Type>(scope, name, extra...), m_base(*this, scope) {\n        {\n            if (detail::global_internals_native_enum_type_map_contains(\n                    std::type_index(typeid(Type)))) {\n                pybind11_fail(\"pybind11::enum_ \\\"\" + std::string(name)\n                              + \"\\\" is already registered as a pybind11::native_enum!\");\n            }\n        }\n\n        constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;\n        constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;\n        m_base.init(is_arithmetic, is_convertible);\n\n        def(init([](Scalar i) { return static_cast<Type>(i); }), arg(\"value\"));\n        def_property_readonly(\"value\", [](Type value) { return (Scalar) value; }, pos_only());\n#define PYBIND11_ENUM_OP_SAME_TYPE(op, expr)                                                      \\\n    def(op, [](Type a, Type b) { return expr; }, pybind11::name(op), arg(\"other\"), pos_only())\n#define PYBIND11_ENUM_OP_SAME_TYPE_RHS_MAY_BE_NONE(op, expr)                                      \\\n    def(op, [](Type a, Type *b_ptr) { return expr; }, pybind11::name(op), arg(\"other\"), pos_only())\n#define PYBIND11_ENUM_OP_SCALAR(op, op_expr)                                                      \\\n    def(                                                                                          \\\n        op,                                                                                       \\\n        [](Type a, Scalar b) { return static_cast<Scalar>(a) op_expr b; },                        \\\n        pybind11::name(op),                                                                       \\\n        arg(\"other\"),                                                                             \\\n        pos_only())\n#define PYBIND11_ENUM_OP_CONV_ARITHMETIC(op, op_expr)                                             \\\n    /* NOLINTNEXTLINE(bugprone-macro-parentheses) */                                              \\\n    PYBIND11_ENUM_OP_SAME_TYPE(op, static_cast<Scalar>(a) op_expr static_cast<Scalar>(b));        \\\n    PYBIND11_ENUM_OP_SCALAR(op, op_expr)\n#define PYBIND11_ENUM_OP_REJECT_UNRELATED_TYPE(op, strict_behavior)                               \\\n    def(                                                                                          \\\n        op,                                                                                       \\\n        [](Type, const object &) { strict_behavior; },                                            \\\n        pybind11::name(op),                                                                       \\\n        arg(\"other\"),                                                                             \\\n        pos_only())\n#define PYBIND11_ENUM_OP_STRICT_ARITHMETIC(op, op_expr, strict_behavior)                          \\\n    /* NOLINTNEXTLINE(bugprone-macro-parentheses) */                                              \\\n    PYBIND11_ENUM_OP_SAME_TYPE(op, static_cast<Scalar>(a) op_expr static_cast<Scalar>(b));        \\\n    PYBIND11_ENUM_OP_REJECT_UNRELATED_TYPE(op, strict_behavior);\n\n        PYBIND11_ENUM_OP_SAME_TYPE_RHS_MAY_BE_NONE(\"__eq__\", b_ptr && a == *b_ptr);\n        PYBIND11_ENUM_OP_SAME_TYPE_RHS_MAY_BE_NONE(\"__ne__\", !b_ptr || a != *b_ptr);\n        if (std::is_convertible<Type, Scalar>::value) {\n            PYBIND11_ENUM_OP_SCALAR(\"__eq__\", ==);\n            PYBIND11_ENUM_OP_SCALAR(\"__ne__\", !=);\n            if (is_arithmetic) {\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__lt__\", <);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__gt__\", >);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__le__\", <=);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__ge__\", >=);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__and__\", &);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__rand__\", &);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__or__\", |);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__ror__\", |);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__xor__\", ^);\n                PYBIND11_ENUM_OP_CONV_ARITHMETIC(\"__rxor__\", ^);\n            }\n        } else if (is_arithmetic) {\n#define PYBIND11_ENUM_OP_THROW_TYPE_ERROR                                                         \\\n    throw type_error(\"Expected an enumeration of matching type!\");\n            PYBIND11_ENUM_OP_STRICT_ARITHMETIC(\"__lt__\", <, PYBIND11_ENUM_OP_THROW_TYPE_ERROR);\n            PYBIND11_ENUM_OP_STRICT_ARITHMETIC(\"__gt__\", >, PYBIND11_ENUM_OP_THROW_TYPE_ERROR);\n            PYBIND11_ENUM_OP_STRICT_ARITHMETIC(\"__le__\", <=, PYBIND11_ENUM_OP_THROW_TYPE_ERROR);\n            PYBIND11_ENUM_OP_STRICT_ARITHMETIC(\"__ge__\", >=, PYBIND11_ENUM_OP_THROW_TYPE_ERROR);\n#undef PYBIND11_ENUM_OP_THROW_TYPE_ERROR\n        }\n        PYBIND11_ENUM_OP_REJECT_UNRELATED_TYPE(\"__eq__\", return false);\n        PYBIND11_ENUM_OP_REJECT_UNRELATED_TYPE(\"__ne__\", return true);\n\n#undef PYBIND11_ENUM_OP_SAME_TYPE\n#undef PYBIND11_ENUM_OP_SAME_TYPE_RHS_MAY_BE_NONE\n#undef PYBIND11_ENUM_OP_SCALAR\n#undef PYBIND11_ENUM_OP_CONV_ARITHMETIC\n#undef PYBIND11_ENUM_OP_REJECT_UNRELATED_TYPE\n#undef PYBIND11_ENUM_OP_STRICT_ARITHMETIC\n\n        def(\"__int__\", [](Type value) { return (Scalar) value; }, pos_only());\n        def(\"__index__\", [](Type value) { return (Scalar) value; }, pos_only());\n        attr(\"__setstate__\") = cpp_function(\n            [](detail::value_and_holder &v_h, Scalar arg) {\n                detail::initimpl::setstate<Base>(\n                    v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);\n            },\n            detail::is_new_style_constructor(),\n            pybind11::name(\"__setstate__\"),\n            is_method(*this),\n            arg(\"state\"),\n            pos_only());\n    }\n\n    /// Export enumeration entries into the parent scope\n    enum_ &export_values() {\n        m_base.export_values();\n        return *this;\n    }\n\n    /// Add an enumeration entry\n    enum_ &value(char const *name, Type value, const char *doc = nullptr) {\n        m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);\n        return *this;\n    }\n\nprivate:\n    detail::enum_base m_base;\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\nPYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {\n    if (!nurse || !patient) {\n        pybind11_fail(\"Could not activate keep_alive!\");\n    }\n\n    if (patient.is_none() || nurse.is_none()) {\n        return; /* Nothing to keep alive or nothing to be kept alive by */\n    }\n\n    auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));\n    if (!tinfo.empty()) {\n        /* It's a pybind-registered type, so we can store the patient in the\n         * internal list. */\n        add_patient(nurse.ptr(), patient.ptr());\n    } else {\n        /* Fall back to clever approach based on weak references taken from\n         * Boost.Python. This is not used for pybind-registered types because\n         * the objects can be destroyed out-of-order in a GC pass. */\n        cpp_function disable_lifesupport([patient](handle weakref) {\n            patient.dec_ref();\n            weakref.dec_ref();\n        });\n\n        weakref wr(nurse, disable_lifesupport);\n\n        patient.inc_ref(); /* reference patient and leak the weak reference */\n        (void) wr.release();\n    }\n}\n\nPYBIND11_NOINLINE void\nkeep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {\n    auto get_arg = [&](size_t n) {\n        if (n == 0) {\n            return ret;\n        }\n        if (n == 1 && call.init_self) {\n            return call.init_self;\n        }\n        if (n <= call.args.size()) {\n            return call.args[n - 1];\n        }\n        return handle();\n    };\n\n    keep_alive_impl(get_arg(Nurse), get_arg(Patient));\n}\n\ninline std::pair<decltype(internals::registered_types_py)::iterator, bool>\nall_type_info_get_cache(PyTypeObject *type) {\n    auto res = with_internals([type](internals &internals) {\n        auto ins = internals\n                       .registered_types_py\n#ifdef __cpp_lib_unordered_map_try_emplace\n                       .try_emplace(type);\n#else\n                       .emplace(type, std::vector<detail::type_info *>());\n#endif\n        if (ins.second) {\n            // For free-threading mode, this call must be under\n            // the with_internals() mutex lock, to avoid that other threads\n            // continue running with the empty ins.first->second.\n            all_type_info_populate(type, ins.first->second);\n        }\n        return ins;\n    });\n    if (res.second) {\n        // New cache entry created; set up a weak reference to automatically remove it if the type\n        // gets destroyed:\n        weakref(reinterpret_cast<PyObject *>(type), cpp_function([type](handle wr) {\n                    with_internals([type](internals &internals) {\n                        internals.registered_types_py.erase(type);\n\n                        // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h\n                        auto &cache = internals.inactive_override_cache;\n                        for (auto it = cache.begin(), last = cache.end(); it != last;) {\n                            if (it->first == reinterpret_cast<PyObject *>(type)) {\n                                it = cache.erase(it);\n                            } else {\n                                ++it;\n                            }\n                        }\n                    });\n\n                    wr.dec_ref();\n                }))\n            .release();\n    }\n\n    return res;\n}\n\n/* There are a large number of apparently unused template arguments because\n * each combination requires a separate py::class_ registration.\n */\ntemplate <typename Access,\n          return_value_policy Policy,\n          typename Iterator,\n          typename Sentinel,\n          typename ValueType,\n          typename... Extra>\nstruct iterator_state {\n    Iterator it;\n    Sentinel end;\n    bool first_or_done;\n};\n\n// Note: these helpers take the iterator by non-const reference because some\n// iterators in the wild can't be dereferenced when const. The & after Iterator\n// is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to\n// bugs in ICC, NVCC, and PGI compilers. See PR #3293.\ntemplate <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>\nstruct iterator_access {\n    using result_type = decltype(*std::declval<Iterator &>());\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    result_type operator()(Iterator &it) const { return *it; }\n};\n\ntemplate <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>\nclass iterator_key_access {\nprivate:\n    using pair_type = decltype(*std::declval<Iterator &>());\n\npublic:\n    /* If either the pair itself or the element of the pair is a reference, we\n     * want to return a reference, otherwise a value. When the decltype\n     * expression is parenthesized it is based on the value category of the\n     * expression; otherwise it is the declared type of the pair member.\n     * The use of declval<pair_type> in the second branch rather than directly\n     * using *std::declval<Iterator &>() is a workaround for nvcc\n     * (it's not used in the first branch because going via decltype and back\n     * through declval does not perfectly preserve references).\n     */\n    using result_type\n        = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,\n                        decltype(((*std::declval<Iterator &>()).first)),\n                        decltype(std::declval<pair_type>().first)>;\n    result_type operator()(Iterator &it) const { return (*it).first; }\n};\n\ntemplate <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>\nclass iterator_value_access {\nprivate:\n    using pair_type = decltype(*std::declval<Iterator &>());\n\npublic:\n    using result_type\n        = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,\n                        decltype(((*std::declval<Iterator &>()).second)),\n                        decltype(std::declval<pair_type>().second)>;\n    result_type operator()(Iterator &it) const { return (*it).second; }\n};\n\ntemplate <typename Access,\n          return_value_policy Policy,\n          typename Iterator,\n          typename Sentinel,\n          typename ValueType,\n          typename... Extra>\n// NOLINTNEXTLINE(performance-unnecessary-value-param)\niterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {\n    using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;\n    // TODO: state captures only the types of Extra, not the values\n\n    // For Python < 3.14.0rc1, pycritical_section uses direct mutex locking (same as a unique\n    // lock), which may deadlock during type registration. See detail/internals.h for details.\n#if PY_VERSION_HEX >= 0x030E00C1 // 3.14.0rc1\n    PYBIND11_LOCK_INTERNALS(get_internals());\n#endif\n    if (!detail::get_type_info(typeid(state), false)) {\n        class_<state>(handle(), \"iterator\", pybind11::module_local())\n            .def(\n                \"__iter__\", [](state &s) -> state & { return s; }, pos_only())\n            .def(\n                \"__next__\",\n                [](state &s) -> ValueType {\n                    if (!s.first_or_done) {\n                        ++s.it;\n                    } else {\n                        s.first_or_done = false;\n                    }\n                    if (s.it == s.end) {\n                        s.first_or_done = true;\n                        throw stop_iteration();\n                    }\n                    return Access()(s.it);\n                    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n                },\n                std::forward<Extra>(extra)...,\n                pos_only(),\n                Policy);\n    }\n\n    return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true});\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Makes a python iterator from a first and past-the-end C++ InputIterator.\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Iterator,\n          typename Sentinel,\n          typename ValueType = typename detail::iterator_access<Iterator>::result_type,\n          typename... Extra>\n// NOLINTNEXTLINE(performance-unnecessary-value-param)\ntyping::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) {\n    return detail::make_iterator_impl<detail::iterator_access<Iterator>,\n                                      Policy,\n                                      Iterator,\n                                      Sentinel,\n                                      ValueType,\n                                      Extra...>(std::forward<Iterator>(first),\n                                                std::forward<Sentinel>(last),\n                                                std::forward<Extra>(extra)...);\n}\n\n/// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a\n/// first and past-the-end InputIterator.\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Iterator,\n          typename Sentinel,\n          typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,\n          typename... Extra>\ntyping::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {\n    return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,\n                                      Policy,\n                                      Iterator,\n                                      Sentinel,\n                                      KeyType,\n                                      Extra...>(std::forward<Iterator>(first),\n                                                std::forward<Sentinel>(last),\n                                                std::forward<Extra>(extra)...);\n}\n\n/// Makes a python iterator over the values (`.second`) of a iterator over pairs from a\n/// first and past-the-end InputIterator.\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Iterator,\n          typename Sentinel,\n          typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,\n          typename... Extra>\ntyping::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {\n    return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,\n                                      Policy,\n                                      Iterator,\n                                      Sentinel,\n                                      ValueType,\n                                      Extra...>(std::forward<Iterator>(first),\n                                                std::forward<Sentinel>(last),\n                                                std::forward<Extra>(extra)...);\n}\n\n/// Makes an iterator over values of an stl container or other container supporting\n/// `std::begin()`/`std::end()`\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Type,\n          typename ValueType = typename detail::iterator_access<\n              decltype(std::begin(std::declval<Type &>()))>::result_type,\n          typename... Extra>\ntyping::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) {\n    return make_iterator<Policy>(\n        std::begin(value), std::end(value), std::forward<Extra>(extra)...);\n}\n\n/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting\n/// `std::begin()`/`std::end()`\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Type,\n          typename KeyType = typename detail::iterator_key_access<\n              decltype(std::begin(std::declval<Type &>()))>::result_type,\n          typename... Extra>\ntyping::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) {\n    return make_key_iterator<Policy>(\n        std::begin(value), std::end(value), std::forward<Extra>(extra)...);\n}\n\n/// Makes an iterator over the values (`.second`) of a stl map-like container supporting\n/// `std::begin()`/`std::end()`\ntemplate <return_value_policy Policy = return_value_policy::reference_internal,\n          typename Type,\n          typename ValueType = typename detail::iterator_value_access<\n              decltype(std::begin(std::declval<Type &>()))>::result_type,\n          typename... Extra>\ntyping::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) {\n    return make_value_iterator<Policy>(\n        std::begin(value), std::end(value), std::forward<Extra>(extra)...);\n}\n\ntemplate <typename InputType, typename OutputType>\nvoid implicitly_convertible() {\n    static int tss_sentinel_pointee = 1; // arbitrary value\n    struct set_flag {\n        thread_specific_storage<int> &flag;\n        explicit set_flag(thread_specific_storage<int> &flag_) : flag(flag_) {\n            flag = &tss_sentinel_pointee; // trick: the pointer itself is the sentinel\n        }\n        ~set_flag() { flag.reset(nullptr); }\n\n        // Prevent copying/moving to ensure RAII guard is used safely\n        set_flag(const set_flag &) = delete;\n        set_flag(set_flag &&) = delete;\n        set_flag &operator=(const set_flag &) = delete;\n        set_flag &operator=(set_flag &&) = delete;\n    };\n    auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {\n        static thread_specific_storage<int> currently_used;\n        if (currently_used) { // implicit conversions are non-reentrant\n            return nullptr;\n        }\n        set_flag flag_helper(currently_used);\n        if (!detail::make_caster<InputType>().load(obj, false)) {\n            return nullptr;\n        }\n        tuple args(1);\n        args[0] = obj;\n        PyObject *result = PyObject_Call(reinterpret_cast<PyObject *>(type), args.ptr(), nullptr);\n        if (result == nullptr) {\n            PyErr_Clear();\n        }\n        return result;\n    };\n\n    if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {\n        tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));\n    } else {\n        pybind11_fail(\"implicitly_convertible: Unable to find type \" + type_id<OutputType>());\n    }\n}\n\ninline void register_exception_translator(ExceptionTranslator &&translator) {\n    detail::with_exception_translators(\n        [&](std::forward_list<ExceptionTranslator> &exception_translators,\n            std::forward_list<ExceptionTranslator> &local_exception_translators) {\n            (void) local_exception_translators;\n            exception_translators.push_front(std::forward<ExceptionTranslator>(translator));\n        });\n}\n\n/**\n * Add a new module-local exception translator. Locally registered functions\n * will be tried before any globally registered exception translators, which\n * will only be invoked if the module-local handlers do not deal with\n * the exception.\n */\ninline void register_local_exception_translator(ExceptionTranslator &&translator) {\n    detail::with_exception_translators(\n        [&](std::forward_list<ExceptionTranslator> &exception_translators,\n            std::forward_list<ExceptionTranslator> &local_exception_translators) {\n            (void) exception_translators;\n            local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator));\n        });\n}\n\n/**\n * Wrapper to generate a new Python exception type.\n *\n * This should only be used with py::set_error() for now.\n * It is not (yet) possible to use as a py::base.\n * Template type argument is reserved for future use.\n */\ntemplate <typename type>\nclass exception : public object {\npublic:\n    exception() = default;\n    exception(handle scope, const char *name, handle base = PyExc_Exception) {\n        std::string full_name\n            = scope.attr(\"__name__\").cast<std::string>() + std::string(\".\") + name;\n        m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);\n        if (hasattr(scope, \"__dict__\") && scope.attr(\"__dict__\").contains(name)) {\n            pybind11_fail(\"Error during initialization: multiple incompatible \"\n                          \"definitions with name \\\"\"\n                          + std::string(name) + \"\\\"\");\n        }\n        scope.attr(name) = *this;\n    }\n\n    // Sets the current python exception to this exception object with the given message\n    PYBIND11_DEPRECATED(\"Please use py::set_error() instead \"\n                        \"(https://github.com/pybind/pybind11/pull/4772)\")\n    void operator()(const char *message) const { set_error(*this, message); }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <>\nstruct handle_type_name<exception<void>> {\n    static constexpr auto name = const_name(\"Exception\");\n};\n\n// Helper function for register_exception and register_local_exception\ntemplate <typename CppException>\nexception<CppException> &\nregister_exception_impl(handle scope, const char *name, handle base, bool isLocal) {\n    PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage;\n    exc_storage.call_once_and_store_result(\n        [&]() { return exception<CppException>(scope, name, base); });\n\n    auto register_func\n        = isLocal ? &register_local_exception_translator : &register_exception_translator;\n\n    register_func([](std::exception_ptr p) {\n        if (!p) {\n            return;\n        }\n        try {\n            std::rethrow_exception(p);\n        } catch (const CppException &e) {\n            set_error(exc_storage.get_stored(), e.what());\n        }\n    });\n    return exc_storage.get_stored();\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/**\n * Registers a Python exception in `m` of the given `name` and installs a translator to\n * translate the C++ exception to the created Python exception using the what() method.\n * This is intended for simple exception translations; for more complex translation, register the\n * exception object and translator directly.\n */\ntemplate <typename CppException>\nexception<CppException> &\nregister_exception(handle scope, const char *name, handle base = PyExc_Exception) {\n    return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);\n}\n\n/**\n * Registers a Python exception in `m` of the given `name` and installs a translator to\n * translate the C++ exception to the created Python exception using the what() method.\n * This translator will only be used for exceptions that are thrown in this module and will be\n * tried before global exception translators, including those registered with register_exception.\n * This is intended for simple exception translations; for more complex translation, register the\n * exception object and translator directly.\n */\ntemplate <typename CppException>\nexception<CppException> &\nregister_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {\n    return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\nPYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {\n    auto strings = tuple(args.size());\n    for (size_t i = 0; i < args.size(); ++i) {\n        strings[i] = str(args[i]);\n    }\n    auto sep = kwargs.contains(\"sep\") ? kwargs[\"sep\"] : str(\" \");\n    auto line = sep.attr(\"join\")(std::move(strings));\n\n    object file;\n    if (kwargs.contains(\"file\")) {\n        file = kwargs[\"file\"].cast<object>();\n    } else {\n        try {\n            file = module_::import(\"sys\").attr(\"stdout\");\n        } catch (const error_already_set &) {\n            /* If print() is called from code that is executed as\n               part of garbage collection during interpreter shutdown,\n               importing 'sys' can fail. Give up rather than crashing the\n               interpreter in this case. */\n            return;\n        }\n    }\n\n    auto write = file.attr(\"write\");\n    write(std::move(line));\n    write(kwargs.contains(\"end\") ? kwargs[\"end\"] : str(\"\\n\"));\n\n    if (kwargs.contains(\"flush\") && kwargs[\"flush\"].cast<bool>()) {\n        file.attr(\"flush\")();\n    }\n}\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>\nvoid print(Args &&...args) {\n    auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);\n    detail::print(c.args(), c.kwargs());\n}\n\ninline void\nerror_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {\n    gil_scoped_acquire gil;\n    error_scope scope;\n    delete raw_ptr;\n}\n\ninline const char *error_already_set::what() const noexcept {\n    gil_scoped_acquire gil;\n    error_scope scope;\n    return m_fetched_error->error_string().c_str();\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline function\nget_type_override(const void *this_ptr, const type_info *this_type, const char *name) {\n    handle self = get_object_handle(this_ptr, this_type);\n    if (!self) {\n        return function();\n    }\n    handle type = type::handle_of(self);\n    auto key = std::make_pair(type.ptr(), name);\n\n    /* Cache functions that aren't overridden in Python to avoid\n       many costly Python dictionary lookups below */\n    bool not_overridden = with_internals([&key](internals &internals) {\n        auto &cache = internals.inactive_override_cache;\n        return cache.find(key) != cache.end();\n    });\n    if (not_overridden) {\n        return function();\n    }\n\n    function override = getattr(self, name, function());\n    if (override.is_cpp_function()) {\n        with_internals([&](internals &internals) {\n            internals.inactive_override_cache.insert(std::move(key));\n        });\n        return function();\n    }\n\n    /* Don't call dispatch code if invoked from overridden function.\n       Unfortunately this doesn't work on PyPy and GraalPy. */\n#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)\n#    if PY_VERSION_HEX >= 0x03090000\n    PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());\n    if (frame != nullptr) {\n        PyCodeObject *f_code = PyFrame_GetCode(frame);\n        // f_code is guaranteed to not be NULL\n        if (std::string(str(f_code->co_name)) == name && f_code->co_argcount > 0) {\n#        if PY_VERSION_HEX >= 0x030d0000\n            PyObject *locals = PyEval_GetFrameLocals();\n#        else\n            PyObject *locals = PyEval_GetLocals();\n            Py_XINCREF(locals);\n#        endif\n            if (locals != nullptr) {\n#        if PY_VERSION_HEX >= 0x030b0000\n                PyObject *co_varnames = PyCode_GetVarnames(f_code);\n#        else\n                PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, \"co_varnames\");\n#        endif\n                PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);\n                Py_DECREF(co_varnames);\n                PyObject *self_caller = dict_getitem(locals, self_arg);\n                Py_DECREF(locals);\n                if (self_caller == self.ptr()) {\n                    Py_DECREF(f_code);\n                    Py_DECREF(frame);\n                    return function();\n                }\n            }\n        }\n        Py_DECREF(f_code);\n        Py_DECREF(frame);\n    }\n#    else\n    PyFrameObject *frame = PyThreadState_Get()->frame;\n    if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name\n        && frame->f_code->co_argcount > 0) {\n        PyFrame_FastToLocals(frame);\n        PyObject *self_caller\n            = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));\n        if (self_caller == self.ptr()) {\n            return function();\n        }\n    }\n#    endif\n\n#else\n    /* PyPy currently doesn't provide a detailed cpyext emulation of\n       frame objects, so we have to emulate this using Python. This\n       is going to be slow..*/\n    dict d;\n    d[\"self\"] = self;\n    d[\"name\"] = pybind11::str(name);\n    PyObject *result\n        = PyRun_String(\"import inspect\\n\"\n                       \"frame = inspect.currentframe()\\n\"\n                       \"if frame is not None:\\n\"\n                       \"    frame = frame.f_back\\n\"\n                       \"    if frame is not None and str(frame.f_code.co_name) == name and \"\n                       \"frame.f_code.co_argcount > 0:\\n\"\n                       \"        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\\n\"\n                       \"        if self_caller == self:\\n\"\n                       \"            self = None\\n\",\n                       Py_file_input,\n                       d.ptr(),\n                       d.ptr());\n    if (result == nullptr)\n        throw error_already_set();\n    Py_DECREF(result);\n    if (d[\"self\"].is_none())\n        return function();\n#endif\n\n    return override;\n}\nPYBIND11_NAMESPACE_END(detail)\n\n/** \\rst\n  Try to retrieve a python method by the provided name from the instance pointed to by the\n  this_ptr.\n\n  :this_ptr: The pointer to the object the overridden method should be retrieved for. This should\n             be the first non-trampoline class encountered in the inheritance chain.\n  :name: The name of the overridden Python method to retrieve.\n  :return: The Python method by this name from the object or an empty function wrapper.\n \\endrst */\ntemplate <class T>\nfunction get_override(const T *this_ptr, const char *name) {\n    auto *tinfo = detail::get_type_info(typeid(T));\n    return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();\n}\n\n#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...)                                        \\\n    do {                                                                                          \\\n        pybind11::gil_scoped_acquire gil;                                                         \\\n        pybind11::function override                                                               \\\n            = pybind11::get_override(static_cast<const cname *>(this), name);                     \\\n        if (override) {                                                                           \\\n            auto o = override(__VA_ARGS__);                                                       \\\n            PYBIND11_WARNING_PUSH                                                                 \\\n            PYBIND11_WARNING_DISABLE_MSVC(4127)                                                   \\\n            if PYBIND11_MAYBE_CONSTEXPR (                                                         \\\n                pybind11::detail::cast_is_temporary_value_reference<ret_type>::value              \\\n                && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) {      \\\n                static pybind11::detail::override_caster_t<ret_type> caster;                      \\\n                return pybind11::detail::cast_ref<ret_type>(std::move(o), caster);                \\\n            } else {                                                                              \\\n                return pybind11::detail::cast_safe<ret_type>(std::move(o));                       \\\n            }                                                                                     \\\n            PYBIND11_WARNING_POP                                                                  \\\n        }                                                                                         \\\n    } while (false)\n\n/** \\rst\n    Macro to populate the virtual method in the trampoline class. This macro tries to look up a\n    method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument\n    conversions to call this method and return the appropriate type.\n    See :ref:`overriding_virtuals` for more information. This macro should be used when the method\n    name in C is not the same as the method name in Python. For example with `__str__`.\n\n    .. code-block:: cpp\n\n      std::string toString() override {\n        PYBIND11_OVERRIDE_NAME(\n            std::string, // Return type (ret_type)\n            Animal,      // Parent class (cname)\n            \"__str__\",   // Name of method in Python (name)\n            toString,    // Name of function in C++ (fn)\n        );\n      }\n\\endrst */\n#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...)                                    \\\n    do {                                                                                          \\\n        PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \\\n        return cname::fn(__VA_ARGS__);                                                            \\\n    } while (false)\n\n/** \\rst\n    Macro for pure virtual functions, this function is identical to\n    :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.\n\\endrst */\n#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...)                               \\\n    do {                                                                                          \\\n        PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \\\n        pybind11::pybind11_fail(                                                                  \\\n            \"Tried to call pure virtual function \\\"\" PYBIND11_STRINGIFY(cname) \"::\" name \"\\\"\");   \\\n    } while (false)\n\n/** \\rst\n    Macro to populate the virtual method in the trampoline class. This macro tries to look up the\n    method from the Python side, deals with the :ref:`gil` and necessary argument conversions to\n    call this method and return the appropriate type. This macro should be used if the method name\n    in C and in Python are identical.\n    See :ref:`overriding_virtuals` for more information.\n\n    .. code-block:: cpp\n\n      class PyAnimal : public Animal {\n      public:\n          // Inherit the constructors\n          using Animal::Animal;\n\n          // Trampoline (need one for each virtual function)\n          std::string go(int n_times) override {\n              PYBIND11_OVERRIDE_PURE(\n                  std::string, // Return type (ret_type)\n                  Animal,      // Parent class (cname)\n                  go,          // Name of function in C++ (must match Python name) (fn)\n                  n_times      // Argument(s) (...)\n              );\n          }\n      };\n\\endrst */\n#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...)                                               \\\n    PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)\n\n/** \\rst\n    Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,\n    except that it throws if no override can be found.\n\\endrst */\n#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...)                                          \\\n    PYBIND11_OVERRIDE_PURE_NAME(                                                                  \\\n        PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)\n\n// Deprecated versions\n\nPYBIND11_DEPRECATED(\"get_type_overload has been deprecated\")\ninline function\nget_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {\n    return detail::get_type_override(this_ptr, this_type, name);\n}\n\ntemplate <class T>\ninline function get_overload(const T *this_ptr, const char *name) {\n    return get_override(this_ptr, name);\n}\n\n#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...)                                         \\\n    PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)\n#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...)                                    \\\n    PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)\n#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...)                               \\\n    PYBIND11_OVERRIDE_PURE_NAME(                                                                  \\\n        PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);\n#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...)                                               \\\n    PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)\n#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...)                                          \\\n    PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/pytypes.h",
    "content": "/*\n    pybind11/pytypes.h: Convenience wrapper classes for basic Python types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"buffer_info.h\"\n\n#include <assert.h>\n#include <cstddef>\n#include <exception>\n#include <frameobject.h>\n#include <iterator>\n#include <memory>\n#include <string>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n\n#if defined(PYBIND11_HAS_OPTIONAL)\n#    include <optional>\n#endif\n\n#ifdef PYBIND11_HAS_STRING_VIEW\n#    include <string_view>\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\n/* A few forward declarations */\nclass handle;\nclass object;\nclass str;\nclass iterator;\nclass type;\nstruct arg;\nstruct arg_v;\n\nPYBIND11_NAMESPACE_BEGIN(detail)\nclass args_proxy;\nbool isinstance_generic(handle obj, const std::type_info &tp);\n\ntemplate <typename T>\nbool isinstance_native_enum(handle obj, const std::type_info &tp);\n\n// Accessor forward declarations\ntemplate <typename Policy>\nclass accessor;\nnamespace accessor_policies {\nstruct obj_attr;\nstruct str_attr;\nstruct generic_item;\nstruct sequence_item;\nstruct list_item;\nstruct tuple_item;\n} // namespace accessor_policies\n// PLEASE KEEP handle_type_name SPECIALIZATIONS IN SYNC.\nusing obj_attr_accessor = accessor<accessor_policies::obj_attr>;\nusing str_attr_accessor = accessor<accessor_policies::str_attr>;\nusing item_accessor = accessor<accessor_policies::generic_item>;\nusing sequence_accessor = accessor<accessor_policies::sequence_item>;\nusing list_accessor = accessor<accessor_policies::list_item>;\nusing tuple_accessor = accessor<accessor_policies::tuple_item>;\n\n/// Tag and check to identify a class which implements the Python object API\nclass pyobject_tag {};\ntemplate <typename T>\nusing is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;\n\n/** \\rst\n    A mixin class which adds common functions to `handle`, `object` and various accessors.\n    The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``.\n\\endrst */\ntemplate <typename Derived>\nclass object_api : public pyobject_tag {\n    object_api() = default;\n    const Derived &derived() const { return static_cast<const Derived &>(*this); }\n    friend Derived;\n\npublic:\n    /** \\rst\n        Return an iterator equivalent to calling ``iter()`` in Python. The object\n        must be a collection which supports the iteration protocol.\n    \\endrst */\n    iterator begin() const;\n    /// Return a sentinel which ends iteration.\n    iterator end() const;\n\n    /** \\rst\n        Return an internal functor to invoke the object's sequence protocol. Casting\n        the returned ``detail::item_accessor`` instance to a `handle` or `object`\n        subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`\n        or `object` subclass causes a call to ``__setitem__``.\n    \\endrst */\n    item_accessor operator[](handle key) const;\n    /// See above (the only difference is that the key's reference is stolen)\n    item_accessor operator[](object &&key) const;\n    /// See above (the only difference is that the key is provided as a string literal)\n    item_accessor operator[](const char *key) const;\n\n    /** \\rst\n        Return an internal functor to access the object's attributes. Casting the\n        returned ``detail::obj_attr_accessor`` instance to a `handle` or `object`\n        subclass causes a corresponding call to ``getattr``. Assigning a `handle`\n        or `object` subclass causes a call to ``setattr``.\n    \\endrst */\n    obj_attr_accessor attr(handle key) const;\n    /// See above (the only difference is that the key's reference is stolen)\n    obj_attr_accessor attr(object &&key) const;\n    /// See above (the only difference is that the key is provided as a string literal)\n    str_attr_accessor attr(const char *key) const;\n\n    /** \\rst\n         Similar to the above attr functions with the difference that the templated Type\n         is used to set the `__annotations__` dict value to the corresponding key. Worth noting\n         that attr_with_type_hint is implemented in cast.h.\n    \\endrst */\n    template <typename T>\n    obj_attr_accessor attr_with_type_hint(handle key) const;\n    /// See above (the only difference is that the key is provided as a string literal)\n    template <typename T>\n    str_attr_accessor attr_with_type_hint(const char *key) const;\n\n    /** \\rst\n        Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple``\n        or ``list`` for a function call. Applying another * to the result yields\n        ** unpacking, e.g. to unpack a dict as function keyword arguments.\n        See :ref:`calling_python_functions`.\n    \\endrst */\n    args_proxy operator*() const;\n\n    /// Check if the given item is contained within this object, i.e. ``item in obj``.\n    template <typename T>\n    bool contains(T &&item) const;\n\n    /** \\rst\n        Assuming the Python object is a function or implements the ``__call__``\n        protocol, ``operator()`` invokes the underlying function, passing an\n        arbitrary set of parameters. The result is returned as a `object` and\n        may need to be converted back into a Python object using `handle::cast()`.\n\n        When some of the arguments cannot be converted to Python objects, the\n        function will throw a `cast_error` exception. When the Python function\n        call fails, a `error_already_set` exception is thrown.\n    \\endrst */\n    template <return_value_policy policy = return_value_policy::automatic_reference,\n              typename... Args>\n    object operator()(Args &&...args) const;\n    template <return_value_policy policy = return_value_policy::automatic_reference,\n              typename... Args>\n    PYBIND11_DEPRECATED(\"call(...) was deprecated in favor of operator()(...)\")\n    object call(Args &&...args) const;\n\n    /// Equivalent to ``obj is other`` in Python.\n    bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }\n    /// Equivalent to ``obj is None`` in Python.\n    bool is_none() const { return derived().ptr() == Py_None; }\n    /// Equivalent to obj == other in Python\n    bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }\n    bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }\n    bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }\n    bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }\n    bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }\n    bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }\n\n    object operator-() const;\n    object operator~() const;\n    object operator+(object_api const &other) const;\n    object operator+=(object_api const &other);\n    object operator-(object_api const &other) const;\n    object operator-=(object_api const &other);\n    object operator*(object_api const &other) const;\n    object operator*=(object_api const &other);\n    object operator/(object_api const &other) const;\n    object operator/=(object_api const &other);\n    object operator|(object_api const &other) const;\n    object operator|=(object_api const &other);\n    object operator&(object_api const &other) const;\n    object operator&=(object_api const &other);\n    object operator^(object_api const &other) const;\n    object operator^=(object_api const &other);\n    object operator<<(object_api const &other) const;\n    object operator<<=(object_api const &other);\n    object operator>>(object_api const &other) const;\n    object operator>>=(object_api const &other);\n\n    PYBIND11_DEPRECATED(\"Use py::str(obj) instead\")\n    pybind11::str str() const;\n\n    /// Get or set the object's docstring, i.e. ``obj.__doc__``.\n    str_attr_accessor doc() const;\n\n    /// Get or set the object's annotations, i.e. ``obj.__annotations__``.\n    object annotations() const;\n\n    /// Return the object's current reference count\n    ssize_t ref_count() const {\n#ifdef PYPY_VERSION\n        // PyPy uses the top few bits for REFCNT_FROM_PYPY & REFCNT_FROM_PYPY_LIGHT\n        // Following pybind11 2.12.1 and older behavior and removing this part\n        return static_cast<ssize_t>(static_cast<int>(Py_REFCNT(derived().ptr())));\n#else\n        return Py_REFCNT(derived().ptr());\n#endif\n    }\n\n    PYBIND11_DEPRECATED(\"Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()\")\n    handle get_type() const;\n\nprivate:\n    bool rich_compare(object_api const &other, int value) const;\n};\n\ntemplate <typename T>\nusing is_pyobj_ptr_or_nullptr_t = detail::any_of<std::is_same<T, PyObject *>,\n                                                 std::is_same<T, PyObject *const>,\n                                                 std::is_same<T, std::nullptr_t>>;\n\nPYBIND11_NAMESPACE_END(detail)\n\n#if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG)\n#    define PYBIND11_HANDLE_REF_DEBUG\n#endif\n\n/** \\rst\n    Holds a reference to a Python object (no reference counting)\n\n    The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a\n    ``PyObject *`` in Python's C API). It does not perform any automatic reference\n    counting and merely provides a basic C++ interface to various Python API functions.\n\n    .. seealso::\n        The `object` class inherits from `handle` and adds automatic reference\n        counting features.\n\\endrst */\nclass handle : public detail::object_api<handle> {\npublic:\n    /// The default constructor creates a handle with a ``nullptr``-valued pointer\n    handle() = default;\n\n    /// Enable implicit conversion from ``PyObject *`` and ``nullptr``.\n    /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``.\n    template <typename T,\n              detail::enable_if_t<detail::is_pyobj_ptr_or_nullptr_t<T>::value, int> = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    handle(T ptr) : m_ptr(ptr) {}\n\n    /// Enable implicit conversion through ``T::operator PyObject *()``.\n    template <\n        typename T,\n        detail::enable_if_t<detail::all_of<detail::none_of<std::is_base_of<handle, T>,\n                                                           detail::is_pyobj_ptr_or_nullptr_t<T>>,\n                                           std::is_convertible<T, PyObject *>>::value,\n                            int>\n        = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    handle(T &obj) : m_ptr(obj) {}\n\n    /// Return the underlying ``PyObject *`` pointer\n    PyObject *ptr() const { return m_ptr; }\n    PyObject *&ptr() { return m_ptr; }\n\n    /** \\rst\n        Manually increase the reference count of the Python object. Usually, it is\n        preferable to use the `object` class which derives from `handle` and calls\n        this function automatically. Returns a reference to itself.\n    \\endrst */\n    const handle &inc_ref() const & {\n#ifdef PYBIND11_HANDLE_REF_DEBUG\n        inc_ref_counter(1);\n#endif\n#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF\n        if (m_ptr != nullptr && PyGILState_Check() == 0) {\n            throw_gilstate_error(\"pybind11::handle::inc_ref()\");\n        }\n#endif\n        Py_XINCREF(m_ptr);\n        return *this;\n    }\n\n    /** \\rst\n        Manually decrease the reference count of the Python object. Usually, it is\n        preferable to use the `object` class which derives from `handle` and calls\n        this function automatically. Returns a reference to itself.\n    \\endrst */\n    const handle &dec_ref() const & {\n#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF\n        if (m_ptr != nullptr && PyGILState_Check() == 0) {\n            throw_gilstate_error(\"pybind11::handle::dec_ref()\");\n        }\n#endif\n        Py_XDECREF(m_ptr);\n        return *this;\n    }\n\n    /** \\rst\n        Attempt to cast the Python object into the given C++ type. A `cast_error`\n        will be throw upon failure.\n    \\endrst */\n    template <typename T>\n    T cast() const;\n    /// Return ``true`` when the `handle` wraps a valid Python object\n    explicit operator bool() const { return m_ptr != nullptr; }\n    /** \\rst\n        Deprecated: Check that the underlying pointers are the same.\n        Equivalent to ``obj1 is obj2`` in Python.\n    \\endrst */\n    PYBIND11_DEPRECATED(\"Use obj1.is(obj2) instead\")\n    bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }\n    PYBIND11_DEPRECATED(\"Use !obj1.is(obj2) instead\")\n    bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }\n    PYBIND11_DEPRECATED(\"Use handle::operator bool() instead\")\n    bool check() const { return m_ptr != nullptr; }\n\nprotected:\n    PyObject *m_ptr = nullptr;\n\nprivate:\n#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF\n    void throw_gilstate_error(const std::string &function_name) const {\n        fprintf(\n            stderr,\n            \"%s is being called while the GIL is either not held or invalid. Please see \"\n            \"https://pybind11.readthedocs.io/en/stable/advanced/\"\n            \"misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\\n\"\n            \"If you are convinced there is no bug in your code, you can #define \"\n            \"PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF \"\n            \"to disable this check. In that case you have to ensure this #define is consistently \"\n            \"used for all translation units linked into a given pybind11 extension, otherwise \"\n            \"there will be ODR violations.\",\n            function_name.c_str());\n        if (Py_TYPE(m_ptr)->tp_name != nullptr) {\n            fprintf(stderr,\n                    \" The failing %s call was triggered on a %s object.\",\n                    function_name.c_str(),\n                    Py_TYPE(m_ptr)->tp_name);\n        }\n        fprintf(stderr, \"\\n\");\n        fflush(stderr);\n        throw std::runtime_error(function_name + \" PyGILState_Check() failure.\");\n    }\n#endif\n\n#ifdef PYBIND11_HANDLE_REF_DEBUG\n    static std::size_t inc_ref_counter(std::size_t add) {\n        thread_local std::size_t counter = 0;\n        counter += add;\n        return counter;\n    }\n\npublic:\n    static std::size_t inc_ref_counter() { return inc_ref_counter(0); }\n#endif\n};\n\ninline void set_error(const handle &type, const char *message) {\n    PyErr_SetString(type.ptr(), message);\n}\n\ninline void set_error(const handle &type, const handle &value) {\n    PyErr_SetObject(type.ptr(), value.ptr());\n}\n\n/** \\rst\n    Holds a reference to a Python object (with reference counting)\n\n    Like `handle`, the `object` class is a thin wrapper around an arbitrary Python\n    object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it\n    optionally increases the object's reference count upon construction, and it\n    *always* decreases the reference count when the `object` instance goes out of\n    scope and is destructed. When using `object` instances consistently, it is much\n    easier to get reference counting right at the first attempt.\n\\endrst */\nclass object : public handle {\npublic:\n    object() = default;\n    PYBIND11_DEPRECATED(\"Use reinterpret_borrow<object>() or reinterpret_steal<object>()\")\n    object(handle h, bool is_borrowed) : handle(h) {\n        if (is_borrowed) {\n            inc_ref();\n        }\n    }\n    /// Copy constructor; always increases the reference count\n    object(const object &o) : handle(o) { inc_ref(); }\n    /// Move constructor; steals the object from ``other`` and preserves its reference count\n    object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; }\n    /// Destructor; automatically calls `handle::dec_ref()`\n    ~object() { dec_ref(); }\n\n    /** \\rst\n        Resets the internal pointer to ``nullptr`` without decreasing the\n        object's reference count. The function returns a raw handle to the original\n        Python object.\n    \\endrst */\n    handle release() {\n        PyObject *tmp = m_ptr;\n        m_ptr = nullptr;\n        return handle(tmp);\n    }\n\n    object &operator=(const object &other) {\n        // Skip inc_ref and dec_ref if both objects are the same\n        if (!this->is(other)) {\n            other.inc_ref();\n            // Use temporary variable to ensure `*this` remains valid while\n            // `Py_XDECREF` executes, in case `*this` is accessible from Python.\n            handle temp(m_ptr);\n            m_ptr = other.m_ptr;\n            temp.dec_ref();\n        }\n        return *this;\n    }\n\n    object &operator=(object &&other) noexcept {\n        if (this != &other) {\n            handle temp(m_ptr);\n            m_ptr = other.m_ptr;\n            other.m_ptr = nullptr;\n            temp.dec_ref();\n        }\n        return *this;\n    }\n\n#define PYBIND11_INPLACE_OP(iop)                                                                  \\\n    object iop(object_api const &other) { return operator=(handle::iop(other)); }\n\n    PYBIND11_INPLACE_OP(operator+=)\n    PYBIND11_INPLACE_OP(operator-=)\n    PYBIND11_INPLACE_OP(operator*=)\n    PYBIND11_INPLACE_OP(operator/=)\n    PYBIND11_INPLACE_OP(operator|=)\n    PYBIND11_INPLACE_OP(operator&=)\n    PYBIND11_INPLACE_OP(operator^=)\n    PYBIND11_INPLACE_OP(operator<<=)\n    PYBIND11_INPLACE_OP(operator>>=)\n#undef PYBIND11_INPLACE_OP\n\n    // Calling cast() on an object lvalue just copies (via handle::cast)\n    template <typename T>\n    T cast() const &;\n    // Calling on an object rvalue does a move, if needed and/or possible\n    template <typename T>\n    T cast() &&;\n\nprotected:\n    // Tags for choosing constructors from raw PyObject *\n    struct borrowed_t {};\n    struct stolen_t {};\n\n    /// @cond BROKEN\n    template <typename T>\n    friend T reinterpret_borrow(handle);\n    template <typename T>\n    friend T reinterpret_steal(handle);\n    /// @endcond\n\npublic:\n    // Only accessible from derived classes and the reinterpret_* functions\n    object(handle h, borrowed_t) : handle(h) { inc_ref(); }\n    object(handle h, stolen_t) : handle(h) {}\n};\n\n/** \\rst\n    Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference.\n    The target type ``T`` must be `object` or one of its derived classes. The function\n    doesn't do any conversions or checks. It's up to the user to make sure that the\n    target type is correct.\n\n    .. code-block:: cpp\n\n        PyObject *p = PyList_GetItem(obj, index);\n        py::object o = reinterpret_borrow<py::object>(p);\n        // or\n        py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`\n\\endrst */\ntemplate <typename T>\nT reinterpret_borrow(handle h) {\n    return {h, object::borrowed_t{}};\n}\n\n/** \\rst\n    Like `reinterpret_borrow`, but steals the reference.\n\n     .. code-block:: cpp\n\n        PyObject *p = PyObject_Str(obj);\n        py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`\n\\endrst */\ntemplate <typename T>\nT reinterpret_steal(handle h) {\n    return {h, object::stolen_t{}};\n}\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class).\ninline const char *obj_class_name(PyObject *obj) {\n    if (PyType_Check(obj)) {\n        return reinterpret_cast<PyTypeObject *>(obj)->tp_name;\n    }\n    return Py_TYPE(obj)->tp_name;\n}\n\nstd::string error_string();\n\n// The code in this struct is very unusual, to minimize the chances of\n// masking bugs (elsewhere) by errors during the error handling (here).\n// This is meant to be a lifeline for troubleshooting long-running processes\n// that crash under conditions that are virtually impossible to reproduce.\n// Low-level implementation alternatives are preferred to higher-level ones\n// that might raise cascading exceptions. Last-ditch-kind-of attempts are made\n// to report as much of the original error as possible, even if there are\n// secondary issues obtaining some of the details.\nstruct error_fetch_and_normalize {\n    // This comment only applies to Python <= 3.11:\n    //     Immediate normalization is long-established behavior (starting with\n    //     https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011\n    //     from Sep 2016) and safest. Normalization could be deferred, but this could mask\n    //     errors elsewhere, the performance gain is very minor in typical situations\n    //     (usually the dominant bottleneck is EH unwinding), and the implementation here\n    //     would be more complex.\n    // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately.\n    // Any errors during normalization are tracked under __notes__.\n    explicit error_fetch_and_normalize(const char *called) {\n        PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());\n        if (!m_type) {\n            pybind11_fail(\"Internal error: \" + std::string(called)\n                          + \" called while \"\n                            \"Python error indicator not set.\");\n        }\n        const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr());\n        if (exc_type_name_orig == nullptr) {\n            pybind11_fail(\"Internal error: \" + std::string(called)\n                          + \" failed to obtain the name \"\n                            \"of the original active exception type.\");\n        }\n        m_lazy_error_string = exc_type_name_orig;\n#if PY_VERSION_HEX >= 0x030C0000\n        // The presence of __notes__ is likely due to exception normalization\n        // errors, although that is not necessarily true, therefore insert a\n        // hint only:\n        const int has_notes = PyObject_HasAttrString(m_value.ptr(), \"__notes__\");\n        if (has_notes == 1) {\n            m_lazy_error_string += \"[WITH __notes__]\";\n        } else if (has_notes == -1) {\n            // Ignore secondary errors when probing for __notes__ to avoid leaking a\n            // spurious exception while still reporting the original error.\n            PyErr_Clear();\n        }\n#else\n        // PyErr_NormalizeException() may change the exception type if there are cascading\n        // failures. This can potentially be extremely confusing.\n        PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr());\n        if (m_type.ptr() == nullptr) {\n            pybind11_fail(\"Internal error: \" + std::string(called)\n                          + \" failed to normalize the \"\n                            \"active exception.\");\n        }\n        const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr());\n        if (exc_type_name_norm == nullptr) {\n            pybind11_fail(\"Internal error: \" + std::string(called)\n                          + \" failed to obtain the name \"\n                            \"of the normalized active exception type.\");\n        }\n        if (exc_type_name_norm != m_lazy_error_string) {\n            std::string msg = std::string(called)\n                              + \": MISMATCH of original and normalized \"\n                                \"active exception types: \";\n            msg += \"ORIGINAL \";\n            msg += m_lazy_error_string;\n            msg += \" REPLACED BY \";\n            msg += exc_type_name_norm;\n            msg += \": \" + format_value_and_trace();\n            pybind11_fail(msg);\n        }\n#endif\n    }\n\n    error_fetch_and_normalize(const error_fetch_and_normalize &) = delete;\n    error_fetch_and_normalize(error_fetch_and_normalize &&) = delete;\n\n    std::string format_value_and_trace() const {\n        std::string result;\n        std::string message_error_string;\n        if (m_value) {\n            auto value_str = reinterpret_steal<object>(PyObject_Str(m_value.ptr()));\n            constexpr const char *message_unavailable_exc\n                = \"<MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>\";\n            if (!value_str) {\n                message_error_string = detail::error_string();\n                result = message_unavailable_exc;\n            } else {\n                // Not using `value_str.cast<std::string>()`, to not potentially throw a secondary\n                // error_already_set that will then result in process termination (#4288).\n                auto value_bytes = reinterpret_steal<object>(\n                    PyUnicode_AsEncodedString(value_str.ptr(), \"utf-8\", \"backslashreplace\"));\n                if (!value_bytes) {\n                    message_error_string = detail::error_string();\n                    result = message_unavailable_exc;\n                } else {\n                    char *buffer = nullptr;\n                    Py_ssize_t length = 0;\n                    if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) {\n                        message_error_string = detail::error_string();\n                        result = message_unavailable_exc;\n                    } else {\n                        result = std::string(buffer, static_cast<std::size_t>(length));\n                    }\n                }\n            }\n#if PY_VERSION_HEX >= 0x030B0000\n            auto notes\n                = reinterpret_steal<object>(PyObject_GetAttrString(m_value.ptr(), \"__notes__\"));\n            if (!notes) {\n                PyErr_Clear(); // No notes is good news.\n            } else {\n                auto len_notes = PyList_Size(notes.ptr());\n                if (len_notes < 0) {\n                    result += \"\\nFAILURE obtaining len(__notes__): \" + detail::error_string();\n                } else {\n                    result += \"\\n__notes__ (len=\" + std::to_string(len_notes) + \"):\";\n                    for (ssize_t i = 0; i < len_notes; i++) {\n                        PyObject *note = PyList_GET_ITEM(notes.ptr(), i);\n                        auto note_bytes = reinterpret_steal<object>(\n                            PyUnicode_AsEncodedString(note, \"utf-8\", \"backslashreplace\"));\n                        if (!note_bytes) {\n                            result += \"\\nFAILURE obtaining __notes__[\" + std::to_string(i)\n                                      + \"]: \" + detail::error_string();\n                        } else {\n                            char *buffer = nullptr;\n                            Py_ssize_t length = 0;\n                            if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length)\n                                == -1) {\n                                result += \"\\nFAILURE formatting __notes__[\" + std::to_string(i)\n                                          + \"]: \" + detail::error_string();\n                            } else {\n                                result += '\\n';\n                                result += std::string(buffer, static_cast<std::size_t>(length));\n                            }\n                        }\n                    }\n                }\n            }\n#endif\n        } else {\n            result = \"<MESSAGE UNAVAILABLE>\";\n        }\n        if (result.empty()) {\n            result = \"<EMPTY MESSAGE>\";\n        }\n\n        bool have_trace = false;\n        if (m_trace) {\n#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)\n            auto *tb = reinterpret_cast<PyTracebackObject *>(m_trace.ptr());\n\n            // Get the deepest trace possible.\n            while (tb->tb_next) {\n                tb = tb->tb_next;\n            }\n\n            PyFrameObject *frame = tb->tb_frame;\n            Py_XINCREF(frame);\n            result += \"\\n\\nAt:\\n\";\n            while (frame) {\n#    if PY_VERSION_HEX >= 0x030900B1\n                PyCodeObject *f_code = PyFrame_GetCode(frame);\n#    else\n                PyCodeObject *f_code = frame->f_code;\n                Py_INCREF(f_code);\n#    endif\n                int lineno = PyFrame_GetLineNumber(frame);\n                result += \"  \";\n                result += handle(f_code->co_filename).cast<std::string>();\n                result += '(';\n                result += std::to_string(lineno);\n                result += \"): \";\n                result += handle(f_code->co_name).cast<std::string>();\n                result += '\\n';\n                Py_DECREF(f_code);\n#    if PY_VERSION_HEX >= 0x030900B1\n                auto *b_frame = PyFrame_GetBack(frame);\n#    else\n                auto *b_frame = frame->f_back;\n                Py_XINCREF(b_frame);\n#    endif\n                Py_DECREF(frame);\n                frame = b_frame;\n            }\n\n            have_trace = true;\n#endif //! defined(PYPY_VERSION)\n        }\n\n        if (!message_error_string.empty()) {\n            if (!have_trace) {\n                result += '\\n';\n            }\n            result += \"\\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: \" + message_error_string;\n        }\n\n        return result;\n    }\n\n    std::string const &error_string() const {\n        if (!m_lazy_error_string_completed) {\n            m_lazy_error_string += \": \" + format_value_and_trace();\n            m_lazy_error_string_completed = true;\n        }\n        return m_lazy_error_string;\n    }\n\n    void restore() {\n        if (m_restore_called) {\n            pybind11_fail(\"Internal error: pybind11::detail::error_fetch_and_normalize::restore() \"\n                          \"called a second time. ORIGINAL ERROR: \"\n                          + error_string());\n        }\n        PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr());\n        m_restore_called = true;\n    }\n\n    bool matches(handle exc) const {\n        return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);\n    }\n\n    // Not protecting these for simplicity.\n    object m_type, m_value, m_trace;\n\nprivate:\n    // Only protecting invariants.\n    mutable std::string m_lazy_error_string;\n    mutable bool m_lazy_error_string_completed = false;\n    mutable bool m_restore_called = false;\n};\n\ninline std::string error_string() {\n    return error_fetch_and_normalize(\"pybind11::detail::error_string\").error_string();\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n/// Fetch and hold an error which was already set in Python.  An instance of this is typically\n/// thrown to propagate python-side errors back through C++ which can either be caught manually or\n/// else falls back to the function dispatcher (which then raises the captured error back to\n/// python).\nclass PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception {\npublic:\n    /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the\n    /// current Python error indicator.\n    error_already_set()\n        : m_fetched_error{new detail::error_fetch_and_normalize(\"pybind11::error_already_set\"),\n                          m_fetched_error_deleter} {}\n\n    /// The what() result is built lazily on demand.\n    /// WARNING: This member function needs to acquire the Python GIL. This can lead to\n    ///          crashes (undefined behavior) if the Python interpreter is finalizing.\n    const char *what() const noexcept override;\n\n    /// Restores the currently-held Python error (which will clear the Python error indicator first\n    /// if already set).\n    /// NOTE: This member function will always restore the normalized exception, which may or may\n    ///       not be the original Python exception.\n    /// WARNING: The GIL must be held when this member function is called!\n    void restore() { m_fetched_error->restore(); }\n\n    /// If it is impossible to raise the currently-held error, such as in a destructor, we can\n    /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context\n    /// should be some object whose `repr()` helps identify the location of the error. Python\n    /// already knows the type and value of the error, so there is no need to repeat that.\n    void discard_as_unraisable(object err_context) {\n        restore();\n        PyErr_WriteUnraisable(err_context.ptr());\n    }\n    /// An alternate version of `discard_as_unraisable()`, where a string provides information on\n    /// the location of the error. For example, `__func__` could be helpful.\n    /// WARNING: The GIL must be held when this member function is called!\n    void discard_as_unraisable(const char *err_context) {\n        discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));\n    }\n\n    // Does nothing; provided for backwards compatibility.\n    PYBIND11_DEPRECATED(\"Use of error_already_set.clear() is deprecated\")\n    void clear() {}\n\n    /// Check if the currently trapped error type matches the given Python exception class (or a\n    /// subclass thereof).  May also be passed a tuple to search for any exception class matches in\n    /// the given tuple.\n    bool matches(handle exc) const { return m_fetched_error->matches(exc); }\n\n    const object &type() const { return m_fetched_error->m_type; }\n    const object &value() const { return m_fetched_error->m_value; }\n    const object &trace() const { return m_fetched_error->m_trace; }\n\nprivate:\n    std::shared_ptr<detail::error_fetch_and_normalize> m_fetched_error;\n\n    /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to\n    ///          crashes (undefined behavior) if the Python interpreter is finalizing.\n    static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr);\n};\n\n/// Replaces the current Python error indicator with the chosen error, performing a\n/// 'raise from' to indicate that the chosen error was caused by the original error.\ninline void raise_from(PyObject *type, const char *message) {\n    // Based on _PyErr_FormatVFromCause:\n    // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405\n    // See https://github.com/pybind/pybind11/pull/2112 for details.\n    PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;\n\n    assert(PyErr_Occurred());\n    PyErr_Fetch(&exc, &val, &tb);\n    PyErr_NormalizeException(&exc, &val, &tb);\n    if (tb != nullptr) {\n        PyException_SetTraceback(val, tb);\n        Py_DECREF(tb);\n    }\n    Py_DECREF(exc);\n    assert(!PyErr_Occurred());\n\n    PyErr_SetString(type, message);\n\n    PyErr_Fetch(&exc, &val2, &tb);\n    PyErr_NormalizeException(&exc, &val2, &tb);\n    Py_INCREF(val);\n    PyException_SetCause(val2, val);\n    PyException_SetContext(val2, val);\n    PyErr_Restore(exc, val2, tb);\n}\n\n/// Sets the current Python error indicator with the chosen error, performing a 'raise from'\n/// from the error contained in error_already_set to indicate that the chosen error was\n/// caused by the original error.\ninline void raise_from(error_already_set &err, PyObject *type, const char *message) {\n    err.restore();\n    raise_from(type, message);\n}\n\n/** \\defgroup python_builtins const_name\n    Unless stated otherwise, the following C++ functions behave the same\n    as their Python counterparts.\n */\n\n/** \\ingroup python_builtins\n    \\rst\n    Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of\n    `object` or a class which was exposed to Python as ``py::class_<T>``.\n\\endrst */\ntemplate <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>\nbool isinstance(handle obj) {\n    return T::check_(obj);\n}\n\ntemplate <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>\nbool isinstance(handle obj) {\n    return detail::isinstance_native_enum<T>(obj, typeid(T))\n           || detail::isinstance_generic(obj, typeid(T));\n}\n\ntemplate <>\nbool isinstance<handle>(handle) = delete;\ntemplate <>\ninline bool isinstance<object>(handle obj) {\n    return obj.ptr() != nullptr;\n}\n\n/// \\ingroup python_builtins\n/// Return true if ``obj`` is an instance of the ``type``.\ninline bool isinstance(handle obj, handle type) {\n    const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());\n    if (result == -1) {\n        throw error_already_set();\n    }\n    return result != 0;\n}\n\n/// \\addtogroup python_builtins\n/// @{\ninline bool hasattr(handle obj, handle name) {\n    return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1;\n}\n\ninline bool hasattr(handle obj, const char *name) {\n    return PyObject_HasAttrString(obj.ptr(), name) == 1;\n}\n\ninline void delattr(handle obj, handle name) {\n    if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {\n        throw error_already_set();\n    }\n}\n\ninline void delattr(handle obj, const char *name) {\n    if (PyObject_DelAttrString(obj.ptr(), name) != 0) {\n        throw error_already_set();\n    }\n}\n\ninline object getattr(handle obj, handle name) {\n    PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());\n    if (!result) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<object>(result);\n}\n\ninline object getattr(handle obj, const char *name) {\n    PyObject *result = PyObject_GetAttrString(obj.ptr(), name);\n    if (!result) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<object>(result);\n}\n\ninline object getattr(handle obj, handle name, handle default_) {\n    if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {\n        return reinterpret_steal<object>(result);\n    }\n    PyErr_Clear();\n    return reinterpret_borrow<object>(default_);\n}\n\ninline object getattr(handle obj, const char *name, handle default_) {\n    if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {\n        return reinterpret_steal<object>(result);\n    }\n    PyErr_Clear();\n    return reinterpret_borrow<object>(default_);\n}\n\ninline void setattr(handle obj, handle name, handle value) {\n    if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {\n        throw error_already_set();\n    }\n}\n\ninline void setattr(handle obj, const char *name, handle value) {\n    if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {\n        throw error_already_set();\n    }\n}\n\ninline ssize_t hash(handle obj) {\n    auto h = PyObject_Hash(obj.ptr());\n    if (h == -1) {\n        throw error_already_set();\n    }\n    return h;\n}\n\n/// @} python_builtins\n\nPYBIND11_NAMESPACE_BEGIN(detail)\ninline handle get_function(handle value) {\n    if (value) {\n        if (PyInstanceMethod_Check(value.ptr())) {\n            value = PyInstanceMethod_GET_FUNCTION(value.ptr());\n        } else if (PyMethod_Check(value.ptr())) {\n            value = PyMethod_GET_FUNCTION(value.ptr());\n        }\n    }\n    return value;\n}\n\n// Reimplementation of python's dict helper functions to ensure that exceptions\n// aren't swallowed (see #2862)\n\n// copied from cpython _PyDict_GetItemStringWithError\ninline PyObject *dict_getitemstring(PyObject *v, const char *key) {\n    PyObject *kv = nullptr, *rv = nullptr;\n    kv = PyUnicode_FromString(key);\n    if (kv == nullptr) {\n        throw error_already_set();\n    }\n\n    rv = PyDict_GetItemWithError(v, kv);\n    Py_DECREF(kv);\n    if (rv == nullptr && PyErr_Occurred()) {\n        throw error_already_set();\n    }\n    return rv;\n}\n\ninline PyObject *dict_getitem(PyObject *v, PyObject *key) {\n    PyObject *rv = PyDict_GetItemWithError(v, key);\n    if (rv == nullptr && PyErr_Occurred()) {\n        throw error_already_set();\n    }\n    return rv;\n}\n\n// PyDict_GetItemStringRef was added in Python 3.13.0a1.\n// See also: https://github.com/python/pythoncapi-compat/blob/main/pythoncapi_compat.h\ninline PyObject *dict_getitemstringref(PyObject *v, const char *key) {\n#if PY_VERSION_HEX >= 0x030D00A1\n    PyObject *rv = nullptr;\n    if (PyDict_GetItemStringRef(v, key, &rv) < 0) {\n        throw error_already_set();\n    }\n    return rv;\n#else\n    PyObject *rv = dict_getitemstring(v, key);\n    if (rv == nullptr && PyErr_Occurred()) {\n        throw error_already_set();\n    }\n    Py_XINCREF(rv);\n    return rv;\n#endif\n}\n\ninline PyObject *dict_setdefaultstring(PyObject *v, const char *key, PyObject *defaultobj) {\n    PyObject *kv = PyUnicode_FromString(key);\n    if (kv == nullptr) {\n        throw error_already_set();\n    }\n\n    PyObject *rv = PyDict_SetDefault(v, kv, defaultobj);\n    Py_DECREF(kv);\n    if (rv == nullptr) {\n        throw error_already_set();\n    }\n    return rv;\n}\n\n// PyDict_SetDefaultRef was added in Python 3.13.0a4.\n// See also: https://github.com/python/pythoncapi-compat/blob/main/pythoncapi_compat.h\ninline PyObject *dict_setdefaultstringref(PyObject *v, const char *key, PyObject *defaultobj) {\n#if PY_VERSION_HEX >= 0x030D00A4\n    PyObject *kv = PyUnicode_FromString(key);\n    if (kv == nullptr) {\n        throw error_already_set();\n    }\n\n    PyObject *rv = nullptr;\n    if (PyDict_SetDefaultRef(v, kv, defaultobj, &rv) < 0) {\n        Py_DECREF(kv);\n        throw error_already_set();\n    }\n    Py_DECREF(kv);\n    return rv;\n#else\n    PyObject *rv = dict_setdefaultstring(v, key, defaultobj);\n    if (rv == nullptr || PyErr_Occurred()) {\n        throw error_already_set();\n    }\n    Py_XINCREF(rv);\n    return rv;\n#endif\n}\n\n// Helper aliases/functions to support implicit casting of values given to python\n// accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++\n// type, the value goes through pybind11::cast(obj) to convert it to an `object`.\ntemplate <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>\nauto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {\n    return std::forward<T>(o);\n}\n// The following casting version is implemented in cast.h:\ntemplate <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>\nobject object_or_cast(T &&o);\n// Match a PyObject*, which we want to convert directly to handle via its converting constructor\ninline handle object_or_cast(PyObject *ptr) { return ptr; }\n\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified\ntemplate <typename Policy>\nclass accessor : public object_api<accessor<Policy>> {\n    using key_type = typename Policy::key_type;\n\npublic:\n    accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}\n    accessor(const accessor &) = default;\n    accessor(accessor &&) noexcept = default;\n\n    // accessor overload required to override default assignment operator (templates are not\n    // allowed to replace default compiler-generated assignments).\n    void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }\n    void operator=(const accessor &a) & { operator=(handle(a)); }\n\n    template <typename T>\n    enable_if_t<!std::is_same<accessor, remove_reference_t<T>>::value> operator=(T &&value) && {\n        Policy::set(obj, key, object_or_cast(std::forward<T>(value)));\n    }\n    template <typename T>\n    enable_if_t<!std::is_same<accessor, remove_reference_t<T>>::value> operator=(T &&value) & {\n        get_cache() = ensure_object(object_or_cast(std::forward<T>(value)));\n    }\n\n    template <typename T = Policy>\n    PYBIND11_DEPRECATED(\n        \"Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)\")\n    explicit\n    operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value\n                             || std::is_same<T, accessor_policies::obj_attr>::value,\n                         bool>() const {\n        return hasattr(obj, key);\n    }\n    template <typename T = Policy>\n    PYBIND11_DEPRECATED(\"Use of obj[key] as bool is deprecated in favor of obj.contains(key)\")\n    explicit\n    operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {\n        return obj.contains(key);\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator object() const { return get_cache(); }\n    PyObject *ptr() const { return get_cache().ptr(); }\n    template <typename T>\n    T cast() const {\n        return get_cache().template cast<T>();\n    }\n\nprivate:\n    static object ensure_object(object &&o) { return std::move(o); }\n    static object ensure_object(handle h) { return reinterpret_borrow<object>(h); }\n\n    object &get_cache() const {\n        if (!cache) {\n            cache = Policy::get(obj, key);\n        }\n        return cache;\n    }\n\nprivate:\n    handle obj;\n    key_type key;\n    mutable object cache;\n};\nPYBIND11_WARNING_POP\n\nPYBIND11_NAMESPACE_BEGIN(accessor_policies)\nstruct obj_attr {\n    using key_type = object;\n    static object get(handle obj, handle key) { return getattr(obj, key); }\n    static void set(handle obj, handle key, handle val) { setattr(obj, key, val); }\n};\n\nstruct str_attr {\n    using key_type = const char *;\n    static object get(handle obj, const char *key) { return getattr(obj, key); }\n    static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); }\n};\n\nstruct generic_item {\n    using key_type = object;\n\n    static object get(handle obj, handle key) {\n        PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());\n        if (!result) {\n            throw error_already_set();\n        }\n        return reinterpret_steal<object>(result);\n    }\n\n    static void set(handle obj, handle key, handle val) {\n        if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {\n            throw error_already_set();\n        }\n    }\n};\n\nstruct sequence_item {\n    using key_type = size_t;\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static object get(handle obj, const IdxType &index) {\n        PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));\n        if (!result) {\n            throw error_already_set();\n        }\n        return reinterpret_steal<object>(result);\n    }\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static void set(handle obj, const IdxType &index, handle val) {\n        // PySequence_SetItem does not steal a reference to 'val'\n        if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {\n            throw error_already_set();\n        }\n    }\n};\n\nstruct list_item {\n    using key_type = size_t;\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static object get(handle obj, const IdxType &index) {\n        PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));\n        if (!result) {\n            throw error_already_set();\n        }\n        return reinterpret_borrow<object>(result);\n    }\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static void set(handle obj, const IdxType &index, handle val) {\n        // PyList_SetItem steals a reference to 'val'\n        if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {\n            throw error_already_set();\n        }\n    }\n};\n\nstruct tuple_item {\n    using key_type = size_t;\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static object get(handle obj, const IdxType &index) {\n        PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));\n        if (!result) {\n            throw error_already_set();\n        }\n        return reinterpret_borrow<object>(result);\n    }\n\n    template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    static void set(handle obj, const IdxType &index, handle val) {\n        // PyTuple_SetItem steals a reference to 'val'\n        if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {\n            throw error_already_set();\n        }\n    }\n};\nPYBIND11_NAMESPACE_END(accessor_policies)\n\n/// STL iterator template used for tuple, list, sequence and dict\ntemplate <typename Policy>\nclass generic_iterator : public Policy {\n    using It = generic_iterator;\n\npublic:\n    using difference_type = ssize_t;\n    using iterator_category = typename Policy::iterator_category;\n    using value_type = typename Policy::value_type;\n    using reference = typename Policy::reference;\n    using pointer = typename Policy::pointer;\n\n    generic_iterator() = default;\n    generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}\n\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    reference operator*() const { return Policy::dereference(); }\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    reference operator[](difference_type n) const { return *(*this + n); }\n    pointer operator->() const { return **this; }\n\n    It &operator++() {\n        Policy::increment();\n        return *this;\n    }\n    It operator++(int) {\n        auto copy = *this;\n        Policy::increment();\n        return copy;\n    }\n    It &operator--() {\n        Policy::decrement();\n        return *this;\n    }\n    It operator--(int) {\n        auto copy = *this;\n        Policy::decrement();\n        return copy;\n    }\n    It &operator+=(difference_type n) {\n        Policy::advance(n);\n        return *this;\n    }\n    It &operator-=(difference_type n) {\n        Policy::advance(-n);\n        return *this;\n    }\n\n    friend It operator+(const It &a, difference_type n) {\n        auto copy = a;\n        return copy += n;\n    }\n    friend It operator+(difference_type n, const It &b) { return b + n; }\n    friend It operator-(const It &a, difference_type n) {\n        auto copy = a;\n        return copy -= n;\n    }\n    friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }\n\n    friend bool operator==(const It &a, const It &b) { return a.equal(b); }\n    friend bool operator!=(const It &a, const It &b) { return !(a == b); }\n    friend bool operator<(const It &a, const It &b) { return b - a > 0; }\n    friend bool operator>(const It &a, const It &b) { return b < a; }\n    friend bool operator>=(const It &a, const It &b) { return !(a < b); }\n    friend bool operator<=(const It &a, const It &b) { return !(a > b); }\n};\n\nPYBIND11_NAMESPACE_BEGIN(iterator_policies)\n/// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers\ntemplate <typename T>\nstruct arrow_proxy {\n    T value;\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    arrow_proxy(T &&value) noexcept : value(std::move(value)) {}\n    T *operator->() const { return &value; }\n};\n\n/// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS``\nclass sequence_fast_readonly {\nprotected:\n    using iterator_category = std::random_access_iterator_tag;\n    using value_type = handle;\n    using reference = const handle; // PR #3263\n    using pointer = arrow_proxy<const handle>;\n\n    sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}\n    sequence_fast_readonly() = default;\n\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    reference dereference() const { return *ptr; }\n    void increment() { ++ptr; }\n    void decrement() { --ptr; }\n    void advance(ssize_t n) { ptr += n; }\n    bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; }\n    ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; }\n\nprivate:\n    PyObject **ptr;\n};\n\n/// Full read and write access using the sequence protocol: see ``detail::sequence_accessor``\nclass sequence_slow_readwrite {\nprotected:\n    using iterator_category = std::random_access_iterator_tag;\n    using value_type = object;\n    using reference = sequence_accessor;\n    using pointer = arrow_proxy<const sequence_accessor>;\n\n    sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}\n    sequence_slow_readwrite() = default;\n\n    reference dereference() const { return {obj, static_cast<size_t>(index)}; }\n    void increment() { ++index; }\n    void decrement() { --index; }\n    void advance(ssize_t n) { index += n; }\n    bool equal(const sequence_slow_readwrite &b) const { return index == b.index; }\n    ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; }\n\nprivate:\n    handle obj;\n    ssize_t index;\n};\n\n/// Python's dictionary protocol permits this to be a forward iterator\nclass dict_readonly {\nprotected:\n    using iterator_category = std::forward_iterator_tag;\n    using value_type = std::pair<handle, handle>;\n    using reference = const value_type; // PR #3263\n    using pointer = arrow_proxy<const value_type>;\n\n    dict_readonly() = default;\n    dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }\n\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    reference dereference() const { return {key, value}; }\n    void increment() {\n        if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {\n            pos = -1;\n        }\n    }\n    bool equal(const dict_readonly &b) const { return pos == b.pos; }\n\nprivate:\n    handle obj;\n    PyObject *key = nullptr, *value = nullptr;\n    ssize_t pos = -1;\n};\nPYBIND11_NAMESPACE_END(iterator_policies)\n\n#if !defined(PYPY_VERSION)\nusing tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;\nusing list_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;\n#else\nusing tuple_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;\nusing list_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;\n#endif\n\nusing sequence_iterator = generic_iterator<iterator_policies::sequence_slow_readwrite>;\nusing dict_iterator = generic_iterator<iterator_policies::dict_readonly>;\n\ninline bool PyIterable_Check(PyObject *obj) {\n    PyObject *iter = PyObject_GetIter(obj);\n    if (iter) {\n        Py_DECREF(iter);\n        return true;\n    }\n    PyErr_Clear();\n    return false;\n}\n\ninline bool PyNone_Check(PyObject *o) { return o == Py_None; }\ninline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }\n\n#ifdef PYBIND11_STR_LEGACY_PERMISSIVE\ninline bool PyUnicode_Check_Permissive(PyObject *o) {\n    return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);\n}\n#    define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive\n#else\n#    define PYBIND11_STR_CHECK_FUN PyUnicode_Check\n#endif\n\ninline bool PyStaticMethod_Check(PyObject *o) { return Py_TYPE(o) == &PyStaticMethod_Type; }\n\nclass kwargs_proxy : public handle {\npublic:\n    explicit kwargs_proxy(handle h) : handle(h) {}\n};\n\nclass args_proxy : public handle {\npublic:\n    explicit args_proxy(handle h) : handle(h) {}\n    kwargs_proxy operator*() const { return kwargs_proxy(*this); }\n};\n\n/// Python argument categories (using PEP 448 terms)\ntemplate <typename T>\nusing is_keyword = std::is_base_of<arg, T>;\ntemplate <typename T>\nusing is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking\ntemplate <typename T>\nusing is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking\ntemplate <typename T>\nusing is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;\ntemplate <typename T>\nusing is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;\n\n// Call argument collector forward declarations\ntemplate <return_value_policy policy = return_value_policy::automatic_reference>\nclass simple_collector;\ntemplate <return_value_policy policy = return_value_policy::automatic_reference>\nclass unpacking_collector;\n\ninline object get_scope_module(handle scope) {\n    if (scope) {\n        if (hasattr(scope, \"__module__\")) {\n            return scope.attr(\"__module__\");\n        }\n        if (hasattr(scope, \"__name__\")) {\n            return scope.attr(\"__name__\");\n        }\n    }\n    return object();\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n// TODO: After the deprecated constructors are removed, this macro can be simplified by\n//       inheriting ctors: `using Parent::Parent`. It's not an option right now because\n//       the `using` statement triggers the parent deprecation warning even if the ctor\n//       isn't even used.\n#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                            \\\npublic:                                                                                           \\\n    PYBIND11_DEPRECATED(\"Use reinterpret_borrow<\" #Name \">() or reinterpret_steal<\" #Name \">()\")  \\\n    Name(handle h, bool is_borrowed)                                                              \\\n        : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {}                \\\n    Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {}                                       \\\n    Name(handle h, stolen_t) : Parent(h, stolen_t{}) {}                                           \\\n    PYBIND11_DEPRECATED(\"Use py::isinstance<py::python_type>(obj) instead\")                       \\\n    bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); }                     \\\n    static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); }              \\\n    template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */                 \\\n    Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}\n\n#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)                                   \\\n    PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                                \\\n    /* This is deliberately not 'explicit' to allow implicit conversion from object: */           \\\n    /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \\\n    Name(const object &o)                                                                         \\\n        : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) {               \\\n        if (!m_ptr)                                                                               \\\n            throw ::pybind11::error_already_set();                                                \\\n    }                                                                                             \\\n    /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \\\n    Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) {  \\\n        if (!m_ptr)                                                                               \\\n            throw ::pybind11::error_already_set();                                                \\\n    }\n\n#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun)                           \\\n    PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)                                       \\\n    Name() = default;\n\n#define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr)                                                 \\\n    ::pybind11::type_error(\"Object of type '\"                                                     \\\n                           + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr))      \\\n                           + \"' is not an instance of '\" #Name \"'\")\n\n#define PYBIND11_OBJECT(Name, Parent, CheckFun)                                                   \\\n    PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun)                                                \\\n    /* This is deliberately not 'explicit' to allow implicit conversion from object: */           \\\n    /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \\\n    Name(const object &o) : Parent(o) {                                                           \\\n        if (m_ptr && !check_(m_ptr))                                                              \\\n            throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr);                                      \\\n    }                                                                                             \\\n    /* NOLINTNEXTLINE(google-explicit-constructor) */                                             \\\n    Name(object &&o) : Parent(std::move(o)) {                                                     \\\n        if (m_ptr && !check_(m_ptr))                                                              \\\n            throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr);                                      \\\n    }\n\n#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)                                           \\\n    PYBIND11_OBJECT(Name, Parent, CheckFun)                                                       \\\n    Name() = default;\n\n/// \\addtogroup pytypes\n/// @{\n\n/** \\rst\n    Wraps a Python iterator so that it can also be used as a C++ input iterator\n\n    Caveat: copying an iterator does not (and cannot) clone the internal\n    state of the Python iterable. This also applies to the post-increment\n    operator. This iterator should only be used to retrieve the current\n    value using ``operator*()``.\n\\endrst */\nclass iterator : public object {\npublic:\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = ssize_t;\n    using value_type = handle;\n    using reference = const handle; // PR #3263\n    using pointer = const handle *;\n\n    PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)\n\n    iterator &operator++() {\n        init();\n        advance();\n        return *this;\n    }\n\n    iterator operator++(int) {\n        // Note: We must call init() first so that rv.value is\n        // the same as this->value just before calling advance().\n        // Otherwise, dereferencing the returned iterator may call\n        // advance() again and return the 3rd item instead of the 1st.\n        init();\n        auto rv = *this;\n        advance();\n        return rv;\n    }\n\n    // NOLINTNEXTLINE(readability-const-return-type) // PR #3263\n    reference operator*() const {\n        init();\n        return value;\n    }\n\n    pointer operator->() const {\n        init();\n        return &value;\n    }\n\n    /** \\rst\n         The value which marks the end of the iteration. ``it == iterator::sentinel()``\n         is equivalent to catching ``StopIteration`` in Python.\n\n         .. code-block:: cpp\n\n             void foo(py::iterator it) {\n                 while (it != py::iterator::sentinel()) {\n                    // use `*it`\n                    ++it;\n                 }\n             }\n    \\endrst */\n    static iterator sentinel() { return {}; }\n\n    friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); }\n    friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); }\n\nprivate:\n    void init() const {\n        if (m_ptr && !value.ptr()) {\n            auto &self = const_cast<iterator &>(*this);\n            self.advance();\n        }\n    }\n\n    void advance() {\n        value = reinterpret_steal<object>(PyIter_Next(m_ptr));\n        if (value.ptr() == nullptr && PyErr_Occurred()) {\n            throw error_already_set();\n        }\n    }\n\nprivate:\n    object value;\n};\n\nclass type : public object {\npublic:\n    PYBIND11_OBJECT(type, object, PyType_Check)\n\n    /// Return a type handle from a handle or an object\n    static handle handle_of(handle h) {\n        return handle(reinterpret_cast<PyObject *>(Py_TYPE(h.ptr())));\n    }\n\n    /// Return a type object from a handle or an object\n    static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }\n\n    // Defined in pybind11/cast.h\n    /// Convert C++ type to handle if previously registered. Does not convert\n    /// standard types, like int, float. etc. yet.\n    /// See https://github.com/pybind/pybind11/issues/2486\n    template <typename T>\n    static handle handle_of();\n\n    /// Convert C++ type to type if previously registered. Does not convert\n    /// standard types, like int, float. etc. yet.\n    /// See https://github.com/pybind/pybind11/issues/2486\n    template <typename T>\n    static type of() {\n        return type(type::handle_of<T>(), borrowed_t{});\n    }\n};\n\nclass iterable : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)\n};\n\nclass bytes;\n\nclass str : public object {\npublic:\n    PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)\n\n    template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>\n    str(const char *c, const SzType &n)\n        : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {\n        if (!m_ptr) {\n            if (PyErr_Occurred()) {\n                throw error_already_set();\n            }\n            pybind11_fail(\"Could not allocate string object!\");\n        }\n    }\n\n    // 'explicit' is explicitly omitted from the following constructors to allow implicit\n    // conversion to py::str from C++ string-like objects\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    str(const char *c = \"\") : object(PyUnicode_FromString(c), stolen_t{}) {\n        if (!m_ptr) {\n            if (PyErr_Occurred()) {\n                throw error_already_set();\n            }\n            pybind11_fail(\"Could not allocate string object!\");\n        }\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    str(const std::string &s) : str(s.data(), s.size()) {}\n\n#ifdef PYBIND11_HAS_STRING_VIEW\n    // enable_if is needed to avoid \"ambiguous conversion\" errors (see PR #3521).\n    template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    str(T s) : str(s.data(), s.size()) {}\n\n#    ifdef PYBIND11_HAS_U8STRING\n    // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}\n#    endif\n\n#endif\n\n    explicit str(const bytes &b);\n\n    /** \\rst\n        Return a string representation of the object. This is analogous to\n        the ``str()`` function in Python.\n    \\endrst */\n    // Templatized to avoid ambiguity with str(const object&) for object-derived types.\n    template <typename T,\n              detail::enable_if_t<!std::is_base_of<object, detail::remove_cvref_t<T>>::value\n                                      && std::is_constructible<handle, T>::value,\n                                  int>\n              = 0>\n    explicit str(T &&h) : object(raw_str(handle(std::forward<T>(h)).ptr()), stolen_t{}) {\n        if (!m_ptr) {\n            throw error_already_set();\n        }\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator std::string() const {\n        object temp = *this;\n        if (PyUnicode_Check(m_ptr)) {\n            temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));\n            if (!temp) {\n                throw error_already_set();\n            }\n        }\n        char *buffer = nullptr;\n        ssize_t length = 0;\n        if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {\n            throw error_already_set();\n        }\n        return std::string(buffer, static_cast<size_t>(length));\n    }\n\n    template <typename... Args>\n    str format(Args &&...args) const {\n        return attr(\"format\")(std::forward<Args>(args)...);\n    }\n\nprivate:\n    /// Return string representation -- always returns a new reference, even if already a str\n    static PyObject *raw_str(PyObject *op) {\n        PyObject *str_value = PyObject_Str(op);\n        return str_value;\n    }\n};\n/// @} pytypes\n\ninline namespace literals {\n/** \\rst\n    String literal version of `str`\n \\endrst */\ninline str\n#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5\noperator\"\" _s // gcc 4.8.5 insists on having a space (hard error).\n#else\noperator\"\"_s // clang 17 generates a deprecation warning if there is a space.\n#endif\n    (const char *s, size_t size) {\n    return {s, size};\n}\n} // namespace literals\n\n/// \\addtogroup pytypes\n/// @{\nclass bytes : public object {\npublic:\n    PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)\n\n    // Allow implicit conversion:\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    bytes(const char *c = \"\") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate bytes object!\");\n        }\n    }\n\n    template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>\n    bytes(const char *c, const SzType &n)\n        : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate bytes object!\");\n        }\n    }\n\n    // Allow implicit conversion:\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    bytes(const std::string &s) : bytes(s.data(), s.size()) {}\n\n    explicit bytes(const pybind11::str &s);\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator std::string() const { return string_op<std::string>(); }\n\n#ifdef PYBIND11_HAS_STRING_VIEW\n    // enable_if is needed to avoid \"ambiguous conversion\" errors (see PR #3521).\n    template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    bytes(T s) : bytes(s.data(), s.size()) {}\n\n    // Obtain a string view that views the current `bytes` buffer value.  Note that this is only\n    // valid so long as the `bytes` instance remains alive and so generally should not outlive the\n    // lifetime of the `bytes` instance.\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator std::string_view() const { return string_op<std::string_view>(); }\n#endif\nprivate:\n    template <typename T>\n    T string_op() const {\n        char *buffer = nullptr;\n        ssize_t length = 0;\n        if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) {\n            throw error_already_set();\n        }\n        return {buffer, static_cast<size_t>(length)};\n    }\n};\n// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors\n// are included in the doxygen group; close here and reopen after as a workaround\n/// @} pytypes\n\ninline bytes::bytes(const pybind11::str &s) {\n    object temp = s;\n    if (PyUnicode_Check(s.ptr())) {\n        temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));\n        if (!temp) {\n            throw error_already_set();\n        }\n    }\n    char *buffer = nullptr;\n    ssize_t length = 0;\n    if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {\n        throw error_already_set();\n    }\n    auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));\n    if (!obj) {\n        pybind11_fail(\"Could not allocate bytes object!\");\n    }\n    m_ptr = obj.release().ptr();\n}\n\ninline str::str(const bytes &b) {\n    char *buffer = nullptr;\n    ssize_t length = 0;\n    if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) {\n        throw error_already_set();\n    }\n    auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));\n    if (!obj) {\n        if (PyErr_Occurred()) {\n            throw error_already_set();\n        }\n        pybind11_fail(\"Could not allocate string object!\");\n    }\n    m_ptr = obj.release().ptr();\n}\n\n/// \\addtogroup pytypes\n/// @{\nclass bytearray : public object {\npublic:\n    PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)\n\n    template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>\n    bytearray(const char *c, const SzType &n)\n        : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate bytearray object!\");\n        }\n    }\n\n    bytearray() : bytearray(\"\", 0) {}\n\n    explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}\n\n    size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }\n\n    explicit operator std::string() const {\n        char *buffer = PyByteArray_AS_STRING(m_ptr);\n        ssize_t size = PyByteArray_GET_SIZE(m_ptr);\n        return std::string(buffer, static_cast<size_t>(size));\n    }\n};\n// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors\n// are included in the doxygen group; close here and reopen after as a workaround\n/// @} pytypes\n\n/// \\addtogroup pytypes\n/// @{\nclass none : public object {\npublic:\n    PYBIND11_OBJECT(none, object, detail::PyNone_Check)\n    none() : object(Py_None, borrowed_t{}) {}\n};\n\nclass ellipsis : public object {\npublic:\n    PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)\n    ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}\n};\n\nclass bool_ : public object {\npublic:\n    PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)\n    bool_() : object(Py_False, borrowed_t{}) {}\n    // Allow implicit conversion from and to `bool`:\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }\n\nprivate:\n    /// Return the truth value of an object -- always returns a new reference\n    static PyObject *raw_bool(PyObject *op) {\n        const auto value = PyObject_IsTrue(op);\n        if (value == -1) {\n            return nullptr;\n        }\n        return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();\n    }\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n// Converts a value to the given unsigned type.  If an error occurs, you get back (Unsigned) -1;\n// otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).\n// (The distinction is critically important when casting a returned -1 error value to some other\n// unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).\ntemplate <typename Unsigned>\nUnsigned as_unsigned(PyObject *o) {\n    if (sizeof(Unsigned) <= sizeof(unsigned long)) {\n        unsigned long v = PyLong_AsUnsignedLong(o);\n        return v == static_cast<unsigned long>(-1) && PyErr_Occurred() ? (Unsigned) -1\n                                                                       : (Unsigned) v;\n    }\n    unsigned long long v = PyLong_AsUnsignedLongLong(o);\n    return v == static_cast<unsigned long long>(-1) && PyErr_Occurred() ? (Unsigned) -1\n                                                                        : (Unsigned) v;\n}\nPYBIND11_NAMESPACE_END(detail)\n\nclass int_ : public object {\npublic:\n    PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)\n    int_() : object(PyLong_FromLong(0), stolen_t{}) {}\n    // Allow implicit conversion from C++ integral types:\n    template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    int_(T value) {\n        if (sizeof(T) <= sizeof(long)) {\n            if (std::is_signed<T>::value) {\n                m_ptr = PyLong_FromLong((long) value);\n            } else {\n                m_ptr = PyLong_FromUnsignedLong((unsigned long) value);\n            }\n        } else {\n            if (std::is_signed<T>::value) {\n                m_ptr = PyLong_FromLongLong((long long) value);\n            } else {\n                m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);\n            }\n        }\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate int object!\");\n        }\n    }\n\n    template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator T() const {\n        return std::is_unsigned<T>::value  ? detail::as_unsigned<T>(m_ptr)\n               : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)\n                                           : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);\n    }\n};\n\nclass float_ : public object {\npublic:\n    PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)\n    // Allow implicit conversion from float/double:\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    float_(float value) : object(PyFloat_FromDouble(static_cast<double>(value)), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate float object!\");\n        }\n    }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    float_(double value = .0) : object(PyFloat_FromDouble(value), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate float object!\");\n        }\n    }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator float() const { return static_cast<float>(PyFloat_AsDouble(m_ptr)); }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator double() const { return PyFloat_AsDouble(m_ptr); }\n};\n\nclass weakref : public object {\npublic:\n    PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)\n    explicit weakref(handle obj, handle callback = {})\n        : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {\n        if (!m_ptr) {\n            if (PyErr_Occurred()) {\n                throw error_already_set();\n            }\n            pybind11_fail(\"Could not allocate weak reference!\");\n        }\n    }\n\nprivate:\n    static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }\n};\n\nclass slice : public object {\npublic:\n    PYBIND11_OBJECT(slice, object, PySlice_Check)\n    slice(handle start, handle stop, handle step)\n        : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate slice object!\");\n        }\n    }\n    slice() : slice(none(), none(), none()) {}\n\n#ifdef PYBIND11_HAS_OPTIONAL\n    slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)\n        : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}\n#else\n    slice(ssize_t start_, ssize_t stop_, ssize_t step_)\n        : slice(int_(start_), int_(stop_), int_(step_)) {}\n#endif\n\n    bool\n    compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {\n        return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,\n                                    (ssize_t) length,\n                                    (ssize_t *) start,\n                                    (ssize_t *) stop,\n                                    (ssize_t *) step,\n                                    (ssize_t *) slicelength)\n               == 0;\n    }\n    bool compute(\n        ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {\n        return PySlice_GetIndicesEx(\n                   (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)\n               == 0;\n    }\n\nprivate:\n    template <typename T>\n    static object index_to_object(T index) {\n        return index ? object(int_(*index)) : object(none());\n    }\n};\n\nclass capsule : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)\n    PYBIND11_DEPRECATED(\"Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()\")\n    capsule(PyObject *ptr, bool is_borrowed)\n        : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}\n\n    explicit capsule(const void *value,\n                     const char *name = nullptr,\n                     PyCapsule_Destructor destructor = nullptr)\n        : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {\n        if (!m_ptr) {\n            throw error_already_set();\n        }\n    }\n\n    PYBIND11_DEPRECATED(\"Please use the ctor with value, name, destructor args\")\n    capsule(const void *value, PyCapsule_Destructor destructor)\n        : object(PyCapsule_New(const_cast<void *>(value), nullptr, destructor), stolen_t{}) {\n        if (!m_ptr) {\n            throw error_already_set();\n        }\n    }\n\n    /// Capsule name is nullptr.\n    capsule(const void *value, void (*destructor)(void *)) {\n        initialize_with_void_ptr_destructor(value, nullptr, destructor);\n    }\n\n    capsule(const void *value, const char *name, void (*destructor)(void *)) {\n        initialize_with_void_ptr_destructor(value, name, destructor);\n    }\n\n    explicit capsule(void (*destructor)()) {\n        m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {\n            const char *name = get_name_in_error_scope(o);\n            auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, name));\n            if (destructor == nullptr) {\n                throw error_already_set();\n            }\n            destructor();\n        });\n\n        if (!m_ptr) {\n            throw error_already_set();\n        }\n    }\n\n    template <typename T>\n    operator T *() const { // NOLINT(google-explicit-constructor)\n        return get_pointer<T>();\n    }\n\n    /// Get the pointer the capsule holds.\n    template <typename T = void>\n    T *get_pointer() const {\n        const auto *name = this->name();\n        T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));\n        if (!result) {\n            throw error_already_set();\n        }\n        return result;\n    }\n\n    /// Replaces a capsule's pointer *without* calling the destructor on the existing one.\n    void set_pointer(const void *value) {\n        if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {\n            throw error_already_set();\n        }\n    }\n\n    const char *name() const {\n        const char *name = PyCapsule_GetName(m_ptr);\n        if ((name == nullptr) && PyErr_Occurred()) {\n            throw error_already_set();\n        }\n        return name;\n    }\n\n    /// Replaces a capsule's name *without* calling the destructor on the existing one.\n    void set_name(const char *new_name) {\n        if (PyCapsule_SetName(m_ptr, new_name) != 0) {\n            throw error_already_set();\n        }\n    }\n\nprivate:\n    static const char *get_name_in_error_scope(PyObject *o) {\n        error_scope error_guard;\n\n        const char *name = PyCapsule_GetName(o);\n        if ((name == nullptr) && PyErr_Occurred()) {\n            // write out and consume error raised by call to PyCapsule_GetName\n            PyErr_WriteUnraisable(o);\n        }\n\n        return name;\n    }\n\n    void initialize_with_void_ptr_destructor(const void *value,\n                                             const char *name,\n                                             void (*destructor)(void *)) {\n        m_ptr = PyCapsule_New(const_cast<void *>(value), name, [](PyObject *o) {\n            // guard if destructor called while err indicator is set\n            error_scope error_guard;\n            auto destructor = reinterpret_cast<void (*)(void *)>(PyCapsule_GetContext(o));\n            if (destructor == nullptr && PyErr_Occurred()) {\n                throw error_already_set();\n            }\n            const char *name = get_name_in_error_scope(o);\n            void *ptr = PyCapsule_GetPointer(o, name);\n            if (ptr == nullptr) {\n                throw error_already_set();\n            }\n\n            if (destructor != nullptr) {\n                destructor(ptr);\n            }\n        });\n\n        if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast<void *>(destructor)) != 0) {\n            throw error_already_set();\n        }\n    }\n};\n\nclass tuple : public object {\npublic:\n    PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)\n    template <typename SzType = ssize_t,\n              detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>\n    // Some compilers generate link errors when using `const SzType &` here:\n    explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate tuple object!\");\n        }\n    }\n    size_t size() const { return static_cast<size_t>(PyTuple_Size(m_ptr)); }\n    bool empty() const { return size() == 0; }\n    detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }\n    template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>\n    detail::item_accessor operator[](T &&o) const {\n        return object::operator[](std::forward<T>(o));\n    }\n    detail::tuple_iterator begin() const { return {*this, 0}; }\n    detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }\n};\n\n// We need to put this into a separate function because the Intel compiler\n// fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below\n// (tested with ICC 2021.1 Beta 20200827).\ntemplate <typename... Args>\nconstexpr bool args_are_all_keyword_or_ds() {\n    return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;\n}\n\nclass dict : public object {\npublic:\n    PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)\n    dict() : object(PyDict_New(), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate dict object!\");\n        }\n    }\n    template <typename... Args,\n              typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,\n              // MSVC workaround: it can't compile an out-of-line definition, so defer the\n              // collector\n              typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>\n    explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}\n\n    size_t size() const { return static_cast<size_t>(PyDict_Size(m_ptr)); }\n    bool empty() const { return size() == 0; }\n    detail::dict_iterator begin() const { return {*this, 0}; }\n    detail::dict_iterator end() const { return {}; }\n    void clear() /* py-non-const */ { PyDict_Clear(ptr()); }\n    template <typename T>\n    bool contains(T &&key) const {\n        auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr());\n        if (result == -1) {\n            throw error_already_set();\n        }\n        return result == 1;\n    }\n\nprivate:\n    /// Call the `dict` Python type -- always returns a new reference\n    static PyObject *raw_dict(PyObject *op) {\n        if (PyDict_Check(op)) {\n            return handle(op).inc_ref().ptr();\n        }\n        return PyObject_CallFunctionObjArgs(\n            reinterpret_cast<PyObject *>(&PyDict_Type), op, nullptr);\n    }\n};\n\nclass sequence : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)\n    size_t size() const {\n        ssize_t result = PySequence_Size(m_ptr);\n        if (result == -1) {\n            throw error_already_set();\n        }\n        return static_cast<size_t>(result);\n    }\n    bool empty() const { return size() == 0; }\n    detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }\n    template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>\n    detail::item_accessor operator[](T &&o) const {\n        return object::operator[](std::forward<T>(o));\n    }\n    detail::sequence_iterator begin() const { return {*this, 0}; }\n    detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; }\n};\n\nclass list : public object {\npublic:\n    PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)\n    template <typename SzType = ssize_t,\n              detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>\n    // Some compilers generate link errors when using `const SzType &` here:\n    explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate list object!\");\n        }\n    }\n    size_t size() const { return static_cast<size_t>(PyList_Size(m_ptr)); }\n    bool empty() const { return size() == 0; }\n    detail::list_accessor operator[](size_t index) const { return {*this, index}; }\n    template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>\n    detail::item_accessor operator[](T &&o) const {\n        return object::operator[](std::forward<T>(o));\n    }\n    detail::list_iterator begin() const { return {*this, 0}; }\n    detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }\n    template <typename T>\n    void append(T &&val) /* py-non-const */ {\n        if (PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) != 0) {\n            throw error_already_set();\n        }\n    }\n    template <typename IdxType,\n              typename ValType,\n              detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>\n    void insert(const IdxType &index, ValType &&val) /* py-non-const */ {\n        if (PyList_Insert(m_ptr,\n                          ssize_t_cast(index),\n                          detail::object_or_cast(std::forward<ValType>(val)).ptr())\n            != 0) {\n            throw error_already_set();\n        }\n    }\n    void clear() /* py-non-const */ {\n        if (PyList_SetSlice(m_ptr, 0, PyList_Size(m_ptr), nullptr) == -1) {\n            throw error_already_set();\n        }\n    }\n};\n\nclass args : public tuple {\n    PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)\n};\nclass kwargs : public dict {\n    PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)\n};\n\n// Subclasses of args and kwargs to support type hinting\n// as defined in PEP 484. See #5357 for more info.\ntemplate <typename T>\nclass Args : public args {\n    using args::args;\n};\n\ntemplate <typename T>\nclass KWArgs : public kwargs {\n    using kwargs::kwargs;\n};\n\nclass anyset : public object {\npublic:\n    PYBIND11_OBJECT(anyset, object, PyAnySet_Check)\n    size_t size() const { return static_cast<size_t>(PySet_Size(m_ptr)); }\n    bool empty() const { return size() == 0; }\n    template <typename T>\n    bool contains(T &&val) const {\n        auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());\n        if (result == -1) {\n            throw error_already_set();\n        }\n        return result == 1;\n    }\n};\n\nclass set : public anyset {\npublic:\n    PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New)\n    set() : anyset(PySet_New(nullptr), stolen_t{}) {\n        if (!m_ptr) {\n            pybind11_fail(\"Could not allocate set object!\");\n        }\n    }\n    template <typename T>\n    bool add(T &&val) /* py-non-const */ {\n        return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;\n    }\n    void clear() /* py-non-const */ { PySet_Clear(m_ptr); }\n};\n\nclass frozenset : public anyset {\npublic:\n    PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New)\n};\n\nclass function : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)\n    handle cpp_function() const {\n        handle fun = detail::get_function(m_ptr);\n        if (fun && PyCFunction_Check(fun.ptr())) {\n            return fun;\n        }\n        return handle();\n    }\n    bool is_cpp_function() const { return (bool) cpp_function(); }\n};\n\nclass staticmethod : public object {\npublic:\n    PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)\n};\n\nclass buffer : public object {\npublic:\n    PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)\n\n    buffer_info request(bool writable = false) const {\n        int flags = PyBUF_STRIDES | PyBUF_FORMAT;\n        if (writable) {\n            flags |= PyBUF_WRITABLE;\n        }\n        auto *view = new Py_buffer();\n        if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {\n            delete view;\n            throw error_already_set();\n        }\n        return buffer_info(view);\n    }\n};\n\nclass memoryview : public object {\npublic:\n    PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)\n\n    /** \\rst\n        Creates ``memoryview`` from ``buffer_info``.\n\n        ``buffer_info`` must be created from ``buffer::request()``. Otherwise\n        throws an exception.\n\n        For creating a ``memoryview`` from objects that support buffer protocol,\n        use ``memoryview(const object& obj)`` instead of this constructor.\n     \\endrst */\n    explicit memoryview(const buffer_info &info) {\n        if (!info.view()) {\n            pybind11_fail(\"Prohibited to create memoryview without Py_buffer\");\n        }\n        // Note: PyMemoryView_FromBuffer never increments obj reference.\n        m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)\n                                   : PyMemoryView_FromBuffer(info.view());\n        if (!m_ptr) {\n            pybind11_fail(\"Unable to create memoryview from buffer descriptor\");\n        }\n    }\n\n    /** \\rst\n        Creates ``memoryview`` from static buffer.\n\n        This method is meant for providing a ``memoryview`` for C/C++ buffer not\n        managed by Python. The caller is responsible for managing the lifetime\n        of ``ptr`` and ``format``, which MUST outlive the memoryview constructed\n        here.\n\n        See also: Python C API documentation for `PyMemoryView_FromBuffer`_.\n\n        .. _PyMemoryView_FromBuffer:\n           https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer\n\n        :param ptr: Pointer to the buffer.\n        :param itemsize: Byte size of an element.\n        :param format: Pointer to the null-terminated format string. For\n            homogeneous Buffers, this should be set to\n            ``format_descriptor<T>::value``.\n        :param shape: Shape of the tensor (1 entry per dimension).\n        :param strides: Number of bytes between adjacent entries (for each\n            per dimension).\n        :param readonly: Flag to indicate if the underlying storage may be\n            written to.\n     \\endrst */\n    static memoryview from_buffer(void *ptr,\n                                  ssize_t itemsize,\n                                  const char *format,\n                                  detail::any_container<ssize_t> shape,\n                                  detail::any_container<ssize_t> strides,\n                                  bool readonly = false);\n\n    static memoryview from_buffer(const void *ptr,\n                                  ssize_t itemsize,\n                                  const char *format,\n                                  detail::any_container<ssize_t> shape,\n                                  detail::any_container<ssize_t> strides) {\n        return memoryview::from_buffer(\n            const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);\n    }\n\n    template <typename T>\n    static memoryview from_buffer(T *ptr,\n                                  detail::any_container<ssize_t> shape,\n                                  detail::any_container<ssize_t> strides,\n                                  bool readonly = false) {\n        return memoryview::from_buffer(reinterpret_cast<void *>(ptr),\n                                       sizeof(T),\n                                       format_descriptor<T>::value,\n                                       std::move(shape),\n                                       std::move(strides),\n                                       readonly);\n    }\n\n    template <typename T>\n    static memoryview from_buffer(const T *ptr,\n                                  detail::any_container<ssize_t> shape,\n                                  detail::any_container<ssize_t> strides) {\n        return memoryview::from_buffer(\n            const_cast<T *>(ptr), std::move(shape), std::move(strides), true);\n    }\n\n    /** \\rst\n        Creates ``memoryview`` from static memory.\n\n        This method is meant for providing a ``memoryview`` for C/C++ buffer not\n        managed by Python. The caller is responsible for managing the lifetime\n        of ``mem``, which MUST outlive the memoryview constructed here.\n\n        See also: Python C API documentation for `PyMemoryView_FromBuffer`_.\n\n        .. _PyMemoryView_FromMemory:\n           https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory\n     \\endrst */\n    static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {\n        PyObject *ptr = PyMemoryView_FromMemory(\n            reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);\n        if (!ptr) {\n            pybind11_fail(\"Could not allocate memoryview object!\");\n        }\n        return memoryview(object(ptr, stolen_t{}));\n    }\n\n    static memoryview from_memory(const void *mem, ssize_t size) {\n        return memoryview::from_memory(const_cast<void *>(mem), size, true);\n    }\n\n#ifdef PYBIND11_HAS_STRING_VIEW\n    static memoryview from_memory(std::string_view mem) {\n        return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);\n    }\n#endif\n};\n\n/// @cond DUPLICATE\ninline memoryview memoryview::from_buffer(void *ptr,\n                                          ssize_t itemsize,\n                                          const char *format,\n                                          detail::any_container<ssize_t> shape,\n                                          detail::any_container<ssize_t> strides,\n                                          bool readonly) {\n    size_t ndim = shape->size();\n    if (ndim != strides->size()) {\n        pybind11_fail(\"memoryview: shape length doesn't match strides length\");\n    }\n    ssize_t size = ndim != 0u ? 1 : 0;\n    for (size_t i = 0; i < ndim; ++i) {\n        size *= (*shape)[i];\n    }\n    Py_buffer view;\n    view.buf = ptr;\n    view.obj = nullptr;\n    view.len = size * itemsize;\n    view.readonly = static_cast<int>(readonly);\n    view.itemsize = itemsize;\n    view.format = const_cast<char *>(format);\n    view.ndim = static_cast<int>(ndim);\n    view.shape = shape->data();\n    view.strides = strides->data();\n    view.suboffsets = nullptr;\n    view.internal = nullptr;\n    PyObject *obj = PyMemoryView_FromBuffer(&view);\n    if (!obj) {\n        throw error_already_set();\n    }\n    return memoryview(object(obj, stolen_t{}));\n}\n/// @endcond\n/// @} pytypes\n\n/// \\addtogroup python_builtins\n/// @{\n\n/// Get the length of a Python object.\ninline size_t len(handle h) {\n    ssize_t result = PyObject_Length(h.ptr());\n    if (result < 0) {\n        throw error_already_set();\n    }\n    return static_cast<size_t>(result);\n}\n\n/// Get the length hint of a Python object.\n/// Returns 0 when this cannot be determined.\ninline size_t len_hint(handle h) {\n    ssize_t result = PyObject_LengthHint(h.ptr(), 0);\n    if (result < 0) {\n        // Sometimes a length can't be determined at all (eg generators)\n        // In which case simply return 0\n        PyErr_Clear();\n        return 0;\n    }\n    return static_cast<size_t>(result);\n}\n\ninline str repr(handle h) {\n    PyObject *str_value = PyObject_Repr(h.ptr());\n    if (!str_value) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<str>(str_value);\n}\n\ninline iterator iter(handle obj) {\n    PyObject *result = PyObject_GetIter(obj.ptr());\n    if (!result) {\n        throw error_already_set();\n    }\n    return reinterpret_steal<iterator>(result);\n}\n/// @} python_builtins\n\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <typename D>\niterator object_api<D>::begin() const {\n    return iter(derived());\n}\ntemplate <typename D>\niterator object_api<D>::end() const {\n    return iterator::sentinel();\n}\ntemplate <typename D>\nitem_accessor object_api<D>::operator[](handle key) const {\n    return {derived(), reinterpret_borrow<object>(key)};\n}\ntemplate <typename D>\nitem_accessor object_api<D>::operator[](object &&key) const {\n    return {derived(), std::move(key)};\n}\ntemplate <typename D>\nitem_accessor object_api<D>::operator[](const char *key) const {\n    return {derived(), pybind11::str(key)};\n}\ntemplate <typename D>\nobj_attr_accessor object_api<D>::attr(handle key) const {\n    return {derived(), reinterpret_borrow<object>(key)};\n}\ntemplate <typename D>\nobj_attr_accessor object_api<D>::attr(object &&key) const {\n    return {derived(), std::move(key)};\n}\ntemplate <typename D>\nstr_attr_accessor object_api<D>::attr(const char *key) const {\n    return {derived(), key};\n}\ntemplate <typename D>\nargs_proxy object_api<D>::operator*() const {\n    return args_proxy(derived().ptr());\n}\ntemplate <typename D>\ntemplate <typename T>\nbool object_api<D>::contains(T &&item) const {\n    return attr(\"__contains__\")(std::forward<T>(item)).template cast<bool>();\n}\n\ntemplate <typename D>\npybind11::str object_api<D>::str() const {\n    return pybind11::str(derived());\n}\n\ntemplate <typename D>\nstr_attr_accessor object_api<D>::doc() const {\n    return attr(\"__doc__\");\n}\n\ntemplate <typename D>\nobject object_api<D>::annotations() const {\n// This is needed again because of the lazy annotations added in 3.14+\n#if PY_VERSION_HEX < 0x030A0000 || PY_VERSION_HEX >= 0x030E0000\n    // https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older\n    if (!hasattr(derived(), \"__annotations__\")) {\n        setattr(derived(), \"__annotations__\", dict());\n    }\n    return attr(\"__annotations__\");\n#else\n    return getattr(derived(), \"__annotations__\", dict());\n#endif\n}\n\ntemplate <typename D>\nhandle object_api<D>::get_type() const {\n    return type::handle_of(derived());\n}\n\ntemplate <typename D>\nbool object_api<D>::rich_compare(object_api const &other, int value) const {\n    int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);\n    if (rv == -1) {\n        throw error_already_set();\n    }\n    return rv == 1;\n}\n\n#define PYBIND11_MATH_OPERATOR_UNARY(op, fn)                                                      \\\n    template <typename D>                                                                         \\\n    object object_api<D>::op() const {                                                            \\\n        object result = reinterpret_steal<object>(fn(derived().ptr()));                           \\\n        if (!result.ptr())                                                                        \\\n            throw error_already_set();                                                            \\\n        return result;                                                                            \\\n    }\n\n#define PYBIND11_MATH_OPERATOR_BINARY(op, fn)                                                     \\\n    template <typename D>                                                                         \\\n    object object_api<D>::op(object_api const &other) const {                                     \\\n        object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr()));    \\\n        if (!result.ptr())                                                                        \\\n            throw error_already_set();                                                            \\\n        return result;                                                                            \\\n    }\n\n#define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn)                                            \\\n    template <typename D>                                                                         \\\n    object object_api<D>::iop(object_api const &other) {                                          \\\n        object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr()));    \\\n        if (!result.ptr())                                                                        \\\n            throw error_already_set();                                                            \\\n        return result;                                                                            \\\n    }\n\nPYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)\nPYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)\nPYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd)\nPYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract)\nPYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply)\nPYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide)\nPYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr)\nPYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd)\nPYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor)\nPYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift)\nPYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)\nPYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift)\n\n#undef PYBIND11_MATH_OPERATOR_UNARY\n#undef PYBIND11_MATH_OPERATOR_BINARY\n#undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE\n\n// Meant to return a Python str, but this is not checked.\ninline object get_module_name_if_available(handle scope) {\n    if (scope) {\n        if (hasattr(scope, \"__module__\")) {\n            return scope.attr(\"__module__\");\n        }\n        if (hasattr(scope, \"__name__\")) {\n            return scope.attr(\"__name__\");\n        }\n    }\n    return object();\n}\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/stl/filesystem.h",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include <pybind11/cast.h>\n#include <pybind11/detail/common.h>\n#include <pybind11/detail/descr.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/pytypes.h>\n\n#include <string>\n\n#if defined(PYBIND11_HAS_FILESYSTEM)\n#    include <filesystem>\n#elif defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)\n#    include <experimental/filesystem>\n#else\n#    error \"Neither #include <filesystem> nor #include <experimental/filesystem> is available.\"\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n#ifdef PYPY_VERSION\n#    define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...) (__VA_ARGS__)\n#else\n#    define PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(...)                                   \\\n        (reinterpret_cast<void *>(__VA_ARGS__))\n#endif\n\n#if defined(PYBIND11_HAS_FILESYSTEM) || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)\ntemplate <typename T>\nstruct path_caster {\n\nprivate:\n    static PyObject *unicode_from_fs_native(const std::string &w) {\n#    if !defined(PYPY_VERSION)\n        return PyUnicode_DecodeFSDefaultAndSize(w.c_str(), ssize_t(w.size()));\n#    else\n        // PyPy mistakenly declares the first parameter as non-const.\n        return PyUnicode_DecodeFSDefaultAndSize(const_cast<char *>(w.c_str()), ssize_t(w.size()));\n#    endif\n    }\n\n    static PyObject *unicode_from_fs_native(const std::wstring &w) {\n        return PyUnicode_FromWideChar(w.c_str(), ssize_t(w.size()));\n    }\n\npublic:\n    static handle cast(const T &path, return_value_policy, handle) {\n        if (auto py_str = unicode_from_fs_native(path.native())) {\n            return module_::import(\"pathlib\")\n                .attr(\"Path\")(reinterpret_steal<object>(py_str))\n                .release();\n        }\n        return nullptr;\n    }\n\n    bool load(handle handle, bool) {\n        // PyUnicode_FSConverter and PyUnicode_FSDecoder normally take care of\n        // calling PyOS_FSPath themselves, but that's broken on PyPy (PyPy\n        // issue #3168) so we do it ourselves instead.\n        PyObject *buf = PyOS_FSPath(handle.ptr());\n        if (!buf) {\n            PyErr_Clear();\n            return false;\n        }\n        PyObject *native = nullptr;\n        if constexpr (std::is_same_v<typename T::value_type, char>) {\n            if (PyUnicode_FSConverter(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))\n                != 0) {\n                if (auto *c_str = PyBytes_AsString(native)) {\n                    // AsString returns a pointer to the internal buffer, which\n                    // must not be free'd.\n                    value = c_str;\n                }\n            }\n        } else if constexpr (std::is_same_v<typename T::value_type, wchar_t>) {\n            if (PyUnicode_FSDecoder(buf, PYBIND11_REINTERPRET_CAST_VOID_PTR_IF_NOT_PYPY(&native))\n                != 0) {\n                if (auto *c_str = PyUnicode_AsWideCharString(native, nullptr)) {\n                    // AsWideCharString returns a new string that must be free'd.\n                    value = c_str; // Copies the string.\n                    PyMem_Free(c_str);\n                }\n            }\n        }\n        Py_XDECREF(native);\n        Py_DECREF(buf);\n        if (PyErr_Occurred()) {\n            PyErr_Clear();\n            return false;\n        }\n        return true;\n    }\n\n    PYBIND11_TYPE_CASTER(T, io_name(\"os.PathLike | str | bytes\", \"pathlib.Path\"));\n};\n\n#endif // PYBIND11_HAS_FILESYSTEM || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)\n\n#if defined(PYBIND11_HAS_FILESYSTEM)\ntemplate <>\nstruct type_caster<std::filesystem::path> : public path_caster<std::filesystem::path> {};\n#elif defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)\ntemplate <>\nstruct type_caster<std::experimental::filesystem::path>\n    : public path_caster<std::experimental::filesystem::path> {};\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/stl.h",
    "content": "/*\n    pybind11/stl.h: Transparent conversion for STL data types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n#include \"detail/common.h\"\n#include \"detail/descr.h\"\n#include \"detail/type_caster_base.h\"\n\n#include <deque>\n#include <initializer_list>\n#include <list>\n#include <map>\n#include <memory>\n#include <ostream>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <valarray>\n\n// See `detail/common.h` for implementation of these guards.\n#if defined(PYBIND11_HAS_OPTIONAL)\n#    include <optional>\n#elif defined(PYBIND11_HAS_EXP_OPTIONAL)\n#    include <experimental/optional>\n#endif\n\n#if defined(PYBIND11_HAS_VARIANT)\n#    include <variant>\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n//\n// Begin: Equivalent of\n//        https://github.com/google/clif/blob/ae4eee1de07cdf115c0c9bf9fec9ff28efce6f6c/clif/python/runtime.cc#L388-L438\n/*\nThe three `object_is_convertible_to_*()` functions below are\nthe result of converging the behaviors of pybind11 and PyCLIF\n(http://github.com/google/clif).\n\nOriginally PyCLIF was extremely far on the permissive side of the spectrum,\nwhile pybind11 was very far on the strict side. Originally PyCLIF accepted any\nPython iterable as input for a C++ `vector`/`set`/`map` argument, as long as\nthe elements were convertible. The obvious (in hindsight) problem was that\nany empty Python iterable could be passed to any of these C++ types, e.g. `{}`\nwas accepted for C++ `vector`/`set` arguments, or `[]` for C++ `map` arguments.\n\nThe functions below strike a practical permissive-vs-strict compromise,\ninformed by tens of thousands of use cases in the wild. A main objective is\nto prevent accidents and improve readability:\n\n- Python literals must match the C++ types.\n\n- For C++ `set`: The potentially reducing conversion from a Python sequence\n  (e.g. Python `list` or `tuple`) to a C++ `set` must be explicit, by going\n  through a Python `set`.\n\n- However, a Python `set` can still be passed to a C++ `vector`. The rationale\n  is that this conversion is not reducing. Implicit conversions of this kind\n  are also fairly commonly used, therefore enforcing explicit conversions\n  would have an unfavorable cost : benefit ratio; more sloppily speaking,\n  such an enforcement would be more annoying than helpful.\n\nAdditional checks have been added to allow types derived from `collections.abc.Set` and\n`collections.abc.Mapping` (`collections.abc.Sequence` is already allowed by `PySequence_Check`).\n*/\n\ninline bool object_is_instance_with_one_of_tp_names(PyObject *obj,\n                                                    std::initializer_list<const char *> tp_names) {\n    if (PyType_Check(obj)) {\n        return false;\n    }\n    const char *obj_tp_name = Py_TYPE(obj)->tp_name;\n    for (const auto *tp_name : tp_names) {\n        if (std::strcmp(obj_tp_name, tp_name) == 0) {\n            return true;\n        }\n    }\n    return false;\n}\n\ninline bool object_is_convertible_to_std_vector(const handle &src) {\n    // Allow sequence-like objects, but not (byte-)string-like objects.\n    if (PySequence_Check(src.ptr()) != 0) {\n        return !PyUnicode_Check(src.ptr()) && !PyBytes_Check(src.ptr());\n    }\n    // Allow generators, set/frozenset and several common iterable types.\n    return (PyGen_Check(src.ptr()) != 0) || (PyAnySet_Check(src.ptr()) != 0)\n           || object_is_instance_with_one_of_tp_names(\n               src.ptr(), {\"dict_keys\", \"dict_values\", \"dict_items\", \"map\", \"zip\"});\n}\n\ninline bool object_is_convertible_to_std_set(const handle &src, bool convert) {\n    // Allow set/frozenset and dict keys.\n    // In convert mode: also allow types derived from collections.abc.Set.\n    return ((PyAnySet_Check(src.ptr()) != 0)\n            || object_is_instance_with_one_of_tp_names(src.ptr(), {\"dict_keys\"}))\n           || (convert && isinstance(src, module_::import(\"collections.abc\").attr(\"Set\")));\n}\n\ninline bool object_is_convertible_to_std_map(const handle &src, bool convert) {\n    // Allow dict.\n    if (PyDict_Check(src.ptr())) {\n        return true;\n    }\n    // Allow types conforming to Mapping Protocol.\n    // According to https://docs.python.org/3/c-api/mapping.html, `PyMappingCheck()` checks for\n    // `__getitem__()` without checking the type of keys. In order to restrict the allowed types\n    // closer to actual Mapping-like types, we also check for the `items()` method.\n    if (PyMapping_Check(src.ptr()) != 0) {\n        PyObject *items = PyObject_GetAttrString(src.ptr(), \"items\");\n        if (items != nullptr) {\n            bool is_convertible = (PyCallable_Check(items) != 0);\n            Py_DECREF(items);\n            if (is_convertible) {\n                return true;\n            }\n        } else {\n            PyErr_Clear();\n        }\n    }\n    // In convert mode: Allow types derived from collections.abc.Mapping\n    return convert && isinstance(src, module_::import(\"collections.abc\").attr(\"Mapping\"));\n}\n\n//\n// End: Equivalent of clif/python/runtime.cc\n//\n\n/// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for\n/// forwarding a container element).  Typically used indirect via forwarded_type(), below.\ntemplate <typename T, typename U>\nusing forwarded_type = conditional_t<std::is_lvalue_reference<T>::value,\n                                     remove_reference_t<U> &,\n                                     remove_reference_t<U> &&>;\n\n/// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically\n/// used for forwarding a container's elements.\ntemplate <typename T, typename U>\nconstexpr forwarded_type<T, U> forward_like(U &&u) {\n    return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));\n}\n\n// Checks if a container has a STL style reserve method.\n// This will only return true for a `reserve()` with a `void` return.\ntemplate <typename C>\nusing has_reserve_method = std::is_same<decltype(std::declval<C>().reserve(0)), void>;\n\ntemplate <typename Type, typename Key>\nstruct set_caster {\n    using type = Type;\n    using key_conv = make_caster<Key>;\n\nprivate:\n    template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>\n    void reserve_maybe(const anyset &s, Type *) {\n        value.reserve(s.size());\n    }\n    void reserve_maybe(const anyset &, void *) {}\n\n    bool convert_iterable(const iterable &itbl, bool convert) {\n        for (const auto &it : itbl) {\n            key_conv conv;\n            if (!conv.load(it, convert)) {\n                return false;\n            }\n            value.insert(cast_op<Key &&>(std::move(conv)));\n        }\n        return true;\n    }\n\n    bool convert_anyset(const anyset &s, bool convert) {\n        value.clear();\n        reserve_maybe(s, &value);\n        return convert_iterable(s, convert);\n    }\n\npublic:\n    bool load(handle src, bool convert) {\n        if (!object_is_convertible_to_std_set(src, convert)) {\n            return false;\n        }\n        if (isinstance<anyset>(src)) {\n            value.clear();\n            return convert_anyset(reinterpret_borrow<anyset>(src), convert);\n        }\n        if (!convert) {\n            return false;\n        }\n        assert(isinstance<iterable>(src));\n        value.clear();\n        return convert_iterable(reinterpret_borrow<iterable>(src), convert);\n    }\n\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        if (!std::is_lvalue_reference<T>::value) {\n            policy = return_value_policy_override<Key>::policy(policy);\n        }\n        pybind11::set s;\n        for (auto &&value : src) {\n            auto value_ = reinterpret_steal<object>(\n                key_conv::cast(detail::forward_like<T>(value), policy, parent));\n            if (!value_ || !s.add(std::move(value_))) {\n                return handle();\n            }\n        }\n        return s.release();\n    }\n\n    PYBIND11_TYPE_CASTER(type,\n                         io_name(\"collections.abc.Set\", \"set\") + const_name(\"[\") + key_conv::name\n                             + const_name(\"]\"));\n};\n\ntemplate <typename Type, typename Key, typename Value>\nstruct map_caster {\n    using key_conv = make_caster<Key>;\n    using value_conv = make_caster<Value>;\n\nprivate:\n    template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>\n    void reserve_maybe(const dict &d, Type *) {\n        value.reserve(d.size());\n    }\n    void reserve_maybe(const dict &, void *) {}\n\n    bool convert_elements(const dict &d, bool convert) {\n        value.clear();\n        reserve_maybe(d, &value);\n        for (const auto &it : d) {\n            key_conv kconv;\n            value_conv vconv;\n            if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {\n                return false;\n            }\n            value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));\n        }\n        return true;\n    }\n\npublic:\n    bool load(handle src, bool convert) {\n        if (!object_is_convertible_to_std_map(src, convert)) {\n            return false;\n        }\n        if (isinstance<dict>(src)) {\n            return convert_elements(reinterpret_borrow<dict>(src), convert);\n        }\n        if (!convert) {\n            return false;\n        }\n        auto items = reinterpret_steal<object>(PyMapping_Items(src.ptr()));\n        if (!items) {\n            throw error_already_set();\n        }\n        assert(isinstance<iterable>(items));\n        return convert_elements(dict(reinterpret_borrow<iterable>(items)), convert);\n    }\n\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        dict d;\n        return_value_policy policy_key = policy;\n        return_value_policy policy_value = policy;\n        if (!std::is_lvalue_reference<T>::value) {\n            policy_key = return_value_policy_override<Key>::policy(policy_key);\n            policy_value = return_value_policy_override<Value>::policy(policy_value);\n        }\n        for (auto &&kv : src) {\n            auto key = reinterpret_steal<object>(\n                key_conv::cast(detail::forward_like<T>(kv.first), policy_key, parent));\n            auto value = reinterpret_steal<object>(\n                value_conv::cast(detail::forward_like<T>(kv.second), policy_value, parent));\n            if (!key || !value) {\n                return handle();\n            }\n            d[std::move(key)] = std::move(value);\n        }\n        return d.release();\n    }\n\n    PYBIND11_TYPE_CASTER(Type,\n                         io_name(\"collections.abc.Mapping\", \"dict\") + const_name(\"[\")\n                             + key_conv::name + const_name(\", \") + value_conv::name\n                             + const_name(\"]\"));\n};\n\ntemplate <typename Type, typename Value>\nstruct list_caster {\n    using value_conv = make_caster<Value>;\n\n    bool load(handle src, bool convert) {\n        if (!object_is_convertible_to_std_vector(src)) {\n            return false;\n        }\n        if (isinstance<sequence>(src)) {\n            return convert_elements(src, convert);\n        }\n        if (!convert) {\n            return false;\n        }\n        // Designed to be behavior-equivalent to passing tuple(src) from Python:\n        // The conversion to a tuple will first exhaust the generator object, to ensure that\n        // the generator is not left in an unpredictable (to the caller) partially-consumed\n        // state.\n        assert(isinstance<iterable>(src));\n        return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);\n    }\n\nprivate:\n    template <typename T = Type, enable_if_t<has_reserve_method<T>::value, int> = 0>\n    void reserve_maybe(const sequence &s, Type *) {\n        value.reserve(s.size());\n    }\n    void reserve_maybe(const sequence &, void *) {}\n\n    bool convert_elements(handle seq, bool convert) {\n        auto s = reinterpret_borrow<sequence>(seq);\n        value.clear();\n        reserve_maybe(s, &value);\n        for (const auto &it : seq) {\n            value_conv conv;\n            if (!conv.load(it, convert)) {\n                return false;\n            }\n            value.push_back(cast_op<Value &&>(std::move(conv)));\n        }\n        return true;\n    }\n\npublic:\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        if (!std::is_lvalue_reference<T>::value) {\n            policy = return_value_policy_override<Value>::policy(policy);\n        }\n        list l(src.size());\n        ssize_t index = 0;\n        for (auto &&value : src) {\n            auto value_ = reinterpret_steal<object>(\n                value_conv::cast(detail::forward_like<T>(value), policy, parent));\n            if (!value_) {\n                return handle();\n            }\n            PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference\n        }\n        return l.release();\n    }\n\n    PYBIND11_TYPE_CASTER(Type,\n                         io_name(\"collections.abc.Sequence\", \"list\") + const_name(\"[\")\n                             + value_conv::name + const_name(\"]\"));\n};\n\ntemplate <typename Type, typename Alloc>\nstruct type_caster<std::vector<Type, Alloc>> : list_caster<std::vector<Type, Alloc>, Type> {};\n\ntemplate <typename Type, typename Alloc>\nstruct type_caster<std::deque<Type, Alloc>> : list_caster<std::deque<Type, Alloc>, Type> {};\n\ntemplate <typename Type, typename Alloc>\nstruct type_caster<std::list<Type, Alloc>> : list_caster<std::list<Type, Alloc>, Type> {};\n\ntemplate <typename ArrayType, typename V, size_t... I>\nArrayType vector_to_array_impl(V &&v, index_sequence<I...>) {\n    return {{std::move(v[I])...}};\n}\n\n// Based on https://en.cppreference.com/w/cpp/container/array/to_array\ntemplate <typename ArrayType, size_t N, typename V>\nArrayType vector_to_array(V &&v) {\n    return vector_to_array_impl<ArrayType, V>(std::forward<V>(v), make_index_sequence<N>{});\n}\n\ntemplate <typename ArrayType, typename Value, bool Resizable, size_t Size = 0>\nstruct array_caster {\n    using value_conv = make_caster<Value>;\n\nprivate:\n    std::unique_ptr<ArrayType> value;\n\n    template <bool R = Resizable, enable_if_t<R, int> = 0>\n    bool convert_elements(handle seq, bool convert) {\n        auto l = reinterpret_borrow<sequence>(seq);\n        value.reset(new ArrayType{});\n        // Using `resize` to preserve the behavior exactly as it was before PR #5305\n        // For the `resize` to work, `Value` must be default constructible.\n        // For `std::valarray`, this is a requirement:\n        // https://en.cppreference.com/w/cpp/named_req/NumericType\n        value->resize(l.size());\n        size_t ctr = 0;\n        for (const auto &it : l) {\n            value_conv conv;\n            if (!conv.load(it, convert)) {\n                return false;\n            }\n            (*value)[ctr++] = cast_op<Value &&>(std::move(conv));\n        }\n        return true;\n    }\n\n    template <bool R = Resizable, enable_if_t<!R, int> = 0>\n    bool convert_elements(handle seq, bool convert) {\n        auto l = reinterpret_borrow<sequence>(seq);\n        if (l.size() != Size) {\n            return false;\n        }\n        // The `temp` storage is needed to support `Value` types that are not\n        // default-constructible.\n        // Deliberate choice: no template specializations, for simplicity, and\n        // because the compile time overhead for the specializations is deemed\n        // more significant than the runtime overhead for the `temp` storage.\n        std::vector<Value> temp;\n        temp.reserve(l.size());\n        for (auto it : l) {\n            value_conv conv;\n            if (!conv.load(it, convert)) {\n                return false;\n            }\n            temp.emplace_back(cast_op<Value &&>(std::move(conv)));\n        }\n        value.reset(new ArrayType(vector_to_array<ArrayType, Size>(std::move(temp))));\n        return true;\n    }\n\npublic:\n    bool load(handle src, bool convert) {\n        if (!object_is_convertible_to_std_vector(src)) {\n            return false;\n        }\n        if (isinstance<sequence>(src)) {\n            return convert_elements(src, convert);\n        }\n        if (!convert) {\n            return false;\n        }\n        // Designed to be behavior-equivalent to passing tuple(src) from Python:\n        // The conversion to a tuple will first exhaust the generator object, to ensure that\n        // the generator is not left in an unpredictable (to the caller) partially-consumed\n        // state.\n        assert(isinstance<iterable>(src));\n        return convert_elements(tuple(reinterpret_borrow<iterable>(src)), convert);\n    }\n\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        list l(src.size());\n        ssize_t index = 0;\n        for (auto &&value : src) {\n            auto value_ = reinterpret_steal<object>(\n                value_conv::cast(detail::forward_like<T>(value), policy, parent));\n            if (!value_) {\n                return handle();\n            }\n            PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference\n        }\n        return l.release();\n    }\n\n    // Code copied from PYBIND11_TYPE_CASTER macro.\n    // Intentionally preserving the behavior exactly as it was before PR #5305\n    template <typename T_, enable_if_t<std::is_same<ArrayType, remove_cv_t<T_>>::value, int> = 0>\n    static handle cast(T_ *src, return_value_policy policy, handle parent) {\n        if (!src) {\n            return none().release();\n        }\n        if (policy == return_value_policy::take_ownership) {\n            auto h = cast(std::move(*src), policy, parent);\n            delete src; // WARNING: Assumes `src` was allocated with `new`.\n            return h;\n        }\n        return cast(*src, policy, parent);\n    }\n\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator ArrayType *() { return &(*value); }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator ArrayType &() { return *value; }\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    operator ArrayType &&() && { return std::move(*value); }\n\n    template <typename T_>\n    using cast_op_type = movable_cast_op_type<T_>;\n\n    static constexpr auto name\n        = const_name<Resizable>(const_name(\"\"), const_name(\"typing.Annotated[\"))\n          + io_name(\"collections.abc.Sequence\", \"list\") + const_name(\"[\") + value_conv::name\n          + const_name(\"]\")\n          + const_name<Resizable>(const_name(\"\"),\n                                  const_name(\", \\\"FixedSize(\") + const_name<Size>()\n                                      + const_name(\")\\\"]\"));\n};\n\ntemplate <typename Type, size_t Size>\nstruct type_caster<std::array<Type, Size>>\n    : array_caster<std::array<Type, Size>, Type, false, Size> {};\n\ntemplate <typename Type>\nstruct type_caster<std::valarray<Type>> : array_caster<std::valarray<Type>, Type, true> {};\n\ntemplate <typename Key, typename Compare, typename Alloc>\nstruct type_caster<std::set<Key, Compare, Alloc>>\n    : set_caster<std::set<Key, Compare, Alloc>, Key> {};\n\ntemplate <typename Key, typename Hash, typename Equal, typename Alloc>\nstruct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>\n    : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> {};\n\ntemplate <typename Key, typename Value, typename Compare, typename Alloc>\nstruct type_caster<std::map<Key, Value, Compare, Alloc>>\n    : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> {};\n\ntemplate <typename Key, typename Value, typename Hash, typename Equal, typename Alloc>\nstruct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>\n    : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> {};\n\n// This type caster is intended to be used for std::optional and std::experimental::optional\ntemplate <typename Type, typename Value = typename Type::value_type>\nstruct optional_caster {\n    using value_conv = make_caster<Value>;\n\n    template <typename T>\n    static handle cast(T &&src, return_value_policy policy, handle parent) {\n        if (!src) {\n            return none().release();\n        }\n        if (!std::is_lvalue_reference<T>::value) {\n            policy = return_value_policy_override<Value>::policy(policy);\n        }\n        // NOLINTNEXTLINE(bugprone-unchecked-optional-access)\n        return value_conv::cast(*std::forward<T>(src), policy, parent);\n    }\n\n    bool load(handle src, bool convert) {\n        if (!src) {\n            return false;\n        }\n        if (src.is_none()) {\n            return true; // default-constructed value is already empty\n        }\n        value_conv inner_caster;\n        if (!inner_caster.load(src, convert)) {\n            return false;\n        }\n\n        value.emplace(cast_op<Value &&>(std::move(inner_caster)));\n        return true;\n    }\n\n    PYBIND11_TYPE_CASTER(Type, value_conv::name | make_caster<none>::name);\n};\n\n#if defined(PYBIND11_HAS_OPTIONAL)\ntemplate <typename T>\nstruct type_caster<std::optional<T>> : public optional_caster<std::optional<T>> {};\n\ntemplate <>\nstruct type_caster<std::nullopt_t> : public void_caster<std::nullopt_t> {};\n#endif\n\n#if defined(PYBIND11_HAS_EXP_OPTIONAL)\ntemplate <typename T>\nstruct type_caster<std::experimental::optional<T>>\n    : public optional_caster<std::experimental::optional<T>> {};\n\ntemplate <>\nstruct type_caster<std::experimental::nullopt_t>\n    : public void_caster<std::experimental::nullopt_t> {};\n#endif\n\n/// Visit a variant and cast any found type to Python\nstruct variant_caster_visitor {\n    return_value_policy policy;\n    handle parent;\n\n    using result_type = handle; // required by boost::variant in C++11\n\n    template <typename T>\n    result_type operator()(T &&src) const {\n        return make_caster<T>::cast(std::forward<T>(src), policy, parent);\n    }\n};\n\n/// Helper class which abstracts away variant's `visit` function. `std::variant` and similar\n/// `namespace::variant` types which provide a `namespace::visit()` function are handled here\n/// automatically using argument-dependent lookup. Users can provide specializations for other\n/// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.\ntemplate <template <typename...> class Variant>\nstruct visit_helper {\n    template <typename... Args>\n    static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {\n        return visit(std::forward<Args>(args)...);\n    }\n};\n\n/// Generic variant caster\ntemplate <typename Variant>\nstruct variant_caster;\n\ntemplate <template <typename...> class V, typename... Ts>\nstruct variant_caster<V<Ts...>> {\n    static_assert(sizeof...(Ts) > 0, \"Variant must consist of at least one alternative.\");\n\n    template <typename U, typename... Us>\n    bool load_alternative(handle src, bool convert, type_list<U, Us...>) {\n        auto caster = make_caster<U>();\n        if (caster.load(src, convert)) {\n            value = cast_op<U>(std::move(caster));\n            return true;\n        }\n        return load_alternative(src, convert, type_list<Us...>{});\n    }\n\n    bool load_alternative(handle, bool, type_list<>) { return false; }\n\n    bool load(handle src, bool convert) {\n        // Do a first pass without conversions to improve constructor resolution.\n        // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`\n        // slot of the variant. Without two-pass loading `double` would be filled\n        // because it appears first and a conversion is possible.\n        if (convert && load_alternative(src, false, type_list<Ts...>{})) {\n            return true;\n        }\n        return load_alternative(src, convert, type_list<Ts...>{});\n    }\n\n    template <typename Variant>\n    static handle cast(Variant &&src, return_value_policy policy, handle parent) {\n        return visit_helper<V>::call(variant_caster_visitor{policy, parent},\n                                     std::forward<Variant>(src));\n    }\n\n    using Type = V<Ts...>;\n    PYBIND11_TYPE_CASTER(Type, ::pybind11::detail::union_concat(make_caster<Ts>::name...));\n};\n\n#if defined(PYBIND11_HAS_VARIANT)\ntemplate <typename... Ts>\nstruct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> {};\n\ntemplate <>\nstruct type_caster<std::monostate> : public void_caster<std::monostate> {};\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\n\ninline std::ostream &operator<<(std::ostream &os, const handle &obj) {\n#ifdef PYBIND11_HAS_STRING_VIEW\n    os << str(obj).cast<std::string_view>();\n#else\n    os << (std::string) str(obj);\n#endif\n    return os;\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/stl_bind.h",
    "content": "/*\n    pybind11/std_bind.h: Binding generators for STL data types\n\n    Copyright (c) 2016 Sergey Lyskov and Wenzel Jakob\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/type_caster_base.h\"\n#include \"cast.h\"\n#include \"operators.h\"\n\n#include <algorithm>\n#include <sstream>\n#include <type_traits>\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/* SFINAE helper class used by 'is_comparable */\ntemplate <typename T>\nstruct container_traits {\n    template <typename T2>\n    static std::true_type\n    test_comparable(decltype(std::declval<const T2 &>() == std::declval<const T2 &>()) *);\n    template <typename T2>\n    static std::false_type test_comparable(...);\n    template <typename T2>\n    static std::true_type test_value(typename T2::value_type *);\n    template <typename T2>\n    static std::false_type test_value(...);\n    template <typename T2>\n    static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *);\n    template <typename T2>\n    static std::false_type test_pair(...);\n\n    static constexpr const bool is_comparable\n        = std::is_same<std::true_type, decltype(test_comparable<T>(nullptr))>::value;\n    static constexpr const bool is_pair\n        = std::is_same<std::true_type, decltype(test_pair<T>(nullptr, nullptr))>::value;\n    static constexpr const bool is_vector\n        = std::is_same<std::true_type, decltype(test_value<T>(nullptr))>::value;\n    static constexpr const bool is_element = !is_pair && !is_vector;\n};\n\n/* Default: is_comparable -> std::false_type */\ntemplate <typename T, typename SFINAE = void>\nstruct is_comparable : std::false_type {};\n\n/* For non-map data structures, check whether operator== can be instantiated */\ntemplate <typename T>\nstruct is_comparable<\n    T,\n    enable_if_t<container_traits<T>::is_element && container_traits<T>::is_comparable>>\n    : std::true_type {};\n\n/* For a vector/map data structure, recursively check the value type\n   (which is std::pair for maps) */\ntemplate <typename T>\nstruct is_comparable<T, enable_if_t<container_traits<T>::is_vector>>\n    : is_comparable<typename recursive_container_traits<T>::type_to_check_recursively> {};\n\ntemplate <>\nstruct is_comparable<recursive_bottom> : std::true_type {};\n\n/* For pairs, recursively check the two data types */\ntemplate <typename T>\nstruct is_comparable<T, enable_if_t<container_traits<T>::is_pair>> {\n    static constexpr const bool value = is_comparable<typename T::first_type>::value\n                                        && is_comparable<typename T::second_type>::value;\n};\n\n/* Fallback functions */\ntemplate <typename, typename, typename... Args>\nvoid vector_if_copy_constructible(const Args &...) {}\ntemplate <typename, typename, typename... Args>\nvoid vector_if_equal_operator(const Args &...) {}\ntemplate <typename, typename, typename... Args>\nvoid vector_if_insertion_operator(const Args &...) {}\ntemplate <typename, typename, typename... Args>\nvoid vector_modifiers(const Args &...) {}\n\ntemplate <typename Vector, typename Class_>\nvoid vector_if_copy_constructible(enable_if_t<is_copy_constructible<Vector>::value, Class_> &cl) {\n    cl.def(init<const Vector &>(), \"Copy constructor\");\n}\n\ntemplate <typename Vector, typename Class_>\nvoid vector_if_equal_operator(enable_if_t<is_comparable<Vector>::value, Class_> &cl) {\n    using T = typename Vector::value_type;\n\n    cl.def(self == self);\n    cl.def(self != self);\n\n    cl.def(\n        \"count\",\n        [](const Vector &v, const T &x) { return std::count(v.begin(), v.end(), x); },\n        arg(\"x\"),\n        \"Return the number of times ``x`` appears in the list\");\n\n    cl.def(\n        \"remove\",\n        [](Vector &v, const T &x) {\n            auto p = std::find(v.begin(), v.end(), x);\n            if (p != v.end()) {\n                v.erase(p);\n            } else {\n                throw value_error();\n            }\n        },\n        arg(\"x\"),\n        \"Remove the first item from the list whose value is x. \"\n        \"It is an error if there is no such item.\");\n\n    cl.def(\n        \"__contains__\",\n        [](const Vector &v, const T &x) { return std::find(v.begin(), v.end(), x) != v.end(); },\n        arg(\"x\"),\n        \"Return true the container contains ``x``\");\n}\n\n// Vector modifiers -- requires a copyable vector_type:\n// (Technically, some of these (pop and __delitem__) don't actually require copyability, but it\n// seems silly to allow deletion but not insertion, so include them here too.)\ntemplate <typename Vector, typename Class_>\nvoid vector_modifiers(\n    enable_if_t<is_copy_constructible<typename Vector::value_type>::value, Class_> &cl) {\n    using T = typename Vector::value_type;\n    using SizeType = typename Vector::size_type;\n    using DiffType = typename Vector::difference_type;\n\n    auto wrap_i = [](DiffType i, SizeType n) {\n        if (i < 0) {\n            i += n;\n        }\n        if (i < 0 || (SizeType) i >= n) {\n            throw index_error();\n        }\n        return i;\n    };\n\n    cl.def(\n        \"append\",\n        [](Vector &v, const T &value) { v.push_back(value); },\n        arg(\"x\"),\n        \"Add an item to the end of the list\");\n\n    cl.def(init([](const iterable &it) {\n        auto v = std::unique_ptr<Vector>(new Vector());\n        v->reserve(len_hint(it));\n        for (handle h : it) {\n            v->push_back(h.cast<T>());\n        }\n        return v.release();\n    }));\n\n    cl.def(\"clear\", [](Vector &v) { v.clear(); }, \"Clear the contents\");\n\n    cl.def(\n        \"extend\",\n        [](Vector &v, const Vector &src) { v.insert(v.end(), src.begin(), src.end()); },\n        arg(\"L\"),\n        \"Extend the list by appending all the items in the given list\");\n\n    cl.def(\n        \"extend\",\n        [](Vector &v, const iterable &it) {\n            const size_t old_size = v.size();\n            v.reserve(old_size + len_hint(it));\n            try {\n                for (handle h : it) {\n                    v.push_back(h.cast<T>());\n                }\n            } catch (const cast_error &) {\n                v.erase(v.begin() + static_cast<typename Vector::difference_type>(old_size),\n                        v.end());\n                try {\n                    v.shrink_to_fit();\n                } catch (const std::exception &) { // NOLINT(bugprone-empty-catch)\n                    // Do nothing\n                }\n                throw;\n            }\n        },\n        arg(\"L\"),\n        \"Extend the list by appending all the items in the given list\");\n\n    cl.def(\n        \"insert\",\n        [](Vector &v, DiffType i, const T &x) {\n            // Can't use wrap_i; i == v.size() is OK\n            if (i < 0) {\n                i += v.size();\n            }\n            if (i < 0 || (SizeType) i > v.size()) {\n                throw index_error();\n            }\n            v.insert(v.begin() + i, x);\n        },\n        arg(\"i\"),\n        arg(\"x\"),\n        \"Insert an item at a given position.\");\n\n    cl.def(\n        \"pop\",\n        [](Vector &v) {\n            if (v.empty()) {\n                throw index_error();\n            }\n            T t = std::move(v.back());\n            v.pop_back();\n            return t;\n        },\n        \"Remove and return the last item\");\n\n    cl.def(\n        \"pop\",\n        [wrap_i](Vector &v, DiffType i) {\n            i = wrap_i(i, v.size());\n            T t = std::move(v[(SizeType) i]);\n            v.erase(std::next(v.begin(), i));\n            return t;\n        },\n        arg(\"i\"),\n        \"Remove and return the item at index ``i``\");\n\n    cl.def(\"__setitem__\", [wrap_i](Vector &v, DiffType i, const T &t) {\n        i = wrap_i(i, v.size());\n        v[(SizeType) i] = t;\n    });\n\n    /// Slicing protocol\n    cl.def(\n        \"__getitem__\",\n        [](const Vector &v, const slice &slice) -> Vector * {\n            size_t start = 0, stop = 0, step = 0, slicelength = 0;\n\n            if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {\n                throw error_already_set();\n            }\n\n            auto *seq = new Vector();\n            seq->reserve(slicelength);\n\n            for (size_t i = 0; i < slicelength; ++i) {\n                seq->push_back(v[start]);\n                start += step;\n            }\n            return seq;\n        },\n        arg(\"s\"),\n        \"Retrieve list elements using a slice object\");\n\n    cl.def(\n        \"__setitem__\",\n        [](Vector &v, const slice &slice, const Vector &value) {\n            size_t start = 0, stop = 0, step = 0, slicelength = 0;\n            if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {\n                throw error_already_set();\n            }\n\n            if (slicelength != value.size()) {\n                throw std::runtime_error(\n                    \"Left and right hand size of slice assignment have different sizes!\");\n            }\n\n            for (size_t i = 0; i < slicelength; ++i) {\n                v[start] = value[i];\n                start += step;\n            }\n        },\n        \"Assign list elements using a slice object\");\n\n    cl.def(\n        \"__delitem__\",\n        [wrap_i](Vector &v, DiffType i) {\n            i = wrap_i(i, v.size());\n            v.erase(v.begin() + i);\n        },\n        \"Delete the list elements at index ``i``\");\n\n    cl.def(\n        \"__delitem__\",\n        [](Vector &v, const slice &slice) {\n            size_t start = 0, stop = 0, step = 0, slicelength = 0;\n\n            if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {\n                throw error_already_set();\n            }\n\n            if (step == 1 && false) {\n                v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));\n            } else {\n                for (size_t i = 0; i < slicelength; ++i) {\n                    v.erase(v.begin() + DiffType(start));\n                    start += step - 1;\n                }\n            }\n        },\n        \"Delete list elements using a slice object\");\n}\n\n// If the type has an operator[] that doesn't return a reference (most notably std::vector<bool>),\n// we have to access by copying; otherwise we return by reference.\ntemplate <typename Vector>\nusing vector_needs_copy\n    = negation<std::is_same<decltype(std::declval<Vector>()[typename Vector::size_type()]),\n                            typename Vector::value_type &>>;\n\n// The usual case: access and iterate by reference\ntemplate <typename Vector, typename Class_>\nvoid vector_accessor(enable_if_t<!vector_needs_copy<Vector>::value, Class_> &cl) {\n    using T = typename Vector::value_type;\n    using SizeType = typename Vector::size_type;\n    using DiffType = typename Vector::difference_type;\n    using ItType = typename Vector::iterator;\n\n    auto wrap_i = [](DiffType i, SizeType n) {\n        if (i < 0) {\n            i += n;\n        }\n        if (i < 0 || (SizeType) i >= n) {\n            throw index_error();\n        }\n        return i;\n    };\n\n    cl.def(\n        \"__getitem__\",\n        [wrap_i](Vector &v, DiffType i) -> T & {\n            i = wrap_i(i, v.size());\n            return v[(SizeType) i];\n        },\n        return_value_policy::reference_internal // ref + keepalive\n    );\n\n    cl.def(\n        \"__iter__\",\n        [](Vector &v) {\n            return make_iterator<return_value_policy::reference_internal, ItType, ItType, T &>(\n                v.begin(), v.end());\n        },\n        keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */\n    );\n}\n\n// The case for special objects, like std::vector<bool>, that have to be returned-by-copy:\ntemplate <typename Vector, typename Class_>\nvoid vector_accessor(enable_if_t<vector_needs_copy<Vector>::value, Class_> &cl) {\n    using T = typename Vector::value_type;\n    using SizeType = typename Vector::size_type;\n    using DiffType = typename Vector::difference_type;\n    using ItType = typename Vector::iterator;\n    cl.def(\"__getitem__\", [](const Vector &v, DiffType i) -> T {\n        if (i < 0) {\n            i += v.size();\n            if (i < 0) {\n                throw index_error();\n            }\n        }\n        auto i_st = static_cast<SizeType>(i);\n        if (i_st >= v.size()) {\n            throw index_error();\n        }\n        return v[i_st];\n    });\n\n    cl.def(\n        \"__iter__\",\n        [](Vector &v) {\n            return make_iterator<return_value_policy::copy, ItType, ItType, T>(v.begin(), v.end());\n        },\n        keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */\n    );\n}\n\ntemplate <typename Vector, typename Class_>\nauto vector_if_insertion_operator(Class_ &cl, std::string const &name)\n    -> decltype(std::declval<std::ostream &>() << std::declval<typename Vector::value_type>(),\n                void()) {\n    using size_type = typename Vector::size_type;\n\n    cl.def(\n        \"__repr__\",\n        [name](Vector &v) {\n            std::ostringstream s;\n            s << name << '[';\n            for (size_type i = 0; i < v.size(); ++i) {\n                s << v[i];\n                if (i != v.size() - 1) {\n                    s << \", \";\n                }\n            }\n            s << ']';\n            return s.str();\n        },\n        \"Return the canonical string representation of this list.\");\n}\n\n// Provide the buffer interface for vectors if we have data() and we have a format for it\n// GCC seems to have \"void std::vector<bool>::data()\" - doing SFINAE on the existence of data()\n// is insufficient, we need to check it returns an appropriate pointer\ntemplate <typename Vector, typename = void>\nstruct vector_has_data_and_format : std::false_type {};\ntemplate <typename Vector>\nstruct vector_has_data_and_format<\n    Vector,\n    enable_if_t<std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(),\n                                      std::declval<Vector>().data()),\n                             typename Vector::value_type *>::value>> : std::true_type {};\n\n// [workaround(intel)] Separate function required here\n// Workaround as the Intel compiler does not compile the enable_if_t part below\n// (tested with icc (ICC) 2021.1 Beta 20200827)\ntemplate <typename... Args>\nconstexpr bool args_any_are_buffer() {\n    return detail::any_of<std::is_same<Args, buffer_protocol>...>::value;\n}\n\n// [workaround(intel)] Separate function required here\n// [workaround(msvc)] Can't use constexpr bool in return type\n\n// Add the buffer interface to a vector\ntemplate <typename Vector, typename Class_, typename... Args>\nvoid vector_buffer_impl(Class_ &cl, std::true_type) {\n    using T = typename Vector::value_type;\n\n    static_assert(vector_has_data_and_format<Vector>::value,\n                  \"There is not an appropriate format descriptor for this vector\");\n\n    // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard\n    // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here\n    format_descriptor<T>::format();\n\n    cl.def_buffer([](Vector &v) -> buffer_info {\n        return buffer_info(v.data(),\n                           static_cast<ssize_t>(sizeof(T)),\n                           format_descriptor<T>::format(),\n                           1,\n                           {v.size()},\n                           {sizeof(T)});\n    });\n\n    cl.def(init([](const buffer &buf) {\n        auto info = buf.request();\n        if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) {\n            throw type_error(\"Only valid 1D buffers can be copied to a vector\");\n        }\n        if (!detail::compare_buffer_info<T>::compare(info)\n            || (ssize_t) sizeof(T) != info.itemsize) {\n            throw type_error(\"Format mismatch (Python: \" + info.format\n                             + \" C++: \" + format_descriptor<T>::format() + \")\");\n        }\n\n        T *p = static_cast<T *>(info.ptr);\n        ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T));\n        T *end = p + info.shape[0] * step;\n        if (step == 1) {\n            return Vector(p, end);\n        }\n        Vector vec;\n        vec.reserve((size_t) info.shape[0]);\n        for (; p != end; p += step) {\n            vec.push_back(*p);\n        }\n        return vec;\n    }));\n\n    return;\n}\n\ntemplate <typename Vector, typename Class_, typename... Args>\nvoid vector_buffer_impl(Class_ &, std::false_type) {}\n\ntemplate <typename Vector, typename Class_, typename... Args>\nvoid vector_buffer(Class_ &cl) {\n    vector_buffer_impl<Vector, Class_, Args...>(\n        cl, detail::any_of<std::is_same<Args, buffer_protocol>...>{});\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\n//\n// std::vector\n//\ntemplate <typename Vector, typename holder_type = default_holder_type<Vector>, typename... Args>\nclass_<Vector, holder_type> bind_vector(handle scope, std::string const &name, Args &&...args) {\n    using Class_ = class_<Vector, holder_type>;\n\n    // If the value_type is unregistered (e.g. a converting type) or is itself registered\n    // module-local then make the vector binding module-local as well:\n    using vtype = typename Vector::value_type;\n    auto *vtype_info = detail::get_type_info(typeid(vtype));\n    bool local = !vtype_info || vtype_info->module_local;\n\n    Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);\n\n    // Declare the buffer interface if a buffer_protocol() is passed in\n    detail::vector_buffer<Vector, Class_, Args...>(cl);\n\n    cl.def(init<>());\n\n    // Register copy constructor (if possible)\n    detail::vector_if_copy_constructible<Vector, Class_>(cl);\n\n    // Register comparison-related operators and functions (if possible)\n    detail::vector_if_equal_operator<Vector, Class_>(cl);\n\n    // Register stream insertion operator (if possible)\n    detail::vector_if_insertion_operator<Vector, Class_>(cl, name);\n\n    // Modifiers require copyable vector value type\n    detail::vector_modifiers<Vector, Class_>(cl);\n\n    // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive\n    detail::vector_accessor<Vector, Class_>(cl);\n\n    cl.def(\n        \"__bool__\",\n        [](const Vector &v) -> bool { return !v.empty(); },\n        \"Check whether the list is nonempty\");\n\n    cl.def(\"__len__\", [](const Vector &vec) { return vec.size(); });\n\n#if 0\n    // C++ style functions deprecated, leaving it here as an example\n    cl.def(init<size_type>());\n\n    cl.def(\"resize\",\n         (void (Vector::*) (size_type count)) & Vector::resize,\n         \"changes the number of elements stored\");\n\n    cl.def(\"erase\",\n        [](Vector &v, SizeType i) {\n        if (i >= v.size())\n            throw index_error();\n        v.erase(v.begin() + i);\n    }, \"erases element at index ``i``\");\n\n    cl.def(\"empty\",         &Vector::empty,         \"checks whether the container is empty\");\n    cl.def(\"size\",          &Vector::size,          \"returns the number of elements\");\n    cl.def(\"push_back\", (void (Vector::*)(const T&)) &Vector::push_back, \"adds an element to the end\");\n    cl.def(\"pop_back\",                               &Vector::pop_back, \"removes the last element\");\n\n    cl.def(\"max_size\",      &Vector::max_size,      \"returns the maximum possible number of elements\");\n    cl.def(\"reserve\",       &Vector::reserve,       \"reserves storage\");\n    cl.def(\"capacity\",      &Vector::capacity,      \"returns the number of elements that can be held in currently allocated storage\");\n    cl.def(\"shrink_to_fit\", &Vector::shrink_to_fit, \"reduces memory usage by freeing unused memory\");\n\n    cl.def(\"clear\", &Vector::clear, \"clears the contents\");\n    cl.def(\"swap\",   &Vector::swap, \"swaps the contents\");\n\n    cl.def(\"front\", [](Vector &v) {\n        if (v.size()) return v.front();\n        else throw index_error();\n    }, \"access the first element\");\n\n    cl.def(\"back\", [](Vector &v) {\n        if (v.size()) return v.back();\n        else throw index_error();\n    }, \"access the last element \");\n\n#endif\n\n    return cl;\n}\n\n//\n// std::map, std::unordered_map\n//\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n/* Fallback functions */\ntemplate <typename, typename, typename... Args>\nvoid map_if_insertion_operator(const Args &...) {}\ntemplate <typename, typename, typename... Args>\nvoid map_assignment(const Args &...) {}\n\n// Map assignment when copy-assignable: just copy the value\ntemplate <typename Map, typename Class_>\nvoid map_assignment(\n    enable_if_t<is_copy_assignable<typename Map::mapped_type>::value, Class_> &cl) {\n    using KeyType = typename Map::key_type;\n    using MappedType = typename Map::mapped_type;\n\n    cl.def(\"__setitem__\", [](Map &m, const KeyType &k, const MappedType &v) {\n        auto it = m.find(k);\n        if (it != m.end()) {\n            it->second = v;\n        } else {\n            m.emplace(k, v);\n        }\n    });\n}\n\n// Not copy-assignable, but still copy-constructible: we can update the value by erasing and\n// reinserting\ntemplate <typename Map, typename Class_>\nvoid map_assignment(enable_if_t<!is_copy_assignable<typename Map::mapped_type>::value\n                                    && is_copy_constructible<typename Map::mapped_type>::value,\n                                Class_> &cl) {\n    using KeyType = typename Map::key_type;\n    using MappedType = typename Map::mapped_type;\n\n    cl.def(\"__setitem__\", [](Map &m, const KeyType &k, const MappedType &v) {\n        // We can't use m[k] = v; because value type might not be default constructable\n        auto r = m.emplace(k, v);\n        if (!r.second) {\n            // value type is not copy assignable so the only way to insert it is to erase it\n            // first...\n            m.erase(r.first);\n            m.emplace(k, v);\n        }\n    });\n}\n\ntemplate <typename Map, typename Class_>\nauto map_if_insertion_operator(Class_ &cl, std::string const &name)\n    -> decltype(std::declval<std::ostream &>() << std::declval<typename Map::key_type>()\n                                               << std::declval<typename Map::mapped_type>(),\n                void()) {\n\n    cl.def(\n        \"__repr__\",\n        [name](Map &m) {\n            std::ostringstream s;\n            s << name << '{';\n            bool f = false;\n            for (auto const &kv : m) {\n                if (f) {\n                    s << \", \";\n                }\n                s << kv.first << \": \" << kv.second;\n                f = true;\n            }\n            s << '}';\n            return s.str();\n        },\n        \"Return the canonical string representation of this map.\");\n}\n\nstruct keys_view {\n    virtual size_t len() = 0;\n    virtual iterator iter() = 0;\n    virtual bool contains(const handle &k) = 0;\n    virtual ~keys_view() = default;\n};\n\nstruct values_view {\n    virtual size_t len() = 0;\n    virtual iterator iter() = 0;\n    virtual ~values_view() = default;\n};\n\nstruct items_view {\n    virtual size_t len() = 0;\n    virtual iterator iter() = 0;\n    virtual ~items_view() = default;\n};\n\ntemplate <typename Map>\nstruct KeysViewImpl : public detail::keys_view {\n    explicit KeysViewImpl(Map &map) : map(map) {}\n    size_t len() override { return map.size(); }\n    iterator iter() override { return make_key_iterator(map.begin(), map.end()); }\n    bool contains(const handle &k) override {\n        try {\n            return map.find(k.template cast<typename Map::key_type>()) != map.end();\n        } catch (const cast_error &) {\n            return false;\n        }\n    }\n    Map &map;\n};\n\ntemplate <typename Map>\nstruct ValuesViewImpl : public detail::values_view {\n    explicit ValuesViewImpl(Map &map) : map(map) {}\n    size_t len() override { return map.size(); }\n    iterator iter() override { return make_value_iterator(map.begin(), map.end()); }\n    Map &map;\n};\n\ntemplate <typename Map>\nstruct ItemsViewImpl : public detail::items_view {\n    explicit ItemsViewImpl(Map &map) : map(map) {}\n    size_t len() override { return map.size(); }\n    iterator iter() override { return make_iterator(map.begin(), map.end()); }\n    Map &map;\n};\n\ninline str format_message_key_error_key_object(handle py_key) {\n    str message = \"pybind11::bind_map key\";\n    if (!py_key) {\n        return message;\n    }\n    try {\n        message = str(py_key);\n    } catch (const std::exception &) {\n        try {\n            message = repr(py_key);\n        } catch (const std::exception &) {\n            return message;\n        }\n    }\n    const ssize_t cut_length = 100;\n    if (len(message) > 2 * cut_length + 3) {\n        return str(message[slice(0, cut_length, 1)]) + str(\"✄✄✄\")\n               + str(message[slice(-cut_length, static_cast<ssize_t>(len(message)), 1)]);\n    }\n    return message;\n}\n\ntemplate <typename KeyType>\nstr format_message_key_error(const KeyType &key) {\n    object py_key;\n    try {\n        py_key = cast(key);\n    } catch (const std::exception &) {\n        do { // Trick to avoid \"empty catch\" warning/error.\n        } while (false);\n    }\n    return format_message_key_error_key_object(py_key);\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\ntemplate <typename Map, typename holder_type = default_holder_type<Map>, typename... Args>\nclass_<Map, holder_type> bind_map(handle scope, const std::string &name, Args &&...args) {\n    using KeyType = typename Map::key_type;\n    using MappedType = typename Map::mapped_type;\n    using KeysView = detail::keys_view;\n    using ValuesView = detail::values_view;\n    using ItemsView = detail::items_view;\n    using Class_ = class_<Map, holder_type>;\n\n    // If either type is a non-module-local bound type then make the map binding non-local as well;\n    // otherwise (e.g. both types are either module-local or converting) the map will be\n    // module-local.\n    auto *tinfo = detail::get_type_info(typeid(MappedType));\n    bool local = !tinfo || tinfo->module_local;\n    if (local) {\n        tinfo = detail::get_type_info(typeid(KeyType));\n        local = !tinfo || tinfo->module_local;\n    }\n\n    Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);\n\n    // Wrap KeysView if it wasn't already wrapped\n    if (!detail::get_type_info(typeid(KeysView))) {\n        class_<KeysView> keys_view(scope, \"KeysView\", pybind11::module_local(local));\n        keys_view.def(\"__len__\", &KeysView::len);\n        keys_view.def(\"__iter__\",\n                      &KeysView::iter,\n                      keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */\n        );\n        keys_view.def(\"__contains__\", &KeysView::contains);\n    }\n    // Similarly for ValuesView:\n    if (!detail::get_type_info(typeid(ValuesView))) {\n        class_<ValuesView> values_view(scope, \"ValuesView\", pybind11::module_local(local));\n        values_view.def(\"__len__\", &ValuesView::len);\n        values_view.def(\"__iter__\",\n                        &ValuesView::iter,\n                        keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */\n        );\n    }\n    // Similarly for ItemsView:\n    if (!detail::get_type_info(typeid(ItemsView))) {\n        class_<ItemsView> items_view(scope, \"ItemsView\", pybind11::module_local(local));\n        items_view.def(\"__len__\", &ItemsView::len);\n        items_view.def(\"__iter__\",\n                       &ItemsView::iter,\n                       keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */\n        );\n    }\n\n    cl.def(init<>());\n\n    // Register stream insertion operator (if possible)\n    detail::map_if_insertion_operator<Map, Class_>(cl, name);\n\n    cl.def(\n        \"__bool__\",\n        [](const Map &m) -> bool { return !m.empty(); },\n        \"Check whether the map is nonempty\");\n\n    cl.def(\n        \"__iter__\",\n        [](Map &m) { return make_key_iterator(m.begin(), m.end()); },\n        keep_alive<0, 1>() /* Essential: keep map alive while iterator exists */\n    );\n\n    cl.def(\n        \"keys\",\n        [](Map &m) { return std::unique_ptr<KeysView>(new detail::KeysViewImpl<Map>(m)); },\n        keep_alive<0, 1>() /* Essential: keep map alive while view exists */\n    );\n\n    cl.def(\n        \"values\",\n        [](Map &m) { return std::unique_ptr<ValuesView>(new detail::ValuesViewImpl<Map>(m)); },\n        keep_alive<0, 1>() /* Essential: keep map alive while view exists */\n    );\n\n    cl.def(\n        \"items\",\n        [](Map &m) { return std::unique_ptr<ItemsView>(new detail::ItemsViewImpl<Map>(m)); },\n        keep_alive<0, 1>() /* Essential: keep map alive while view exists */\n    );\n\n    cl.def(\n        \"__getitem__\",\n        [](Map &m, const KeyType &k) -> MappedType & {\n            auto it = m.find(k);\n            if (it == m.end()) {\n                set_error(PyExc_KeyError, detail::format_message_key_error(k));\n                throw error_already_set();\n            }\n            return it->second;\n        },\n        return_value_policy::reference_internal // ref + keepalive\n    );\n\n    cl.def(\"__contains__\", [](Map &m, const KeyType &k) -> bool {\n        auto it = m.find(k);\n        if (it == m.end()) {\n            return false;\n        }\n        return true;\n    });\n    // Fallback for when the object is not of the key type\n    cl.def(\"__contains__\", [](Map &, const object &) -> bool { return false; });\n\n    // Assignment provided only if the type is copyable\n    detail::map_assignment<Map, Class_>(cl);\n\n    cl.def(\"__delitem__\", [](Map &m, const KeyType &k) {\n        auto it = m.find(k);\n        if (it == m.end()) {\n            set_error(PyExc_KeyError, detail::format_message_key_error(k));\n            throw error_already_set();\n        }\n        m.erase(it);\n    });\n\n    // Always use a lambda in case of `using` declaration\n    cl.def(\"__len__\", [](const Map &m) { return m.size(); });\n\n    return cl;\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/subinterpreter.h",
    "content": "/*\n    pybind11/subinterpreter.h: Support for creating and using subinterpreters\n\n    Copyright (c) 2025 The Pybind Development Team.\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/internals.h\"\n#include \"gil.h\"\n\n#include <stdexcept>\n\n#ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n#    error \"This platform does not support subinterpreters, do not include this file.\"\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nclass subinterpreter;\n\n/// Activate the subinterpreter and acquire its GIL, while also releasing any GIL and interpreter\n/// currently held. Upon exiting the scope, the previous subinterpreter (if any) and its\n/// associated GIL are restored to their state as they were before the scope was entered.\nclass subinterpreter_scoped_activate {\npublic:\n    explicit subinterpreter_scoped_activate(subinterpreter const &si);\n    ~subinterpreter_scoped_activate();\n\n    subinterpreter_scoped_activate(subinterpreter_scoped_activate &&) = delete;\n    subinterpreter_scoped_activate(subinterpreter_scoped_activate const &) = delete;\n    subinterpreter_scoped_activate &operator=(subinterpreter_scoped_activate &) = delete;\n    subinterpreter_scoped_activate &operator=(subinterpreter_scoped_activate const &) = delete;\n\nprivate:\n    PyThreadState *old_tstate_ = nullptr;\n    PyThreadState *tstate_ = nullptr;\n    PyGILState_STATE gil_state_;\n    bool simple_gil_ = false;\n};\n\n/// Holds a Python subinterpreter instance\nclass subinterpreter {\npublic:\n    /// empty/unusable, but move-assignable.  use create() to create a subinterpreter.\n    subinterpreter() = default;\n\n    subinterpreter(subinterpreter const &copy) = delete;\n    subinterpreter &operator=(subinterpreter const &copy) = delete;\n\n    subinterpreter(subinterpreter &&old) noexcept\n        : istate_(old.istate_), creation_tstate_(old.creation_tstate_) {\n        old.istate_ = nullptr;\n        old.creation_tstate_ = nullptr;\n    }\n\n    subinterpreter &operator=(subinterpreter &&old) noexcept {\n        std::swap(old.istate_, istate_);\n        std::swap(old.creation_tstate_, creation_tstate_);\n        return *this;\n    }\n\n    /// Create a new subinterpreter with the specified configuration\n    /// @note This function acquires (and then releases) the main interpreter GIL, but the main\n    /// interpreter and its GIL are not required to be held prior to calling this function.\n    static subinterpreter create(PyInterpreterConfig const &cfg) {\n\n        error_scope err_scope;\n        subinterpreter result;\n        {\n            // we must hold the main GIL in order to create a subinterpreter\n            subinterpreter_scoped_activate main_guard(main());\n\n            auto *prev_tstate = PyThreadState_Get();\n\n            PyStatus status;\n\n            {\n                /*\n                Several internal CPython modules are lacking proper subinterpreter support in 3.12\n                even though it is \"stable\" in that version.  This most commonly seems to cause\n                crashes when two interpreters concurrently initialize, which imports several things\n                (like builtins, unicode, codecs).\n                */\n#if PY_VERSION_HEX < 0x030D0000 && defined(Py_MOD_PER_INTERPRETER_GIL_SUPPORTED)\n                static std::mutex one_at_a_time;\n                std::lock_guard<std::mutex> guard(one_at_a_time);\n#endif\n                status = Py_NewInterpreterFromConfig(&result.creation_tstate_, &cfg);\n            }\n\n            // this doesn't raise a normal Python exception, it provides an exit() status code.\n            if (PyStatus_Exception(status) != 0) {\n                pybind11_fail(\"failed to create new sub-interpreter\");\n            }\n\n            // upon success, the new interpreter is activated in this thread\n            result.istate_ = result.creation_tstate_->interp;\n            detail::has_seen_non_main_interpreter() = true;\n            detail::get_internals(); // initialize internals.tstate, amongst other things...\n\n            // In 3.13+ this state should be deleted right away, and the memory will be reused for\n            // the next threadstate on this interpreter. However, on 3.12 we cannot do that, we\n            // must keep it around (but not use it) ... see destructor.\n#if PY_VERSION_HEX >= 0x030D0000\n            PyThreadState_Clear(result.creation_tstate_);\n            PyThreadState_DeleteCurrent();\n#endif\n\n            // we have to switch back to main, and then the scopes will handle cleanup\n            PyThreadState_Swap(prev_tstate);\n        }\n        return result;\n    }\n\n    /// Calls create() with a default configuration of an isolated interpreter that disallows fork,\n    /// exec, and Python threads.\n    static subinterpreter create() {\n        // same as the default config in the python docs\n        PyInterpreterConfig cfg;\n        std::memset(&cfg, 0, sizeof(cfg));\n        cfg.allow_threads = 1;\n        cfg.check_multi_interp_extensions = 1;\n        cfg.gil = PyInterpreterConfig_OWN_GIL;\n        return create(cfg);\n    }\n\n    ~subinterpreter() {\n        if (!creation_tstate_) {\n            // non-owning wrapper, do nothing.\n            return;\n        }\n\n        PyThreadState *destroy_tstate = nullptr;\n        PyThreadState *old_tstate = nullptr;\n\n        // Python 3.12 requires us to keep the original PyThreadState alive until we are ready to\n        // destroy the interpreter.  We prefer to use that to destroy the interpreter.\n#if PY_VERSION_HEX < 0x030D0000\n        // The tstate passed to Py_EndInterpreter MUST have been created on the current OS thread.\n        bool same_thread = false;\n#    ifdef PY_HAVE_THREAD_NATIVE_ID\n        same_thread = PyThread_get_thread_native_id() == creation_tstate_->native_thread_id;\n#    endif\n        if (same_thread) {\n            // OK it is safe to use the creation state here\n            destroy_tstate = creation_tstate_;\n            old_tstate = PyThreadState_Swap(destroy_tstate);\n        } else {\n            // We have to make a new tstate on this thread and use that.\n            destroy_tstate = PyThreadState_New(istate_);\n            old_tstate = PyThreadState_Swap(destroy_tstate);\n\n            // We can use the one we just created, so we must delete the creation state.\n            PyThreadState_Clear(creation_tstate_);\n            PyThreadState_Delete(creation_tstate_);\n        }\n#else\n        destroy_tstate = PyThreadState_New(istate_);\n        old_tstate = PyThreadState_Swap(destroy_tstate);\n#endif\n\n        bool switch_back = (old_tstate != nullptr) && old_tstate->interp != istate_;\n\n        // Internals always exists in the subinterpreter, this class enforces it when it creates\n        // the subinterpreter. Even if it didn't, this only creates the pointer-to-pointer, not the\n        // internals themselves.\n        detail::get_internals_pp_manager().get_pp();\n        detail::get_local_internals_pp_manager().get_pp();\n\n        // End it\n        Py_EndInterpreter(destroy_tstate);\n\n        // It's possible for the  internals to be created during endinterpreter (e.g. if a\n        // py::capsule calls `get_internals()` during destruction), so we destroy afterward.\n        detail::get_internals_pp_manager().destroy();\n        detail::get_local_internals_pp_manager().destroy();\n\n        // switch back to the old tstate and old GIL (if there was one)\n        if (switch_back) {\n            PyThreadState_Swap(old_tstate);\n        }\n    }\n\n    /// Get a handle to the main interpreter that can be used with subinterpreter_scoped_activate\n    /// Note that destructing the handle is a noop, the main interpreter can only be ended by\n    /// py::finalize_interpreter()\n    static subinterpreter main() {\n        subinterpreter m;\n        m.istate_ = PyInterpreterState_Main();\n        m.disarm(); // make destruct a noop\n        return m;\n    }\n\n    /// Get a non-owning wrapper of the currently active interpreter (if any)\n    static subinterpreter current() {\n        subinterpreter c;\n        c.istate_ = detail::get_interpreter_state_unchecked();\n        c.disarm(); // make destruct a noop, we don't own this...\n        return c;\n    }\n\n    /// Get the numerical identifier for the sub-interpreter\n    int64_t id() const {\n        if (istate_ != nullptr) {\n            return PyInterpreterState_GetID(istate_);\n        }\n        return -1; // CPython uses one-up numbers from 0, so negative should be safe to return\n                   // here.\n    }\n\n    /// Get the interpreter's state dict.  This interpreter's GIL must be held before calling!\n    dict state_dict() { return reinterpret_borrow<dict>(PyInterpreterState_GetDict(istate_)); }\n\n    /// abandon cleanup of this subinterpreter (leak it). this might be needed during\n    /// finalization...\n    void disarm() { creation_tstate_ = nullptr; }\n\n    /// An empty wrapper cannot be activated\n    bool empty() const { return istate_ == nullptr; }\n\n    /// Is this wrapper non-empty\n    explicit operator bool() const { return !empty(); }\n\nprivate:\n    friend class subinterpreter_scoped_activate;\n    PyInterpreterState *istate_ = nullptr;\n    PyThreadState *creation_tstate_ = nullptr;\n};\n\nclass scoped_subinterpreter {\npublic:\n    scoped_subinterpreter() : si_(subinterpreter::create()), scope_(si_) {}\n\n    explicit scoped_subinterpreter(PyInterpreterConfig const &cfg)\n        : si_(subinterpreter::create(cfg)), scope_(si_) {}\n\nprivate:\n    subinterpreter si_;\n    subinterpreter_scoped_activate scope_;\n};\n\ninline subinterpreter_scoped_activate::subinterpreter_scoped_activate(subinterpreter const &si) {\n    if (!si.istate_) {\n        pybind11_fail(\"null subinterpreter\");\n    }\n\n    if (detail::get_interpreter_state_unchecked() == si.istate_) {\n        // we are already on this interpreter, make sure we hold the GIL\n        simple_gil_ = true;\n        gil_state_ = PyGILState_Ensure();\n        return;\n    }\n\n    // we can't really interact with the interpreter at all until we switch to it\n    // not even to, for example, look in its state dict or touch its internals\n    tstate_ = PyThreadState_New(si.istate_);\n\n    // make the interpreter active and acquire the GIL\n    old_tstate_ = PyThreadState_Swap(tstate_);\n\n    // save this in internals for scoped_gil calls (see also: PR #5870)\n    detail::get_internals().tstate = tstate_;\n}\n\ninline subinterpreter_scoped_activate::~subinterpreter_scoped_activate() {\n    if (simple_gil_) {\n        // We were on this interpreter already, so just make sure the GIL goes back as it was\n        PyGILState_Release(gil_state_);\n    } else {\n        if (tstate_) {\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n            if (detail::get_thread_state_unchecked() != tstate_) {\n                pybind11_fail(\"~subinterpreter_scoped_activate: thread state must be current!\");\n            }\n#endif\n            detail::get_internals().tstate.reset();\n            PyThreadState_Clear(tstate_);\n            PyThreadState_DeleteCurrent();\n        }\n\n        // Go back the previous interpreter (if any) and acquire THAT gil\n        PyThreadState_Swap(old_tstate_);\n    }\n}\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/trampoline_self_life_support.h",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/using_smart_holder.h\"\n#include \"detail/value_and_holder.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n// PYBIND11:REMINDER: Needs refactoring of existing pybind11 code.\ninline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo);\nPYBIND11_NAMESPACE_END(detail)\n\n// The original core idea for this struct goes back to PyCLIF:\n// https://github.com/google/clif/blob/07f95d7e69dca2fcf7022978a55ef3acff506c19/clif/python/runtime.cc#L37\n// URL provided here mainly to give proper credit.\nstruct trampoline_self_life_support {\n    // NOTE: PYBIND11_INTERNALS_VERSION needs to be bumped if changes are made to this struct.\n    detail::value_and_holder v_h;\n\n    trampoline_self_life_support() = default;\n\n    void activate_life_support(const detail::value_and_holder &v_h_) {\n        Py_INCREF((PyObject *) v_h_.inst);\n        v_h = v_h_;\n    }\n\n    void deactivate_life_support() {\n        Py_DECREF((PyObject *) v_h.inst);\n        v_h = detail::value_and_holder();\n    }\n\n    ~trampoline_self_life_support() {\n        if (v_h.inst != nullptr && v_h.vh != nullptr) {\n            void *value_void_ptr = v_h.value_ptr();\n            if (value_void_ptr != nullptr) {\n                PyGILState_STATE threadstate = PyGILState_Ensure();\n                v_h.value_ptr() = nullptr;\n                v_h.holder<smart_holder>().release_disowned();\n                detail::deregister_instance(v_h.inst, value_void_ptr, v_h.type);\n                Py_DECREF((PyObject *) v_h.inst); // Must be after deregister.\n                PyGILState_Release(threadstate);\n            }\n        }\n    }\n\n    // For the next two, the default implementations generate undefined behavior (ASAN failures\n    // manually verified). The reason is that v_h needs to be kept default-initialized.\n    trampoline_self_life_support(const trampoline_self_life_support &) {}\n    trampoline_self_life_support(trampoline_self_life_support &&) noexcept {}\n\n    // These should never be needed (please provide test cases if you think they are).\n    trampoline_self_life_support &operator=(const trampoline_self_life_support &) = delete;\n    trampoline_self_life_support &operator=(trampoline_self_life_support &&) = delete;\n};\n\nPYBIND11_NAMESPACE_BEGIN(detail)\nusing get_trampoline_self_life_support_fn = trampoline_self_life_support *(*) (void *);\nPYBIND11_NAMESPACE_END(detail)\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/type_caster_pyobject_ptr.h",
    "content": "// Copyright (c) 2023 The pybind Community.\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"detail/descr.h\"\n#include \"cast.h\"\n#include \"pytypes.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <>\nclass type_caster<PyObject> {\npublic:\n    static constexpr auto name = const_name(\"object\"); // See discussion under PR #4601.\n\n    // This overload is purely to guard against accidents.\n    template <typename T,\n              detail::enable_if_t<!is_same_ignoring_cvref<T, PyObject *>::value, int> = 0>\n    static handle cast(T &&, return_value_policy, handle /*parent*/) {\n        static_assert(is_same_ignoring_cvref<T, PyObject *>::value,\n                      \"Invalid C++ type T for to-Python conversion (type_caster<PyObject>).\");\n        return nullptr; // Unreachable.\n    }\n\n    static handle cast(PyObject *src, return_value_policy policy, handle /*parent*/) {\n        if (src == nullptr) {\n            throw error_already_set();\n        }\n        if (PyErr_Occurred()) {\n            raise_from(PyExc_SystemError, \"src != nullptr but PyErr_Occurred()\");\n            throw error_already_set();\n        }\n        if (policy == return_value_policy::take_ownership) {\n            return src;\n        }\n        if (policy == return_value_policy::reference\n            || policy == return_value_policy::automatic_reference) {\n            return handle(src).inc_ref();\n        }\n        pybind11_fail(\"type_caster<PyObject>::cast(): unsupported return_value_policy: \"\n                      + std::to_string(static_cast<int>(policy)));\n    }\n\n    bool load(handle src, bool) {\n        value = reinterpret_borrow<object>(src);\n        return true;\n    }\n\n    template <typename T>\n    using cast_op_type = PyObject *;\n\n    explicit operator PyObject *() { return value.ptr(); }\n\nprivate:\n    object value;\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/typing.h",
    "content": "/*\n    pybind11/typing.h: Convenience wrapper classes for basic Python types\n    with more explicit annotations.\n\n    Copyright (c) 2023 Dustin Spicuzza <dustin@virtualroadside.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"detail/common.h\"\n#include \"cast.h\"\n#include \"pytypes.h\"\n\n#include <algorithm>\n\n#if defined(__cpp_nontype_template_args) && __cpp_nontype_template_args >= 201911L\n#    define PYBIND11_TYPING_H_HAS_STRING_LITERAL\n#    include <numeric>\n#    include <ranges>\n#    include <string_view>\n#endif\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(typing)\n\n/*\n    The following types can be used to direct pybind11-generated docstrings\n    to have have more explicit types (e.g., `list[str]` instead of `list`).\n    Just use these in place of existing types.\n\n    There is no additional enforcement of types at runtime.\n*/\n\n// Tuple type hint defined in cast.h for use in py::make_tuple to avoid circular includes\n\ntemplate <typename K, typename V>\nclass Dict : public dict {\n    using dict::dict;\n};\n\ntemplate <typename T>\nclass List : public list {\n    using list::list;\n};\n\ntemplate <typename T>\nclass Set : public set {\n    using set::set;\n};\n\ntemplate <typename T>\nclass Iterable : public iterable {\n    using iterable::iterable;\n};\n\ntemplate <typename T>\nclass Iterator : public iterator {\n    using iterator::iterator;\n};\n\ntemplate <typename Signature>\nclass Callable;\n\ntemplate <typename Return, typename... Args>\nclass Callable<Return(Args...)> : public function {\n    using function::function;\n};\n\ntemplate <typename T>\nclass Type : public type {\n    using type::type;\n};\n\ntemplate <typename... Types>\nclass Union : public object {\n    PYBIND11_OBJECT_DEFAULT(Union, object, PyObject_Type)\n    using object::object;\n};\n\ntemplate <typename T>\nclass Optional : public object {\n    PYBIND11_OBJECT_DEFAULT(Optional, object, PyObject_Type)\n    using object::object;\n};\n\ntemplate <typename T>\nclass Final : public object {\n    PYBIND11_OBJECT_DEFAULT(Final, object, PyObject_Type)\n    using object::object;\n};\n\ntemplate <typename T>\nclass ClassVar : public object {\n    PYBIND11_OBJECT_DEFAULT(ClassVar, object, PyObject_Type)\n    using object::object;\n};\n\ntemplate <typename T>\nclass TypeGuard : public bool_ {\n    using bool_::bool_;\n};\n\ntemplate <typename T>\nclass TypeIs : public bool_ {\n    using bool_::bool_;\n};\n\nclass NoReturn : public none {\n    using none::none;\n};\n\nclass Never : public none {\n    using none::none;\n};\n\n#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)\ntemplate <size_t N>\nstruct StringLiteral {\n    constexpr StringLiteral(const char (&str)[N]) { std::copy_n(str, N, name); }\n    char name[N];\n};\n\ntemplate <StringLiteral... StrLits>\nclass Literal : public object {\n    PYBIND11_OBJECT_DEFAULT(Literal, object, PyObject_Type)\n};\n\n// Example syntax for creating a TypeVar.\n// typedef typing::TypeVar<\"T\"> TypeVarT;\ntemplate <StringLiteral>\nclass TypeVar : public object {\n    PYBIND11_OBJECT_DEFAULT(TypeVar, object, PyObject_Type)\n    using object::object;\n};\n#endif\n\nPYBIND11_NAMESPACE_END(typing)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ntemplate <typename... Types>\nstruct handle_type_name<typing::Tuple<Types...>> {\n    static constexpr auto name = const_name(\"tuple[\")\n                                 + ::pybind11::detail::concat(make_caster<Types>::name...)\n                                 + const_name(\"]\");\n};\n\ntemplate <>\nstruct handle_type_name<typing::Tuple<>> {\n    // PEP 484 specifies this syntax for an empty tuple\n    static constexpr auto name = const_name(\"tuple[()]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Tuple<T, ellipsis>> {\n    // PEP 484 specifies this syntax for a variable-length tuple\n    static constexpr auto name\n        = const_name(\"tuple[\") + make_caster<T>::name + const_name(\", ...]\");\n};\n\ntemplate <typename K, typename V>\nstruct handle_type_name<typing::Dict<K, V>> {\n    static constexpr auto name = const_name(\"dict[\") + make_caster<K>::name + const_name(\", \")\n                                 + make_caster<V>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::List<T>> {\n    static constexpr auto name = const_name(\"list[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Set<T>> {\n    static constexpr auto name = const_name(\"set[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Iterable<T>> {\n    static constexpr auto name\n        = const_name(\"collections.abc.Iterable[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Iterator<T>> {\n    static constexpr auto name\n        = const_name(\"collections.abc.Iterator[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename Return, typename... Args>\nstruct handle_type_name<typing::Callable<Return(Args...)>> {\n    using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;\n    static constexpr auto name\n        = const_name(\"collections.abc.Callable[[\")\n          + ::pybind11::detail::concat(::pybind11::detail::arg_descr(make_caster<Args>::name)...)\n          + const_name(\"], \") + ::pybind11::detail::return_descr(make_caster<retval_type>::name)\n          + const_name(\"]\");\n};\n\ntemplate <typename Return>\nstruct handle_type_name<typing::Callable<Return(ellipsis)>> {\n    // PEP 484 specifies this syntax for defining only return types of callables\n    using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;\n    static constexpr auto name = const_name(\"collections.abc.Callable[..., \")\n                                 + ::pybind11::detail::return_descr(make_caster<retval_type>::name)\n                                 + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Type<T>> {\n    static constexpr auto name = const_name(\"type[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename... Types>\nstruct handle_type_name<typing::Union<Types...>> {\n    static constexpr auto name = ::pybind11::detail::union_concat(make_caster<Types>::name...);\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Optional<T>> {\n    static constexpr auto name = make_caster<T>::name | make_caster<none>::name;\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::Final<T>> {\n    static constexpr auto name = const_name(\"typing.Final[\")\n                                 + ::pybind11::detail::return_descr(make_caster<T>::name)\n                                 + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::ClassVar<T>> {\n    static constexpr auto name\n        = const_name(\"typing.ClassVar[\") + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::TypeGuard<T>> {\n    static constexpr auto name = const_name(PYBIND11_TYPE_GUARD_TYPE_HINT) + const_name(\"[\")\n                                 + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <typename T>\nstruct handle_type_name<typing::TypeIs<T>> {\n    static constexpr auto name = const_name(PYBIND11_TYPE_IS_TYPE_HINT) + const_name(\"[\")\n                                 + make_caster<T>::name + const_name(\"]\");\n};\n\ntemplate <>\nstruct handle_type_name<typing::NoReturn> {\n    static constexpr auto name = const_name(\"typing.NoReturn\");\n};\n\ntemplate <>\nstruct handle_type_name<typing::Never> {\n    static constexpr auto name = const_name(PYBIND11_NEVER_TYPE_HINT);\n};\n\n#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)\ntemplate <typing::StringLiteral StrLit>\nconsteval auto sanitize_string_literal() {\n    constexpr std::string_view v(StrLit.name);\n    constexpr std::string_view special_chars(\"!@%{}-\");\n    constexpr auto num_special_chars = std::accumulate(\n        special_chars.begin(), special_chars.end(), (size_t) 0, [&v](auto acc, const char &c) {\n            return std::move(acc) + std::ranges::count(v, c);\n        });\n    char result[v.size() + num_special_chars + 1];\n    size_t i = 0;\n    for (auto c : StrLit.name) {\n        if (special_chars.find(c) != std::string_view::npos) {\n            result[i++] = '!';\n        }\n        result[i++] = c;\n    }\n    return typing::StringLiteral(result);\n}\n\ntemplate <typing::StringLiteral... Literals>\nstruct handle_type_name<typing::Literal<Literals...>> {\n    static constexpr auto name\n        = const_name(\"typing.Literal[\")\n          + pybind11::detail::concat(const_name(sanitize_string_literal<Literals>().name)...)\n          + const_name(\"]\");\n};\ntemplate <typing::StringLiteral StrLit>\nstruct handle_type_name<typing::TypeVar<StrLit>> {\n    static constexpr auto name = const_name(sanitize_string_literal<StrLit>().name);\n};\n#endif\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "include/pybind11/warnings.h",
    "content": "/*\n    pybind11/warnings.h: Python warnings wrappers.\n\n    Copyright (c) 2024 Jan Iwaszkiewicz <jiwaszkiewicz6@gmail.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#pragma once\n\n#include \"pybind11.h\"\n#include \"detail/common.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\n\nPYBIND11_NAMESPACE_BEGIN(detail)\n\ninline bool PyWarning_Check(PyObject *obj) {\n    int result = PyObject_IsSubclass(obj, PyExc_Warning);\n    if (result == 1) {\n        return true;\n    }\n    if (result == -1) {\n        raise_from(PyExc_SystemError,\n                   \"pybind11::detail::PyWarning_Check(): PyObject_IsSubclass() call failed.\");\n        throw error_already_set();\n    }\n    return false;\n}\n\nPYBIND11_NAMESPACE_END(detail)\n\nPYBIND11_NAMESPACE_BEGIN(warnings)\n\ninline object\nnew_warning_type(handle scope, const char *name, handle base = PyExc_RuntimeWarning) {\n    if (!detail::PyWarning_Check(base.ptr())) {\n        pybind11_fail(\"pybind11::warnings::new_warning_type(): cannot create custom warning, base \"\n                      \"must be a subclass of \"\n                      \"PyExc_Warning!\");\n    }\n    if (hasattr(scope, name)) {\n        pybind11_fail(\"pybind11::warnings::new_warning_type(): an attribute with name \\\"\"\n                      + std::string(name) + \"\\\" exists already.\");\n    }\n    std::string full_name = scope.attr(\"__name__\").cast<std::string>() + std::string(\".\") + name;\n    handle h(PyErr_NewException(full_name.c_str(), base.ptr(), nullptr));\n    if (!h) {\n        raise_from(PyExc_SystemError,\n                   \"pybind11::warnings::new_warning_type(): PyErr_NewException() call failed.\");\n        throw error_already_set();\n    }\n    auto obj = reinterpret_steal<object>(h);\n    scope.attr(name) = obj;\n    return obj;\n}\n\n// Similar to Python `warnings.warn()`\ninline void\nwarn(const char *message, handle category = PyExc_RuntimeWarning, int stack_level = 2) {\n    if (!detail::PyWarning_Check(category.ptr())) {\n        pybind11_fail(\n            \"pybind11::warnings::warn(): cannot raise warning, category must be a subclass of \"\n            \"PyExc_Warning!\");\n    }\n\n    if (PyErr_WarnEx(category.ptr(), message, stack_level) == -1) {\n        throw error_already_set();\n    }\n}\n\nPYBIND11_NAMESPACE_END(warnings)\n\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "noxfile.py",
    "content": "#!/usr/bin/env -S uv run\n\n# /// script\n# dependencies = [\"nox>=2025.2.9\"]\n# ///\n\nfrom __future__ import annotations\n\nimport argparse\nimport contextlib\nimport os\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from collections.abc import Generator\n\nimport nox\n\nnox.needs_version = \">=2025.2.9\"\nnox.options.default_venv_backend = \"uv|virtualenv\"\n\n\n@nox.session(reuse_venv=True)\ndef lint(session: nox.Session) -> None:\n    \"\"\"\n    Lint the codebase (except for clang-format/tidy).\n    \"\"\"\n    session.install(\"pre-commit\")\n    session.run(\"pre-commit\", \"run\", \"-a\", *session.posargs)\n\n\n@nox.session\ndef tests(session: nox.Session) -> None:\n    \"\"\"\n    Run the tests (requires a compiler).\n    \"\"\"\n    tmpdir = session.create_tmp()\n    session.install(\"cmake\")\n    session.install(\"-r\", \"tests/requirements.txt\")\n    session.run(\n        \"cmake\",\n        \"-S.\",\n        f\"-B{tmpdir}\",\n        \"-DPYBIND11_WERROR=ON\",\n        \"-DDOWNLOAD_CATCH=ON\",\n        \"-DDOWNLOAD_EIGEN=ON\",\n        *session.posargs,\n    )\n    session.run(\"cmake\", \"--build\", tmpdir)\n    session.run(\"cmake\", \"--build\", tmpdir, \"--config=Release\", \"--target\", \"check\")\n\n\n@nox.session\ndef tests_packaging(session: nox.Session) -> None:\n    \"\"\"\n    Run the packaging tests.\n    \"\"\"\n\n    session.install(\"-r\", \"tests/requirements.txt\", \"pip\")\n    session.run(\"pytest\", \"tests/extra_python_package\", *session.posargs)\n\n\n@nox.session(reuse_venv=True, default=False)\ndef docs(session: nox.Session) -> None:\n    \"\"\"\n    Build the docs. Pass --non-interactive to avoid serving.\n    \"\"\"\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"-b\", dest=\"builder\", default=\"html\", help=\"Build target (default: html)\"\n    )\n    args, posargs = parser.parse_known_args(session.posargs)\n    serve = args.builder == \"html\" and session.interactive\n\n    extra_installs = [\"sphinx-autobuild\"] if serve else []\n    session.install(\"-r\", \"docs/requirements.txt\", *extra_installs)\n    session.chdir(\"docs\")\n\n    shared_args = (\n        \"-n\",  # nitpicky mode\n        \"-T\",  # full tracebacks\n        f\"-b={args.builder}\",\n        \".\",\n        f\"_build/{args.builder}\",\n        *posargs,\n    )\n\n    if serve:\n        session.run(\n            \"sphinx-autobuild\", \"--open-browser\", \"--ignore=.build\", *shared_args\n        )\n    else:\n        session.run(\"sphinx-build\", \"--keep-going\", *shared_args)\n\n\n@nox.session(reuse_venv=True, default=False)\ndef make_changelog(session: nox.Session) -> None:\n    \"\"\"\n    Inspect the closed issues and make entries for a changelog.\n    \"\"\"\n    session.install_and_run_script(\"tools/make_changelog.py\")\n\n\n@nox.session(reuse_venv=True, default=False)\ndef build(session: nox.Session) -> None:\n    \"\"\"\n    Build SDist and wheel.\n    \"\"\"\n\n    session.install(\"build\")\n    session.log(\"Building normal files\")\n    session.run(\"python\", \"-m\", \"build\", *session.posargs)\n\n\n@contextlib.contextmanager\ndef preserve_file(filename: Path) -> Generator[str, None, None]:\n    \"\"\"\n    Causes a file to be stored and preserved when the context manager exits.\n    \"\"\"\n    old_stat = filename.stat()\n    old_file = filename.read_text(encoding=\"utf-8\")\n    try:\n        yield old_file\n    finally:\n        filename.write_text(old_file, encoding=\"utf-8\")\n        os.utime(filename, (old_stat.st_atime, old_stat.st_mtime))\n\n\n@nox.session(reuse_venv=True)\ndef build_global(session: nox.Session) -> None:\n    \"\"\"\n    Build global SDist and wheel.\n    \"\"\"\n\n    installer = [\"--installer=uv\"] if session.venv_backend == \"uv\" else []\n    session.install(\"build\", \"tomlkit\")\n    session.log(\"Building pybind11-global files\")\n    pyproject = Path(\"pyproject.toml\")\n    with preserve_file(pyproject):\n        newer_txt = session.run(\"python\", \"tools/make_global.py\", silent=True)\n        assert isinstance(newer_txt, str)\n        pyproject.write_text(newer_txt, encoding=\"utf-8\")\n        session.run(\n            \"python\",\n            \"-m\",\n            \"build\",\n            *installer,\n            *session.posargs,\n        )\n"
  },
  {
    "path": "pybind11/__init__.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nif sys.version_info < (3, 8):  # noqa: UP036\n    msg = \"pybind11 does not support Python < 3.8. v2.13 was the last release supporting Python 3.7.\"\n    raise ImportError(msg)\n\n\nfrom ._version import __version__, version_info\nfrom .commands import get_cmake_dir, get_include, get_pkgconfig_dir\n\n__all__ = (\n    \"version_info\",\n    \"__version__\",\n    \"get_include\",\n    \"get_cmake_dir\",\n    \"get_pkgconfig_dir\",\n)\n"
  },
  {
    "path": "pybind11/__main__.py",
    "content": "# pylint: disable=missing-function-docstring\nfrom __future__ import annotations\n\nimport argparse\nimport functools\nimport re\nimport sys\nimport sysconfig\n\nfrom ._version import __version__\nfrom .commands import get_cmake_dir, get_include, get_pkgconfig_dir\n\n# This is the conditional used for os.path being posixpath\nif \"posix\" in sys.builtin_module_names:\n    from shlex import quote\nelif \"nt\" in sys.builtin_module_names:\n    # See https://github.com/mesonbuild/meson/blob/db22551ed9d2dd7889abea01cc1c7bba02bf1c75/mesonbuild/utils/universal.py#L1092-L1121\n    # and the original documents:\n    # https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and\n    # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/\n    UNSAFE = re.compile(\"[ \\t\\n\\r]\")\n\n    def quote(s: str) -> str:\n        if s and not UNSAFE.search(s):\n            return s\n\n        # Paths cannot contain a '\"' on Windows, so we don't need to worry\n        # about nuanced counting here.\n        return f'\"{s}\\\\\"' if s.endswith(\"\\\\\") else f'\"{s}\"'\nelse:\n\n    def quote(s: str) -> str:\n        return s\n\n\ndef print_includes() -> None:\n    dirs = [\n        sysconfig.get_path(\"include\"),\n        sysconfig.get_path(\"platinclude\"),\n        get_include(),\n    ]\n\n    # Make unique but preserve order\n    unique_dirs = []\n    for d in dirs:\n        if d and d not in unique_dirs:\n            unique_dirs.append(d)\n\n    print(\" \".join(quote(f\"-I{d}\") for d in unique_dirs))\n\n\ndef main() -> None:\n    make_parser = functools.partial(argparse.ArgumentParser, allow_abbrev=False)\n    if sys.version_info >= (3, 14):\n        make_parser = functools.partial(make_parser, color=True, suggest_on_error=True)\n    parser = make_parser()\n    parser.add_argument(\n        \"--version\",\n        action=\"version\",\n        version=__version__,\n        help=\"Print the version and exit.\",\n    )\n    parser.add_argument(\n        \"--includes\",\n        action=\"store_true\",\n        help=\"Include flags for both pybind11 and Python headers.\",\n    )\n    parser.add_argument(\n        \"--cmakedir\",\n        action=\"store_true\",\n        help=\"Print the CMake module directory, ideal for setting -Dpybind11_ROOT in CMake.\",\n    )\n    parser.add_argument(\n        \"--pkgconfigdir\",\n        action=\"store_true\",\n        help=\"Print the pkgconfig directory, ideal for setting $PKG_CONFIG_PATH.\",\n    )\n    parser.add_argument(\n        \"--extension-suffix\",\n        action=\"store_true\",\n        help=\"Print the extension for a Python module\",\n    )\n    args = parser.parse_args()\n    if not sys.argv[1:]:\n        parser.print_help()\n    if args.includes:\n        print_includes()\n    if args.cmakedir:\n        print(quote(get_cmake_dir()))\n    if args.pkgconfigdir:\n        print(quote(get_pkgconfig_dir()))\n    if args.extension_suffix:\n        print(sysconfig.get_config_var(\"EXT_SUFFIX\"))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "pybind11/_version.py",
    "content": "# This file will be replaced in the wheel with a hard-coded version. This only\n# exists to allow running directly from source without installing (not\n# recommended, but supported).\n\nfrom __future__ import annotations\n\nimport re\nfrom pathlib import Path\n\nDIR = Path(__file__).parent.resolve()\n\ninput_file = DIR.parent / \"include/pybind11/detail/common.h\"\nregex = re.compile(\n    r\"\"\"\n\\#define \\s+ PYBIND11_VERSION_MAJOR \\s+ (?P<major>\\d+) .*?\n\\#define \\s+ PYBIND11_VERSION_MINOR \\s+ (?P<minor>\\d+) .*?\n\\#define \\s+ PYBIND11_VERSION_PATCH \\s+ (?P<patch>\\S+)\n\"\"\",\n    re.MULTILINE | re.DOTALL | re.VERBOSE,\n)\n\nmatch = regex.search(input_file.read_text(encoding=\"utf-8\"))\nassert match, \"Unable to find version in pybind11/detail/common.h\"\n__version__ = \"{major}.{minor}.{patch}\".format(**match.groupdict())\n\n\ndef _to_int(s: str) -> int | str:\n    try:\n        return int(s)\n    except ValueError:\n        return s\n\n\nversion_info = tuple(_to_int(s) for s in __version__.split(\".\"))\n"
  },
  {
    "path": "pybind11/commands.py",
    "content": "from __future__ import annotations\n\nimport os\n\nDIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_include(user: bool = False) -> str:  # noqa: ARG001\n    \"\"\"\n    Return the path to the pybind11 include directory. The historical \"user\"\n    argument is unused, and may be removed.\n    \"\"\"\n    installed_path = os.path.join(DIR, \"include\")\n    source_path = os.path.join(os.path.dirname(DIR), \"include\")\n    return installed_path if os.path.exists(installed_path) else source_path\n\n\ndef get_cmake_dir() -> str:\n    \"\"\"\n    Return the path to the pybind11 CMake module directory.\n    \"\"\"\n    cmake_installed_path = os.path.join(DIR, \"share\", \"cmake\", \"pybind11\")\n    if os.path.exists(cmake_installed_path):\n        return cmake_installed_path\n\n    msg = \"pybind11 not installed, installation required to access the CMake files\"\n    raise ImportError(msg)\n\n\ndef get_pkgconfig_dir() -> str:\n    \"\"\"\n    Return the path to the pybind11 pkgconfig directory.\n    \"\"\"\n    pkgconfig_installed_path = os.path.join(DIR, \"share\", \"pkgconfig\")\n    if os.path.exists(pkgconfig_installed_path):\n        return pkgconfig_installed_path\n\n    msg = \"pybind11 not installed, installation required to access the pkgconfig files\"\n    raise ImportError(msg)\n"
  },
  {
    "path": "pybind11/py.typed",
    "content": ""
  },
  {
    "path": "pybind11/setup_helpers.py",
    "content": "\"\"\"\nThis module provides helpers for C++11+ projects using pybind11.\n\nLICENSE:\n\nCopyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\n# IMPORTANT: If you change this file in the pybind11 repo, also review\n# setup_helpers.pyi for matching changes.\n#\n# If you copy this file in, you don't\n# need the .pyi file; it's just an interface file for static type checkers.\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport platform\nimport shlex\nimport shutil\nimport sys\nimport sysconfig\nimport tempfile\nimport threading\nimport warnings\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n)\n\ntry:\n    from setuptools import Extension as _Extension\n    from setuptools.command.build_ext import build_ext as _build_ext\nexcept ImportError:\n    from distutils.command.build_ext import (  # type: ignore[assignment]\n        build_ext as _build_ext,\n    )\n    from distutils.extension import Extension as _Extension  # type: ignore[assignment]\n\nimport distutils.ccompiler\nimport distutils.errors\n\nWIN = sys.platform.startswith(\"win32\") and \"mingw\" not in sysconfig.get_platform()\nMACOS = sys.platform.startswith(\"darwin\")\nSTD_TMPL = \"/std:c++{}\" if WIN else \"-std=c++{}\"\n\n\n# It is recommended to use PEP 518 builds if using this module. However, this\n# file explicitly supports being copied into a user's project directory\n# standalone, and pulling pybind11 with the deprecated setup_requires feature.\n# If you copy the file, remember to add it to your MANIFEST.in, and add the current\n# directory into your path if it sits beside your setup.py.\n\n\nclass Pybind11Extension(_Extension):\n    \"\"\"\n    Build a C++11+ Extension module with pybind11. This automatically adds the\n    recommended flags when you init the extension and assumes C++ sources - you\n    can further modify the options yourself.\n\n    The customizations are:\n\n    * ``/EHsc`` and ``/bigobj`` on Windows\n    * ``stdlib=libc++`` on macOS\n    * ``visibility=hidden`` and ``-g0`` on Unix\n\n    Finally, you can set ``cxx_std`` via constructor or afterwards to enable\n    flags for C++ std, and a few extra helper flags related to the C++ standard\n    level. It is _highly_ recommended you either set this, or use the provided\n    ``build_ext``, which will search for the highest supported extension for\n    you if the ``cxx_std`` property is not set. Do not set the ``cxx_std``\n    property more than once, as flags are added when you set it. Set the\n    property to None to disable the addition of C++ standard flags.\n\n    If you want to add pybind11 headers manually, for example for an exact\n    git checkout, then set ``include_pybind11=False``.\n    \"\"\"\n\n    # flags are prepended, so that they can be further overridden, e.g. by\n    # ``extra_compile_args=[\"-g\"]``.\n\n    def _add_cflags(self, flags: list[str]) -> None:\n        self.extra_compile_args[:0] = flags\n\n    def _add_ldflags(self, flags: list[str]) -> None:\n        self.extra_link_args[:0] = flags\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        self._cxx_level = 0\n        cxx_std = kwargs.pop(\"cxx_std\", 0)\n\n        if \"language\" not in kwargs:\n            kwargs[\"language\"] = \"c++\"\n\n        include_pybind11 = kwargs.pop(\"include_pybind11\", True)\n\n        super().__init__(*args, **kwargs)\n\n        # Include the installed package pybind11 headers\n        if include_pybind11:\n            # If using setup_requires, this fails the first time - that's okay\n            try:\n                import pybind11\n\n                pyinc = pybind11.get_include()\n\n                if pyinc not in self.include_dirs:\n                    self.include_dirs.append(pyinc)\n            except ModuleNotFoundError:\n                pass\n\n        self.cxx_std = cxx_std\n\n        cflags = []\n        if WIN:\n            cflags += [\"/EHsc\", \"/bigobj\"]\n        else:\n            cflags += [\"-fvisibility=hidden\"]\n            env_cflags = os.environ.get(\"CFLAGS\", \"\")\n            env_cppflags = os.environ.get(\"CPPFLAGS\", \"\")\n            c_cpp_flags = shlex.split(env_cflags) + shlex.split(env_cppflags)\n            if not any(opt.startswith(\"-g\") for opt in c_cpp_flags):\n                cflags += [\"-g0\"]\n        self._add_cflags(cflags)\n\n    @property\n    def cxx_std(self) -> int:\n        \"\"\"\n        The CXX standard level. If set, will add the required flags. If left at\n        0, it will trigger an automatic search when pybind11's build_ext is\n        used. If None, will have no effect.  Besides just the flags, this may\n        add a macos-min 10.9 or 10.14 flag if MACOSX_DEPLOYMENT_TARGET is\n        unset.\n        \"\"\"\n        return self._cxx_level\n\n    @cxx_std.setter\n    def cxx_std(self, level: int) -> None:\n        if self._cxx_level:\n            warnings.warn(\n                \"You cannot safely change the cxx_level after setting it!\", stacklevel=2\n            )\n\n        # MSVC 2015 Update 3 and later only have 14 (and later 17) modes, so\n        # force a valid flag here.\n        if WIN and level == 11:\n            level = 14\n\n        self._cxx_level = level\n\n        if not level:\n            return\n\n        cflags = [STD_TMPL.format(level)]\n        ldflags = []\n\n        if MACOS and \"MACOSX_DEPLOYMENT_TARGET\" not in os.environ:\n            # C++17 requires a higher min version of macOS. An earlier version\n            # (10.12 or 10.13) can be set manually via environment variable if\n            # you are careful in your feature usage, but 10.14 is the safest\n            # setting for general use. However, never set higher than the\n            # current macOS version!\n            current_macos = tuple(int(x) for x in platform.mac_ver()[0].split(\".\")[:2])\n            desired_macos = (10, 9) if level < 17 else (10, 14)\n            macos_string = \".\".join(str(x) for x in min(current_macos, desired_macos))\n            macosx_min = f\"-mmacosx-version-min={macos_string}\"\n            cflags += [macosx_min]\n            ldflags += [macosx_min]\n\n        self._add_cflags(cflags)\n        self._add_ldflags(ldflags)\n\n\n# Just in case someone clever tries to multithread\ntmp_chdir_lock = threading.Lock()\n\n\n@contextlib.contextmanager\ndef tmp_chdir() -> Iterator[str]:\n    \"Prepare and enter a temporary directory, cleanup when done\"\n\n    # Threadsafe\n    with tmp_chdir_lock:\n        olddir = os.getcwd()\n        try:\n            tmpdir = tempfile.mkdtemp()\n            os.chdir(tmpdir)\n            yield tmpdir\n        finally:\n            os.chdir(olddir)\n            shutil.rmtree(tmpdir)\n\n\n# cf http://bugs.python.org/issue26689\ndef has_flag(compiler: Any, flag: str) -> bool:\n    \"\"\"\n    Return the flag if a flag name is supported on the\n    specified compiler, otherwise None (can be used as a boolean).\n    If multiple flags are passed, return the first that matches.\n    \"\"\"\n\n    with tmp_chdir():\n        fname = Path(\"flagcheck.cpp\")\n        # Don't trigger -Wunused-parameter.\n        fname.write_text(\"int main (int, char **) { return 0; }\", encoding=\"utf-8\")\n\n        try:\n            compiler.compile([str(fname)], extra_postargs=[flag])\n        except distutils.errors.CompileError:\n            return False\n        return True\n\n\n# Every call will cache the result\ncpp_flag_cache = None\n\n\n@lru_cache\ndef auto_cpp_level(compiler: Any) -> str | int:\n    \"\"\"\n    Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.\n    \"\"\"\n\n    if WIN:\n        return \"latest\"\n\n    levels = [17, 14, 11]\n\n    for level in levels:\n        if has_flag(compiler, STD_TMPL.format(level)):\n            return level\n\n    msg = \"Unsupported compiler -- at least C++11 support is needed!\"\n    raise RuntimeError(msg)\n\n\nclass build_ext(_build_ext):  # noqa: N801\n    \"\"\"\n    Customized build_ext that allows an auto-search for the highest supported\n    C++ level for Pybind11Extension. This is only needed for the auto-search\n    for now, and is completely optional otherwise.\n    \"\"\"\n\n    def build_extensions(self) -> None:\n        \"\"\"\n        Build extensions, injecting C++ std for Pybind11Extension if needed.\n        \"\"\"\n\n        for ext in self.extensions:\n            if hasattr(ext, \"_cxx_level\") and ext._cxx_level == 0:\n                ext.cxx_std = auto_cpp_level(self.compiler)\n\n        super().build_extensions()\n\n\ndef intree_extensions(\n    paths: Iterable[str], package_dir: dict[str, str] | None = None\n) -> list[Pybind11Extension]:\n    \"\"\"\n    Generate Pybind11Extensions from source files directly located in a Python\n    source tree.\n\n    ``package_dir`` behaves as in ``setuptools.setup``.  If unset, the Python\n    package root parent is determined as the first parent directory that does\n    not contain an ``__init__.py`` file.\n    \"\"\"\n    exts = []\n\n    if package_dir is None:\n        for path in paths:\n            parent, _ = os.path.split(path)\n            while os.path.exists(os.path.join(parent, \"__init__.py\")):\n                parent, _ = os.path.split(parent)\n            relname, _ = os.path.splitext(os.path.relpath(path, parent))\n            qualified_name = relname.replace(os.path.sep, \".\")\n            exts.append(Pybind11Extension(qualified_name, [path]))\n        return exts\n\n    for path in paths:\n        for prefix, parent in package_dir.items():\n            if path.startswith(parent):\n                relname, _ = os.path.splitext(os.path.relpath(path, parent))\n                qualified_name = relname.replace(os.path.sep, \".\")\n                if prefix:\n                    qualified_name = prefix + \".\" + qualified_name\n                exts.append(Pybind11Extension(qualified_name, [path]))\n                break\n        else:\n            msg = (\n                f\"path {path} is not a child of any of the directories listed \"\n                f\"in 'package_dir' ({package_dir})\"\n            )\n            raise ValueError(msg)\n\n    return exts\n\n\ndef naive_recompile(obj: str, src: str) -> bool:\n    \"\"\"\n    This will recompile only if the source file changes. It does not check\n    header files, so a more advanced function or Ccache is better if you have\n    editable header files in your package.\n    \"\"\"\n    return os.stat(obj).st_mtime < os.stat(src).st_mtime\n\n\ndef no_recompile(obg: str, src: str) -> bool:  # noqa: ARG001\n    \"\"\"\n    This is the safest but slowest choice (and is the default) - will always\n    recompile sources.\n    \"\"\"\n    return True\n\n\nS = TypeVar(\"S\", bound=\"ParallelCompile\")\n\nCCompilerMethod = Callable[\n    [\n        distutils.ccompiler.CCompiler,\n        List[str],\n        Optional[str],\n        Optional[List[Union[Tuple[str], Tuple[str, Optional[str]]]]],\n        Optional[List[str]],\n        bool,\n        Optional[List[str]],\n        Optional[List[str]],\n        Optional[List[str]],\n    ],\n    List[str],\n]\n\n\n# Optional parallel compile utility\n# inspired by: http://stackoverflow.com/questions/11013851/speeding-up-build-process-with-distutils\n# and: https://github.com/tbenthompson/cppimport/blob/stable/cppimport/build_module.py\n# and NumPy's parallel distutils module:\n#              https://github.com/numpy/numpy/blob/master/numpy/distutils/ccompiler.py\nclass ParallelCompile:\n    \"\"\"\n    Make a parallel compile function. Inspired by\n    numpy.distutils.ccompiler.CCompiler.compile and cppimport.\n\n    This takes several arguments that allow you to customize the compile\n    function created:\n\n    envvar:\n        Set an environment variable to control the compilation threads, like\n        NPY_NUM_BUILD_JOBS\n    default:\n        0 will automatically multithread, or 1 will only multithread if the\n        envvar is set.\n    max:\n        The limit for automatic multithreading if non-zero\n    needs_recompile:\n        A function of (obj, src) that returns True when recompile is needed.  No\n        effect in isolated mode; use ccache instead, see\n        https://github.com/matplotlib/matplotlib/issues/1507/\n\n    To use::\n\n        ParallelCompile(\"NPY_NUM_BUILD_JOBS\").install()\n\n    or::\n\n        with ParallelCompile(\"NPY_NUM_BUILD_JOBS\"):\n            setup(...)\n\n    By default, this assumes all files need to be recompiled. A smarter\n    function can be provided via needs_recompile.  If the output has not yet\n    been generated, the compile will always run, and this function is not\n    called.\n    \"\"\"\n\n    __slots__ = (\"envvar\", \"default\", \"max\", \"_old\", \"needs_recompile\")\n\n    def __init__(\n        self,\n        envvar: str | None = None,\n        default: int = 0,\n        max: int = 0,  # pylint: disable=redefined-builtin\n        needs_recompile: Callable[[str, str], bool] = no_recompile,\n    ) -> None:\n        self.envvar = envvar\n        self.default = default\n        self.max = max\n        self.needs_recompile = needs_recompile\n        self._old: list[CCompilerMethod] = []\n\n    def function(self) -> CCompilerMethod:\n        \"\"\"\n        Builds a function object usable as distutils.ccompiler.CCompiler.compile.\n        \"\"\"\n\n        def compile_function(\n            compiler: distutils.ccompiler.CCompiler,\n            sources: list[str],\n            output_dir: str | None = None,\n            macros: list[tuple[str] | tuple[str, str | None]] | None = None,\n            include_dirs: list[str] | None = None,\n            debug: bool = False,\n            extra_preargs: list[str] | None = None,\n            extra_postargs: list[str] | None = None,\n            depends: list[str] | None = None,\n        ) -> Any:\n            # These lines are directly from distutils.ccompiler.CCompiler\n            macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile(  # type: ignore[attr-defined]\n                output_dir, macros, include_dirs, sources, depends, extra_postargs\n            )\n            cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs)  # type: ignore[attr-defined]\n\n            # The number of threads; start with default.\n            threads = self.default\n\n            # Determine the number of compilation threads, unless set by an environment variable.\n            if self.envvar is not None:\n                threads = int(os.environ.get(self.envvar, self.default))\n\n            def _single_compile(obj: Any) -> None:\n                try:\n                    src, ext = build[obj]\n                except KeyError:\n                    return\n\n                if not os.path.exists(obj) or self.needs_recompile(obj, src):\n                    compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)  # type: ignore[attr-defined]\n\n            try:\n                # Importing .synchronize checks for platforms that have some multiprocessing\n                # capabilities but lack semaphores, such as AWS Lambda and Android Termux.\n                import multiprocessing.synchronize\n                from multiprocessing.pool import ThreadPool\n            except ImportError:\n                threads = 1\n\n            if threads == 0:\n                try:\n                    threads = multiprocessing.cpu_count()\n                    threads = self.max if self.max and self.max < threads else threads\n                except NotImplementedError:\n                    threads = 1\n\n            if threads > 1:\n                with ThreadPool(threads) as pool:\n                    for _ in pool.imap_unordered(_single_compile, objects):\n                        pass\n            else:\n                for ob in objects:\n                    _single_compile(ob)\n\n            return objects\n\n        return compile_function\n\n    def install(self: S) -> S:\n        \"\"\"\n        Installs the compile function into distutils.ccompiler.CCompiler.compile.\n        \"\"\"\n        distutils.ccompiler.CCompiler.compile = self.function()  # type: ignore[assignment]\n        return self\n\n    def __enter__(self: S) -> S:\n        self._old.append(distutils.ccompiler.CCompiler.compile)\n        return self.install()\n\n    def __exit__(self, *args: Any) -> None:\n        distutils.ccompiler.CCompiler.compile = self._old.pop()  # type: ignore[assignment]\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"scikit-build-core >=0.11.2\"]\nbuild-backend = \"scikit_build_core.build\"\n\n[project]\nname = \"pybind11\"\ndescription = \"Seamless operability between C++11 and Python\"\nauthors = [{name = \"Wenzel Jakob\", email = \"wenzel.jakob@epfl.ch\"}]\nlicense = \"BSD-3-Clause\"\nlicense-files = [\"LICENSE\"]\nreadme = \"README.rst\"\nclassifiers = [\n    \"Development Status :: 5 - Production/Stable\",\n    \"Intended Audience :: Developers\",\n    \"Topic :: Software Development :: Libraries :: Python Modules\",\n    \"Topic :: Utilities\",\n    \"Programming Language :: C++\",\n    \"Programming Language :: Python :: 3 :: Only\",\n    \"Programming Language :: Python :: 3.8\",\n    \"Programming Language :: Python :: 3.9\",\n    \"Programming Language :: Python :: 3.10\",\n    \"Programming Language :: Python :: 3.11\",\n    \"Programming Language :: Python :: 3.12\",\n    \"Programming Language :: Python :: 3.13\",\n    \"Programming Language :: Python :: 3.14\",\n    \"Programming Language :: Python :: Implementation :: PyPy\",\n    \"Programming Language :: Python :: Implementation :: CPython\",\n    \"Programming Language :: C++\",\n    \"Topic :: Software Development :: Libraries :: Python Modules\",\n]\nkeywords = [\n    \"C++11\",\n    \"Python bindings\",\n]\ndynamic = [\"version\", \"optional-dependencies\"]\nrequires-python = \">=3.8\"\n\n[project.urls]\nHomepage = \"https://github.com/pybind/pybind11\"\nDocumentation = \"https://pybind11.readthedocs.io/\"\n\"Issue Tracker\" = \"https://github.com/pybind/pybind11/issues\"\nDiscussions = \"https://github.com/pybind/pybind11/discussions\"\nChangelog = \"https://pybind11.readthedocs.io/en/latest/changelog.html\"\nChat = \"https://gitter.im/pybind/Lobby\"\n\n[project.scripts]\npybind11-config = \"pybind11.__main__:main\"\n\n[project.entry-points.\"pipx.run\"]\npybind11 = \"pybind11.__main__:main\"\n\n[project.entry-points.pkg_config]\npybind11 = \"pybind11.share.pkgconfig\"\n\n\n[dependency-groups]\ntest = [\n  \"pytest\",\n  \"build\",\n]\ndev = [\n  \"tomlkit\",\n  { include-group = \"test\" }\n]\n\n\n[tool.scikit-build]\nminimum-version = \"build-system.requires\"\nsdist.exclude = [\n  \"/docs/**\",\n  \"/.**\",\n]\nwheel.install-dir = \"pybind11\"\nwheel.platlib = false\n\n[tool.scikit-build.cmake.define]\nBUILD_TESTING = false\nPYBIND11_NOPYTHON = true\nprefix_for_pc_file = \"${pcfiledir}/../../\"\n\n[tool.scikit-build.metadata.version]\nprovider = \"scikit_build_core.metadata.regex\"\ninput = \"include/pybind11/detail/common.h\"\nregex = '''(?sx)\n\\#define \\s+ PYBIND11_VERSION_MAJOR \\s+ (?P<major>\\d+) .*?\n\\#define \\s+ PYBIND11_VERSION_MINOR \\s+ (?P<minor>\\d+) .*?\n\\#define \\s+ PYBIND11_VERSION_PATCH \\s+ (?P<patch>\\S+)\n'''\nresult = \"{major}.{minor}.{patch}\"\n\n[tool.scikit-build.metadata.optional-dependencies]\nprovider = \"scikit_build_core.metadata.template\"\nresult = { global = [\"pybind11-global=={project[version]}\"]}\n\n[[tool.scikit-build.generate]]\npath = \"pybind11/_version.py\"\ntemplate = '''\nfrom __future__ import annotations\n\n\ndef _to_int(s: str) -> int | str:\n    try:\n        return int(s)\n    except ValueError:\n        return s\n\n\n__version__ = \"$version\"\nversion_info = tuple(_to_int(s) for s in __version__.split(\".\"))\n'''\n\n\n[tool.uv]\n# Can't use tool.uv.sources with requirements.txt\nindex-strategy = \"unsafe-best-match\"\n# This extra confuses uv\noverride-dependencies = [\"pybind11-global\"]\n\n\n[tool.mypy]\nfiles = [\"pybind11\"]\npython_version = \"3.8\"\nstrict = true\nenable_error_code = [\"ignore-without-code\", \"redundant-expr\", \"truthy-bool\"]\nwarn_unreachable = true\n\n[[tool.mypy.overrides]]\nmodule = [\"ghapi.*\", \"tomlkit\"]  # tomlkit has types, but not very helpful\nignore_missing_imports = true\n\n\n[tool.pylint]\nmaster.py-version = \"3.8\"\nreports.output-format = \"colorized\"\nmessages_control.disable = [\n  \"design\",\n  \"fixme\",\n  \"imports\",\n  \"line-too-long\",\n  \"imports\",\n  \"invalid-name\",\n  \"protected-access\",\n  \"missing-module-docstring\",\n  \"unused-argument\",  # covered by Ruff ARG\n  \"consider-using-f-string\", # triggers in _version.py incorrectly\n]\n\n[tool.ruff.lint]\nextend-select = [\n  \"B\",           # flake8-bugbear\n  \"I\",           # isort\n  \"N\",           # pep8-naming\n  \"ARG\",         # flake8-unused-arguments\n  \"C4\",          # flake8-comprehensions\n  \"EM\",          # flake8-errmsg\n  \"ICN\",         # flake8-import-conventions\n  \"ISC\",         # flake8-implicit-str-concat\n  \"PERF\",        # Perflint\n  \"PGH\",         # pygrep-hooks\n  \"PIE\",         # flake8-pie\n  \"PL\",          # pylint\n  \"PT\",          # flake8-pytest-style\n  \"RET\",         # flake8-return\n  \"RUF100\",      # Ruff-specific\n  \"SIM\",         # flake8-simplify\n  \"UP\",          # pyupgrade\n  \"YTT\",         # flake8-2020\n]\nignore = [\n  \"PLR\",     # Design related pylint\n  \"PT011\",   # Too broad with raises in pytest\n  \"SIM118\",  # iter(x) is not always the same as iter(x.keys())\n  \"PLC0415\", # We import in functions for various reasons\n]\nisort.known-first-party = [\"env\", \"pybind11_cross_module_tests\", \"pybind11_tests\"]\nisort.required-imports = [\"from __future__ import annotations\"]\n\n\n[tool.ruff.lint.per-file-ignores]\n\"tests/**\" = [\n  \"EM\",\n  \"N\",\n  \"E721\",\n]\n\"tests/test_call_policies.py\" = [\"PLC1901\"]\n\n[tool.repo-review]\nignore = [\"PP\"]\n\n[tool.typos]\nfiles.extend-exclude = [\"/cpython\"]\n\n[tool.typos.default.extend-identifiers]\nser_no = \"ser_no\"\nSerNo = \"SerNo\"\nStrLits = \"StrLits\"\n\n[tool.typos.default.extend-words]\nnd = \"nd\"\nvalu = \"valu\"\nfo = \"fo\"\nquater = \"quater\"\noptin = \"optin\"\nothr = \"othr\"\n\n#[tool.typos.type.cpp.extend-words]\nsetp = \"setp\"\not = \"ot\"\n\n[tool.typos.type.json.extend-words]\nba = \"ba\"\n"
  },
  {
    "path": "tests/CMakeLists.txt",
    "content": "# CMakeLists.txt -- Build system for the pybind11 test suite\n#\n# Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\ncmake_minimum_required(VERSION 3.15...4.2)\n\n# Filter out items; print an optional message if any items filtered. This ignores extensions.\n#\n# Usage:\n#   pybind11_filter_tests(LISTNAME file1.cpp file2.cpp ... MESSAGE \"\")\n#\nmacro(pybind11_filter_tests LISTNAME)\n  cmake_parse_arguments(ARG \"\" \"MESSAGE\" \"\" ${ARGN})\n  set(PYBIND11_FILTER_TESTS_FOUND OFF)\n  # Make a list of the test without any extensions, for easier filtering.\n  set(_TMP_ACTUAL_LIST \"${${LISTNAME}};\") # enforce ';' at the end to allow matching last item.\n  string(REGEX REPLACE \"\\\\.[^.;]*;\" \";\" LIST_WITHOUT_EXTENSIONS \"${_TMP_ACTUAL_LIST}\")\n  foreach(filename IN LISTS ARG_UNPARSED_ARGUMENTS)\n    string(REGEX REPLACE \"\\\\.[^.]*$\" \"\" filename_no_ext ${filename})\n    # Search in the list without extensions.\n    list(FIND LIST_WITHOUT_EXTENSIONS ${filename_no_ext} _FILE_FOUND)\n    if(_FILE_FOUND GREATER -1)\n      list(REMOVE_AT ${LISTNAME} ${_FILE_FOUND}) # And remove from the list with extensions.\n      list(REMOVE_AT LIST_WITHOUT_EXTENSIONS ${_FILE_FOUND}\n      )# And our search list, to ensure it is in sync.\n      set(PYBIND11_FILTER_TESTS_FOUND ON)\n    endif()\n  endforeach()\n  if(PYBIND11_FILTER_TESTS_FOUND AND ARG_MESSAGE)\n    message(STATUS \"${ARG_MESSAGE}\")\n  endif()\nendmacro()\n\nmacro(possibly_uninitialized)\n  foreach(VARNAME ${ARGN})\n    if(NOT DEFINED \"${VARNAME}\")\n      set(\"${VARNAME}\" \"\")\n    endif()\n  endforeach()\nendmacro()\n\n# Function to add additional targets if any of the provided tests are found.\n# Needles; Specifies the test names to look for.\n# Additions; Specifies the additional test targets to add when any of the needles are found.\nmacro(tests_extra_targets needles additions)\n  # Add the index for this relation to the index extra targets map.\n  list(LENGTH PYBIND11_TEST_EXTRA_TARGETS PYBIND11_TEST_EXTRA_TARGETS_LEN)\n  list(APPEND PYBIND11_TEST_EXTRA_TARGETS ${PYBIND11_TEST_EXTRA_TARGETS_LEN})\n  # Add the test names to look for, and the associated test target additions.\n  set(PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${needles})\n  set(PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${PYBIND11_TEST_EXTRA_TARGETS_LEN} ${additions})\nendmacro()\n\n# New Python support\nif(DEFINED Python_EXECUTABLE)\n  set(PYTHON_EXECUTABLE \"${Python_EXECUTABLE}\")\n  set(PYTHON_VERSION \"${Python_VERSION}\")\nendif()\n\n# There's no harm in including a project in a project\nproject(pybind11_tests CXX)\n\n# Access FindCatch and more\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_CURRENT_LIST_DIR}/../tools\")\n\noption(PYBIND11_WERROR \"Report all warnings as errors\" OFF)\noption(DOWNLOAD_CATCH \"Download catch2 if not found\" OFF)\noption(DOWNLOAD_EIGEN \"Download EIGEN\" OFF)\noption(PYBIND11_CUDA_TESTS \"Enable building CUDA tests\" OFF)\noption(PYBIND11_TEST_SMART_HOLDER \"Change the default to smart holder\" OFF)\nset(PYBIND11_TEST_OVERRIDE\n    \"\"\n    CACHE STRING \"Tests from ;-separated list of *.cpp files will be built instead of all tests\")\nset(PYBIND11_TEST_FILTER\n    \"\"\n    CACHE STRING \"Tests from ;-separated list of *.cpp files will be removed from all tests\")\n\nif(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)\n  # We're being loaded directly, i.e. not via add_subdirectory, so make this\n  # work as its own project and load the pybind11Config to get the tools we need\n\n  if(SKBUILD)\n    add_subdirectory(.. pybind11_src)\n  else()\n    find_package(pybind11 REQUIRED CONFIG)\n  endif()\nendif()\n\nif(NOT CMAKE_BUILD_TYPE AND NOT DEFINED CMAKE_CONFIGURATION_TYPES)\n  message(STATUS \"Setting tests build type to MinSizeRel as none was specified\")\n  set(CMAKE_BUILD_TYPE\n      MinSizeRel\n      CACHE STRING \"Choose the type of build.\" FORCE)\n  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS \"Debug\" \"Release\" \"MinSizeRel\"\n                                               \"RelWithDebInfo\")\nendif()\n\nif(PYBIND11_CUDA_TESTS)\n  enable_language(CUDA)\n  if(DEFINED CMAKE_CXX_STANDARD)\n    set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD})\n  endif()\n  set(CMAKE_CUDA_STANDARD_REQUIRED ON)\nendif()\n\n# Full set of test files (you can override these; see below, overrides ignore extension)\n# Any test that has no extension is both .py and .cpp, so 'foo' will add 'foo.cpp' and 'foo.py'.\n# Any test that has an extension is exclusively that and handled as such.\nset(PYBIND11_TEST_FILES\n    test_async\n    test_buffers\n    test_builtin_casters\n    test_call_policies\n    test_callbacks\n    test_chrono\n    test_class\n    test_class_cross_module_use_after_one_module_dealloc\n    test_class_release_gil_before_calling_cpp_dtor\n    test_class_sh_basic\n    test_class_sh_disowning\n    test_class_sh_disowning_mi\n    test_class_sh_factory_constructors\n    test_class_sh_inheritance\n    test_class_sh_mi_thunks\n    test_class_sh_property\n    test_class_sh_property_non_owning\n    test_class_sh_shared_ptr_copy_move\n    test_class_sh_trampoline_basic\n    test_class_sh_trampoline_self_life_support\n    test_class_sh_trampoline_shared_from_this\n    test_class_sh_trampoline_shared_ptr_cpp_arg\n    test_class_sh_trampoline_unique_ptr\n    test_class_sh_unique_ptr_custom_deleter\n    test_class_sh_unique_ptr_member\n    test_class_sh_virtual_py_cpp_mix\n    test_const_name\n    test_constants_and_functions\n    test_copy_move\n    test_cpp_conduit\n    test_custom_type_casters\n    test_custom_type_setup\n    test_docstring_options\n    test_docs_advanced_cast_custom\n    test_eigen_matrix\n    test_eigen_tensor\n    test_enum\n    test_eval\n    test_exceptions\n    test_factory_constructors\n    test_gil_scoped\n    test_iostream\n    test_kwargs_and_defaults\n    test_local_bindings\n    test_methods_and_attributes\n    test_modules\n    test_multiple_inheritance\n    test_multiple_interpreters.py\n    test_native_enum\n    test_numpy_array\n    test_numpy_dtypes\n    test_numpy_scalars\n    test_numpy_vectorize\n    test_opaque_types\n    test_operator_overloading\n    test_pickling\n    test_potentially_slicing_weak_ptr\n    test_python_multiple_inheritance\n    test_pytypes\n    test_scoped_critical_section\n    test_sequences_and_iterators\n    test_smart_ptr\n    test_stl\n    test_stl_binders\n    test_tagbased_polymorphic\n    test_thread\n    test_type_caster_pyobject_ptr\n    test_type_caster_std_function_specializations\n    test_union\n    test_unnamed_namespace_a\n    test_unnamed_namespace_b\n    test_vector_unique_ptr_member\n    test_virtual_functions\n    test_warnings)\n\n# Invoking cmake with something like:\n#     cmake -DPYBIND11_TEST_OVERRIDE=\"test_callbacks.cpp;test_pickling.cpp\" ..\n# lets you override the tests that get compiled and run.  You can restore to all tests with:\n#     cmake -DPYBIND11_TEST_OVERRIDE= ..\nif(PYBIND11_TEST_OVERRIDE)\n  # Instead of doing a direct override here, we iterate over the overrides without extension and\n  # match them against entries from the PYBIND11_TEST_FILES, anything that not matches goes into the filter list.\n  string(REGEX REPLACE \"\\\\.[^.;]*;\" \";\" TEST_OVERRIDE_NO_EXT \"${PYBIND11_TEST_OVERRIDE};\")\n  string(REGEX REPLACE \"\\\\.[^.;]*;\" \";\" TEST_FILES_NO_EXT \"${PYBIND11_TEST_FILES};\")\n  # This allows the override to be done with extensions, preserving backwards compatibility.\n  foreach(test_name ${TEST_FILES_NO_EXT})\n    if(NOT ${test_name} IN_LIST TEST_OVERRIDE_NO_EXT\n    )# If not in the allowlist, add to be filtered out.\n      list(APPEND PYBIND11_TEST_FILTER ${test_name})\n    endif()\n  endforeach()\nendif()\n\n# You can also filter tests:\nif(PYBIND11_TEST_FILTER)\n  pybind11_filter_tests(PYBIND11_TEST_FILES ${PYBIND11_TEST_FILTER})\nendif()\n\n# Skip tests for CUDA check:\n# /pybind11/tests/test_constants_and_functions.cpp(125):\n#   error: incompatible exception specifications\nif(PYBIND11_CUDA_TESTS)\n  pybind11_filter_tests(\n    PYBIND11_TEST_FILES test_constants_and_functions.cpp MESSAGE\n    \"Skipping test_constants_and_functions due to incompatible exception specifications\")\nendif()\n\n# Now that the test filtering is complete, we need to split the list into the test for PYTEST\n# and the list for the cpp targets.\nset(PYBIND11_CPPTEST_FILES \"\")\nset(PYBIND11_PYTEST_FILES \"\")\n\nforeach(test_name ${PYBIND11_TEST_FILES})\n  if(test_name MATCHES \"\\\\.py$\") # Ends in .py, purely python test.\n    list(APPEND PYBIND11_PYTEST_FILES ${test_name})\n  elseif(test_name MATCHES \"\\\\.cpp$\") # Ends in .cpp, purely cpp test.\n    list(APPEND PYBIND11_CPPTEST_FILES ${test_name})\n  elseif(NOT test_name MATCHES \"\\\\.\") # No extension specified, assume both, add extension.\n    list(APPEND PYBIND11_PYTEST_FILES ${test_name}.py)\n    list(APPEND PYBIND11_CPPTEST_FILES ${test_name}.cpp)\n  else()\n    message(WARNING \"Unhanded test extension in test: ${test_name}\")\n  endif()\nendforeach()\nset(PYBIND11_TEST_FILES ${PYBIND11_CPPTEST_FILES})\nlist(SORT PYBIND11_PYTEST_FILES)\n\n# Contains the set of test files that require pybind11_cross_module_tests to be\n# built; if none of these are built (i.e. because TEST_OVERRIDE is used and\n# doesn't include them) the second module doesn't get built.\ntests_extra_targets(\n  \"test_class_cross_module_use_after_one_module_dealloc.py;test_exceptions.py;test_local_bindings.py;test_stl.py;test_stl_binders.py\"\n  \"pybind11_cross_module_tests\")\n\n# And add additional targets for other tests.\ntests_extra_targets(\"test_exceptions.py\" \"cross_module_interleaved_error_already_set\")\ntests_extra_targets(\"test_gil_scoped.py\" \"cross_module_gil_utils\")\ntests_extra_targets(\"test_cpp_conduit.py\"\n                    \"exo_planet_pybind11;exo_planet_c_api;home_planet_very_lonely_traveler\")\n\nset(PYBIND11_EIGEN_REPO\n    \"https://gitlab.com/libeigen/eigen.git\"\n    CACHE STRING \"Eigen repository to use for tests\")\n# Always use a hash for reconfigure speed and security reasons\n# Include the version number for pretty printing (keep in sync)\nset(PYBIND11_EIGEN_VERSION_AND_HASH\n    \"3.4.0;929bc0e191d0927b1735b9a1ddc0e8b77e3a25ec\"\n    CACHE STRING \"Eigen version to use for tests, format: VERSION;HASH\")\n\nlist(GET PYBIND11_EIGEN_VERSION_AND_HASH 0 PYBIND11_EIGEN_VERSION_STRING)\nlist(GET PYBIND11_EIGEN_VERSION_AND_HASH 1 PYBIND11_EIGEN_VERSION_HASH)\n\n# Check if Eigen is available; if not, remove from PYBIND11_TEST_FILES (but\n# keep it in PYBIND11_PYTEST_FILES, so that we get the \"eigen is not installed\"\n# skip message).\nlist(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I)\nif(PYBIND11_TEST_FILES_EIGEN_I EQUAL -1)\n  list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I)\nendif()\nif(PYBIND11_TEST_FILES_EIGEN_I GREATER -1)\n  # Try loading via newer Eigen's Eigen3Config first (bypassing tools/FindEigen3.cmake).\n  # Eigen 3.3.1+ exports a cmake 3.0+ target for handling dependency requirements, but also\n  if(DOWNLOAD_EIGEN)\n    if(CMAKE_VERSION VERSION_LESS 3.18)\n      set(_opts)\n    else()\n      set(_opts SOURCE_SUBDIR no-cmake-build)\n    endif()\n    include(FetchContent)\n    FetchContent_Declare(\n      eigen\n      GIT_REPOSITORY \"${PYBIND11_EIGEN_REPO}\"\n      GIT_TAG \"${PYBIND11_EIGEN_VERSION_HASH}\"\n      ${_opts})\n    FetchContent_MakeAvailable(eigen)\n    if(NOT CMAKE_VERSION VERSION_LESS 3.18)\n      set(EIGEN3_INCLUDE_DIR \"${eigen_SOURCE_DIR}\")\n    endif()\n\n    set(EIGEN3_INCLUDE_DIR ${eigen_SOURCE_DIR})\n    set(EIGEN3_FOUND TRUE)\n    # When getting locally, the version is not visible from a superprojet,\n    # so just force it.\n    set(EIGEN3_VERSION \"${PYBIND11_EIGEN_VERSION_STRING}\")\n\n  else()\n    find_package(Eigen3 3.2.7 QUIET CONFIG)\n\n    if(NOT EIGEN3_FOUND)\n      # Couldn't load via target, so fall back to allowing module mode finding, which will pick up\n      # tools/FindEigen3.cmake\n      find_package(Eigen3 3.2.7 QUIET)\n    endif()\n  endif()\n\n  if(EIGEN3_FOUND)\n    if(NOT TARGET Eigen3::Eigen)\n      add_library(Eigen3::Eigen IMPORTED INTERFACE)\n      set_property(TARGET Eigen3::Eigen PROPERTY INTERFACE_INCLUDE_DIRECTORIES\n                                                 \"${EIGEN3_INCLUDE_DIR}\")\n    endif()\n\n    # Eigen 3.3.1+ cmake sets EIGEN3_VERSION_STRING (and hard codes the version when installed\n    # rather than looking it up in the cmake script); older versions, and the\n    # tools/FindEigen3.cmake, set EIGEN3_VERSION instead.\n    if(NOT EIGEN3_VERSION AND EIGEN3_VERSION_STRING)\n      set(EIGEN3_VERSION ${EIGEN3_VERSION_STRING})\n    endif()\n    message(STATUS \"Building tests with Eigen v${EIGEN3_VERSION}\")\n\n    if(NOT (CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0))\n      tests_extra_targets(\"test_eigen_tensor.py\" \"eigen_tensor_avoid_stl_array\")\n    endif()\n\n  else()\n    list(FIND PYBIND11_TEST_FILES test_eigen_matrix.cpp PYBIND11_TEST_FILES_EIGEN_I)\n    if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1)\n      list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I})\n    endif()\n\n    list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I)\n    if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1)\n      list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I})\n    endif()\n    message(STATUS \"Building tests WITHOUT Eigen, use -DDOWNLOAD_EIGEN=ON to download\")\n  endif()\nendif()\n\n# Some code doesn't support gcc 4\nif(CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)\n  list(FIND PYBIND11_TEST_FILES test_eigen_tensor.cpp PYBIND11_TEST_FILES_EIGEN_I)\n  if(PYBIND11_TEST_FILES_EIGEN_I GREATER -1)\n    list(REMOVE_AT PYBIND11_TEST_FILES ${PYBIND11_TEST_FILES_EIGEN_I})\n  endif()\nendif()\n\n# Optional dependency for some tests (boost::variant is only supported with version >= 1.56)\nfind_package(Boost 1.56)\n\nif(Boost_FOUND)\n  if(NOT TARGET Boost::headers)\n    add_library(Boost::headers IMPORTED INTERFACE)\n    if(TARGET Boost::boost)\n      # Classic FindBoost\n      set_property(TARGET Boost::headers PROPERTY INTERFACE_LINK_LIBRARIES Boost::boost)\n    else()\n      # Very old FindBoost, or newer Boost than CMake in older CMakes\n      set_property(TARGET Boost::headers PROPERTY INTERFACE_INCLUDE_DIRECTORIES\n                                                  ${Boost_INCLUDE_DIRS})\n    endif()\n  endif()\nendif()\n\n# Check if we need to add -lstdc++fs or -lc++fs or nothing\nif(DEFINED CMAKE_CXX_STANDARD AND CMAKE_CXX_STANDARD LESS 17)\n  set(STD_FS_NO_LIB_NEEDED TRUE)\nelseif(MSVC)\n  set(STD_FS_NO_LIB_NEEDED TRUE)\nelse()\n  file(\n    WRITE ${CMAKE_CURRENT_BINARY_DIR}/main.cpp\n    \"#include <filesystem>\\nint main(int /*argc*/, char ** argv) {\\n  std::filesystem::path p(argv[0]);\\n  return p.string().length();\\n}\"\n  )\n  try_compile(\n    STD_FS_NO_LIB_NEEDED ${CMAKE_CURRENT_BINARY_DIR}\n    SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp\n    COMPILE_DEFINITIONS -std=c++17)\n  try_compile(\n    STD_FS_NEEDS_STDCXXFS ${CMAKE_CURRENT_BINARY_DIR}\n    SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp\n    COMPILE_DEFINITIONS -std=c++17\n    LINK_LIBRARIES stdc++fs)\n  try_compile(\n    STD_FS_NEEDS_CXXFS ${CMAKE_CURRENT_BINARY_DIR}\n    SOURCES ${CMAKE_CURRENT_BINARY_DIR}/main.cpp\n    COMPILE_DEFINITIONS -std=c++17\n    LINK_LIBRARIES c++fs)\nendif()\n\nif(${STD_FS_NEEDS_STDCXXFS})\n  set(STD_FS_LIB stdc++fs)\nelseif(${STD_FS_NEEDS_CXXFS})\n  set(STD_FS_LIB c++fs)\nelseif(${STD_FS_NO_LIB_NEEDED})\n  set(STD_FS_LIB \"\")\nelse()\n  message(WARNING \"Unknown C++17 compiler - not passing -lstdc++fs\")\n  set(STD_FS_LIB \"\")\nendif()\n\n# Compile with compiler warnings turned on\nfunction(pybind11_enable_warnings target_name)\n  if(MSVC)\n    target_compile_options(${target_name} PRIVATE /W4 /wd4189)\n  elseif(CMAKE_CXX_COMPILER_ID MATCHES \"(GNU|Intel|Clang)\" AND NOT PYBIND11_CUDA_TESTS)\n    target_compile_options(\n      ${target_name}\n      PRIVATE -Wall\n              -Wextra\n              -Wconversion\n              -Wcast-qual\n              -Wdeprecated\n              -Wundef\n              -Wnon-virtual-dtor)\n    if(DEFINED CMAKE_CXX_STANDARD AND NOT CMAKE_CXX_STANDARD VERSION_LESS 20)\n      target_compile_options(${target_name} PRIVATE -Wpedantic)\n    endif()\n  endif()\n\n  if(PYBIND11_WERROR)\n    if(CMAKE_CXX_COMPILER_ID STREQUAL \"Intel\")\n      if(CMAKE_CXX_STANDARD EQUAL 17) # See PR #3570\n        target_compile_options(${target_name} PRIVATE -Wno-conversion)\n      endif()\n      # \"Inlining inhibited by limit max-size\", \"Inlining inhibited by limit max-total-size\"\n      target_compile_options(${target_name} PRIVATE -diag-disable 11074,11076)\n    endif()\n\n    if(CMAKE_VERSION VERSION_LESS \"3.24\")\n      if(MSVC)\n        target_compile_options(${target_name} PRIVATE /WX)\n      elseif(PYBIND11_CUDA_TESTS)\n        target_compile_options(${target_name} PRIVATE \"SHELL:-Werror all-warnings\")\n      elseif(CMAKE_CXX_COMPILER_ID MATCHES \"(GNU|Clang|IntelLLVM)\")\n        target_compile_options(${target_name} PRIVATE -Werror)\n      elseif(CMAKE_CXX_COMPILER_ID STREQUAL \"Intel\")\n        target_compile_options(${target_name} PRIVATE -Werror-all)\n      endif()\n    else()\n      set_target_properties(${target_name} PROPERTIES COMPILE_WARNING_AS_ERROR ON)\n    endif()\n  endif()\nendfunction()\n\nset(test_targets pybind11_tests)\n\n# Check if any tests need extra targets by iterating through the mappings registered.\nforeach(i ${PYBIND11_TEST_EXTRA_TARGETS})\n  foreach(needle ${PYBIND11_TEST_EXTRA_TARGETS_NEEDLES_${i}})\n    if(needle IN_LIST PYBIND11_PYTEST_FILES)\n      # Add all the additional targets to the test list. List join in newer cmake.\n      foreach(extra_target ${PYBIND11_TEST_EXTRA_TARGETS_ADDITION_${i}})\n        list(APPEND test_targets ${extra_target})\n      endforeach()\n      break() # Breaks out of the needle search, continues with the next mapping.\n    endif()\n  endforeach()\nendforeach()\n\n# Support CUDA testing by forcing the target file to compile with NVCC\nif(PYBIND11_CUDA_TESTS)\n  set_property(SOURCE ${PYBIND11_TEST_FILES} PROPERTY LANGUAGE CUDA)\nendif()\n\nforeach(target ${test_targets})\n  set(test_files ${PYBIND11_TEST_FILES})\n  if(NOT \"${target}\" STREQUAL \"pybind11_tests\")\n    set(test_files \"\")\n  endif()\n\n  # Support CUDA testing by forcing the target file to compile with NVCC\n  if(PYBIND11_CUDA_TESTS)\n    set_property(SOURCE ${target}.cpp PROPERTY LANGUAGE CUDA)\n  endif()\n\n  # Create the binding library\n  pybind11_add_module(${target} THIN_LTO ${target}.cpp ${test_files} ${PYBIND11_HEADERS})\n  pybind11_enable_warnings(${target})\n\n  if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)\n    get_property(\n      suffix\n      TARGET ${target}\n      PROPERTY SUFFIX)\n    set(source_output \"${CMAKE_CURRENT_SOURCE_DIR}/${target}${suffix}\")\n    if(suffix AND EXISTS \"${source_output}\")\n      message(WARNING \"Output file also in source directory; \"\n                      \"please remove to avoid confusion: ${source_output}\")\n    endif()\n  endif()\n\n  if(MSVC)\n    target_compile_options(${target} PRIVATE /utf-8)\n  endif()\n\n  if(EIGEN3_FOUND)\n    target_link_libraries(${target} PRIVATE Eigen3::Eigen)\n    target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_EIGEN)\n  endif()\n\n  if(Boost_FOUND)\n    target_link_libraries(${target} PRIVATE Boost::headers)\n    target_compile_definitions(${target} PRIVATE -DPYBIND11_TEST_BOOST)\n  endif()\n\n  if(PYBIND11_TEST_SMART_HOLDER)\n    target_compile_definitions(\n      ${target}\n      PUBLIC -DPYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE\n    )\n  endif()\n\n  target_link_libraries(${target} PRIVATE ${STD_FS_LIB})\n\n  # Always write the output file directly into the 'tests' directory (even on MSVC)\n  if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY)\n    set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY\n                                               \"${CMAKE_CURRENT_BINARY_DIR}\")\n\n    if(DEFINED CMAKE_CONFIGURATION_TYPES)\n      foreach(config ${CMAKE_CONFIGURATION_TYPES})\n        string(TOUPPER ${config} config)\n        set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${config}\n                                                   \"${CMAKE_CURRENT_BINARY_DIR}\")\n      endforeach()\n    endif()\n  endif()\n  if(SKBUILD)\n    install(TARGETS ${target} LIBRARY DESTINATION .)\n  endif()\n\n  if(\"${target}\" STREQUAL \"exo_planet_c_api\")\n    if(CMAKE_CXX_COMPILER_ID MATCHES \"(GNU|Intel|Clang|NVHPC)\")\n      target_compile_options(${target} PRIVATE -fno-exceptions)\n    endif()\n  endif()\nendforeach()\n\n# Provide nice organisation in IDEs\nsource_group(\n  TREE \"${CMAKE_CURRENT_SOURCE_DIR}/../include\"\n  PREFIX \"Header Files\"\n  FILES ${PYBIND11_HEADERS})\n\n# Make sure pytest is found or produce a warning\nif(NOT CMAKE_CROSSCOMPILING)\n  pybind11_find_import(pytest VERSION 3.1)\nendif()\n\nif(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)\n  # This is not used later in the build, so it's okay to regenerate each time.\n  configure_file(\"${CMAKE_CURRENT_SOURCE_DIR}/pytest.ini\" \"${CMAKE_CURRENT_BINARY_DIR}/pytest.ini\"\n                 COPYONLY)\n  file(APPEND \"${CMAKE_CURRENT_BINARY_DIR}/pytest.ini\"\n       \"\\ntestpaths = \\\"${CMAKE_CURRENT_SOURCE_DIR}\\\"\")\n\nendif()\n\n# Convert relative to full file names\nlist(TRANSFORM PYBIND11_PYTEST_FILES PREPEND \"${CMAKE_CURRENT_SOURCE_DIR}/\"\n                                             OUTPUT_VARIABLE PYBIND11_ABS_PYTEST_FILES)\n\nset(PYBIND11_TEST_PREFIX_COMMAND\n    \"\"\n    CACHE STRING \"Put this before pytest, use for checkers and such\")\n\nset(PYBIND11_PYTEST_ARGS\n    \"\"\n    CACHE STRING \"Extra arguments for pytest\")\n\n# A single command to compile and run the tests\nadd_custom_target(\n  pytest\n  COMMAND ${PYBIND11_TEST_PREFIX_COMMAND} ${PYTHON_EXECUTABLE} -m pytest\n          ${PYBIND11_ABS_PYTEST_FILES} ${PYBIND11_PYTEST_ARGS}\n  DEPENDS ${test_targets}\n  WORKING_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}\"\n  USES_TERMINAL)\n\nif(NOT PYBIND11_CUDA_TESTS)\n  set(PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES\n      mod_per_interpreter_gil mod_shared_interpreter_gil mod_per_interpreter_gil_with_singleton)\n\n  # These modules don't get mixed with other test modules because those aren't subinterpreter safe.\n  foreach(mod IN LISTS PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES)\n    pybind11_add_module(\"${mod}\" THIN_LTO \"${mod}.cpp\")\n    pybind11_enable_warnings(\"${mod}\")\n  endforeach()\n\n  # Put the built modules next to `pybind11_tests.so` so that the test scripts can find them.\n  get_target_property(pybind11_tests_output_directory pybind11_tests LIBRARY_OUTPUT_DIRECTORY)\n  foreach(mod IN LISTS PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES)\n    set_target_properties(\"${mod}\" PROPERTIES LIBRARY_OUTPUT_DIRECTORY\n                                              \"${pybind11_tests_output_directory}\")\n    # Also set config-specific output directories for multi-configuration generators (MSVC)\n    if(DEFINED CMAKE_CONFIGURATION_TYPES)\n      foreach(config ${CMAKE_CONFIGURATION_TYPES})\n        string(TOUPPER ${config} config)\n        set_target_properties(\"${mod}\" PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${config}\n                                                  \"${pybind11_tests_output_directory}\")\n      endforeach()\n    endif()\n  endforeach()\n\n  if(SKBUILD)\n    foreach(mod IN LISTS PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES)\n      install(TARGETS \"${mod}\" LIBRARY DESTINATION .)\n    endforeach()\n  endif()\n\n  if(PYBIND11_TEST_SMART_HOLDER)\n    foreach(mod IN LISTS PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES)\n      target_compile_definitions(\n        \"${mod}\"\n        PUBLIC\n          -DPYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE)\n    endforeach()\n  endif()\n\n  add_dependencies(pytest ${PYBIND11_MULTIPLE_INTERPRETERS_TEST_MODULES})\nendif()\n\nif(PYBIND11_TEST_OVERRIDE)\n  add_custom_command(\n    TARGET pytest\n    POST_BUILD\n    COMMAND ${CMAKE_COMMAND} -E echo\n            \"Note: not all tests run: -DPYBIND11_TEST_OVERRIDE is in effect\")\nendif()\n\n# cmake-format: off\nadd_custom_target(\n  memcheck\n  COMMAND\n    PYTHONMALLOC=malloc\n    valgrind\n    --leak-check=full\n    --show-leak-kinds=definite,indirect\n    --errors-for-leak-kinds=definite,indirect\n    --error-exitcode=1\n    --read-var-info=yes\n    --track-origins=yes\n    --suppressions=\"${CMAKE_CURRENT_SOURCE_DIR}/valgrind-python.supp\"\n    --suppressions=\"${CMAKE_CURRENT_SOURCE_DIR}/valgrind-numpy-scipy.supp\"\n    --gen-suppressions=all\n    ${PYTHON_EXECUTABLE} -m pytest ${PYBIND11_ABS_PYTEST_FILES}\n  DEPENDS ${test_targets}\n  WORKING_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}\"\n  USES_TERMINAL)\n# cmake-format: on\n\n# Add a check target to run all the tests, starting with pytest (we add dependencies to this below)\nadd_custom_target(check DEPENDS pytest)\n\n# The remaining tests only apply when being built as part of the pybind11 project, but not if the\n# tests are being built independently.\nif(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)\n  return()\nendif()\n\n# Add a post-build comment to show the primary test suite .so size and, if a previous size, compare it:\nadd_custom_command(\n  TARGET pybind11_tests\n  POST_BUILD\n  COMMAND\n    ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/../tools/libsize.py\n    $<TARGET_FILE:pybind11_tests>\n    ${CMAKE_CURRENT_BINARY_DIR}/sosize-$<TARGET_FILE_NAME:pybind11_tests>.txt)\n\nif(NOT PYBIND11_CUDA_TESTS)\n  # Test pure C++ code (not depending on Python). Provides the `test_pure_cpp` target.\n  add_subdirectory(pure_cpp)\n\n  # Test C++ code that depends on Python, such as embedding the interpreter. Provides the `cpptest` target.\n  add_subdirectory(test_with_catch)\n\n  # Test CMake build using functions and targets from subdirectory or installed location\n  add_subdirectory(test_cmake_build)\n\n  # Test visibility of common symbols across shared libraries\n  add_subdirectory(test_cross_module_rtti)\nendif()\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "\"\"\"pytest configuration\n\nExtends output capture as needed by pybind11: ignore constructors, optional unordered lines.\nAdds docstring and exceptions message sanitizers.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport difflib\nimport gc\nimport importlib.metadata\nimport multiprocessing\nimport re\nimport sys\nimport sysconfig\nimport textwrap\nimport traceback\nimport weakref\nfrom typing import Callable\n\nimport pytest\n\n# Early diagnostic for failed imports\ntry:\n    import pybind11_tests\nexcept Exception:\n    # pytest does not show the traceback without this.\n    traceback.print_exc()\n    raise\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef use_multiprocessing_forkserver_on_linux():\n    if sys.platform != \"linux\" or sys.implementation.name == \"graalpy\":\n        # The default on Windows, macOS and GraalPy is \"spawn\": If it's not broken, don't fix it.\n        return\n\n    # Full background: https://github.com/pybind/pybind11/issues/4105#issuecomment-1301004592\n    # In a nutshell: fork() after starting threads == flakiness in the form of deadlocks.\n    # It is actually a well-known pitfall, unfortunately without guard rails.\n    # \"forkserver\" is more performant than \"spawn\" (~9s vs ~13s for tests/test_gil_scoped.py,\n    # visit the issuecomment link above for details).\n    multiprocessing.set_start_method(\"forkserver\")\n\n\n_long_marker = re.compile(r\"([0-9])L\")\n_hexadecimal = re.compile(r\"0x[0-9a-fA-F]+\")\n\n# Avoid collecting Python3 only files\ncollect_ignore = []\n\n\ndef _strip_and_dedent(s):\n    \"\"\"For triple-quote strings\"\"\"\n    return textwrap.dedent(s.lstrip(\"\\n\").rstrip())\n\n\ndef _split_and_sort(s):\n    \"\"\"For output which does not require specific line order\"\"\"\n    return sorted(_strip_and_dedent(s).splitlines())\n\n\ndef _make_explanation(a, b):\n    \"\"\"Explanation for a failed assert -- the a and b arguments are List[str]\"\"\"\n    return [\"--- actual / +++ expected\"] + [\n        line.strip(\"\\n\") for line in difflib.ndiff(a, b)\n    ]\n\n\nclass Output:\n    \"\"\"Basic output post-processing and comparison\"\"\"\n\n    def __init__(self, string):\n        self.string = string\n        self.explanation = []\n\n    def __str__(self):\n        return self.string\n\n    __hash__ = None\n\n    def __eq__(self, other):\n        # Ignore constructor/destructor output which is prefixed with \"###\"\n        a = [\n            line\n            for line in self.string.strip().splitlines()\n            if not line.startswith(\"###\")\n        ]\n        b = _strip_and_dedent(other).splitlines()\n        if a == b:\n            return True\n        self.explanation = _make_explanation(a, b)\n        return False\n\n\nclass Unordered(Output):\n    \"\"\"Custom comparison for output without strict line ordering\"\"\"\n\n    __hash__ = None\n\n    def __eq__(self, other):\n        a = _split_and_sort(self.string)\n        b = _split_and_sort(other)\n        if a == b:\n            return True\n        self.explanation = _make_explanation(a, b)\n        return False\n\n\nclass Capture:\n    def __init__(self, capfd):\n        self.capfd = capfd\n        self.out = \"\"\n        self.err = \"\"\n\n    def __enter__(self):\n        self.capfd.readouterr()\n        return self\n\n    def __exit__(self, *args):\n        self.out, self.err = self.capfd.readouterr()\n\n    __hash__ = None\n\n    def __eq__(self, other):\n        a = Output(self.out)\n        b = other\n        if a == b:\n            return True\n        self.explanation = a.explanation\n        return False\n\n    def __str__(self):\n        return self.out\n\n    def __contains__(self, item):\n        return item in self.out\n\n    @property\n    def unordered(self):\n        return Unordered(self.out)\n\n    @property\n    def stderr(self):\n        return Output(self.err)\n\n\n@pytest.fixture\ndef capture(capsys):\n    \"\"\"Extended `capsys` with context manager and custom equality operators\"\"\"\n    return Capture(capsys)\n\n\nclass SanitizedString:\n    def __init__(self, sanitizer):\n        self.sanitizer = sanitizer\n        self.string = \"\"\n        self.explanation = []\n\n    def __call__(self, thing):\n        self.string = self.sanitizer(thing)\n        return self\n\n    __hash__ = None\n\n    def __eq__(self, other):\n        a = self.string\n        b = _strip_and_dedent(other)\n        if a == b:\n            return True\n        self.explanation = _make_explanation(a.splitlines(), b.splitlines())\n        return False\n\n\ndef _sanitize_general(s):\n    s = s.strip()\n    s = s.replace(\"pybind11_tests.\", \"m.\")\n    return _long_marker.sub(r\"\\1\", s)\n\n\ndef _sanitize_docstring(thing):\n    s = thing.__doc__\n    return _sanitize_general(s)\n\n\n@pytest.fixture\ndef doc():\n    \"\"\"Sanitize docstrings and add custom failure explanation\"\"\"\n    return SanitizedString(_sanitize_docstring)\n\n\ndef _sanitize_message(thing):\n    s = str(thing)\n    s = _sanitize_general(s)\n    return _hexadecimal.sub(\"0\", s)\n\n\n@pytest.fixture\ndef msg():\n    \"\"\"Sanitize messages and add custom failure explanation\"\"\"\n    return SanitizedString(_sanitize_message)\n\n\ndef pytest_assertrepr_compare(op, left, right):  # noqa: ARG001\n    \"\"\"Hook to insert custom failure explanation\"\"\"\n    if hasattr(left, \"explanation\"):\n        return left.explanation\n    return None\n\n\n# Number of times we think repeatedly collecting garbage might do anything.\n# The only reason to do more than once is because finalizers executed during\n# one GC pass could create garbage that can't be collected until a future one.\n# This quickly produces diminishing returns, and GC passes can be slow, so this\n# value is a tradeoff between non-flakiness and fast tests. (It errs on the\n# side of non-flakiness; many uses of this idiom only do 3 passes.)\nnum_gc_collect = 5\n\n\ndef gc_collect():\n    \"\"\"Run the garbage collector several times (needed when running\n    reference counting tests with PyPy)\"\"\"\n    for _ in range(num_gc_collect):\n        gc.collect()\n\n\ndef delattr_and_ensure_destroyed(*specs):\n    \"\"\"For each of the given *specs* (a tuple of the form ``(scope, name)``),\n    perform ``delattr(scope, name)``, then do enough GC collections that the\n    deleted reference has actually caused the target to be destroyed. This is\n    typically used to test what happens when a type object is destroyed; if you\n    use it for that, you should be aware that extension types, or all types,\n    are immortal on some Python versions. See ``env.TYPES_ARE_IMMORTAL``.\n    \"\"\"\n    wrs = []\n    for mod, name in specs:\n        wrs.append(weakref.ref(getattr(mod, name)))\n        delattr(mod, name)\n\n    for _ in range(num_gc_collect):\n        gc.collect()\n        if all(wr() is None for wr in wrs):\n            break\n    else:\n        # If this fires, most likely something is still holding a reference\n        # to the object you tried to destroy - for example, it's a type that\n        # still has some instances alive. Try setting a breakpoint here and\n        # examining `gc.get_referrers(wrs[0]())`. It's vaguely possible that\n        # num_gc_collect needs to be increased also.\n        pytest.fail(\n            f\"Could not delete bindings such as {next(wr for wr in wrs if wr() is not None)!r}\"\n        )\n\n\ndef pytest_configure():\n    pytest.suppress = contextlib.suppress\n    pytest.gc_collect = gc_collect\n    pytest.delattr_and_ensure_destroyed = delattr_and_ensure_destroyed\n\n\ndef pytest_report_header():\n    assert pybind11_tests.compiler_info is not None, (\n        \"Please update pybind11_tests.cpp if this assert fails.\"\n    )\n    interesting_packages = (\"pybind11\", \"numpy\", \"scipy\", \"build\")\n    valid = []\n    for package in sorted(interesting_packages):\n        with contextlib.suppress(ModuleNotFoundError):\n            valid.append(f\"{package}=={importlib.metadata.version(package)}\")\n    reqs = \" \".join(valid)\n\n    cpp_info = [\n        \"C++ Info:\",\n        f\"{pybind11_tests.compiler_info}\",\n        f\"{pybind11_tests.cpp_std}\",\n        f\"{pybind11_tests.PYBIND11_INTERNALS_ID}\",\n        f\"PYBIND11_SIMPLE_GIL_MANAGEMENT={pybind11_tests.PYBIND11_SIMPLE_GIL_MANAGEMENT}\",\n    ]\n    if \"__graalpython__\" in sys.modules:\n        cpp_info.append(\n            f\"GraalPy version: {sys.modules['__graalpython__'].get_graalvm_version()}\"\n        )\n    lines = [\n        f\"installed packages of interest: {reqs}\",\n        \" \".join(cpp_info),\n    ]\n    if sysconfig.get_config_var(\"Py_GIL_DISABLED\"):\n        lines.append(\"free-threaded Python build\")\n\n    return lines\n\n\n@pytest.fixture\ndef backport_typehints() -> Callable[[SanitizedString], SanitizedString]:\n    d = {}\n    if sys.version_info < (3, 13):\n        d[\"typing_extensions.TypeIs\"] = \"typing.TypeIs\"\n        d[\"typing_extensions.CapsuleType\"] = \"types.CapsuleType\"\n    if sys.version_info < (3, 12):\n        d[\"typing_extensions.Buffer\"] = \"collections.abc.Buffer\"\n    if sys.version_info < (3, 11):\n        d[\"typing_extensions.Never\"] = \"typing.Never\"\n    if sys.version_info < (3, 10):\n        d[\"typing_extensions.TypeGuard\"] = \"typing.TypeGuard\"\n\n    def backport(sanitized_string: SanitizedString) -> SanitizedString:\n        for old, new in d.items():\n            sanitized_string.string = sanitized_string.string.replace(old, new)\n\n        return sanitized_string\n\n    return backport\n"
  },
  {
    "path": "tests/constructor_stats.h",
    "content": "#pragma once\n/*\n    tests/constructor_stats.h -- framework for printing and tracking object\n    instance lifetimes in example/test code.\n\n    Copyright (c) 2016 Jason Rhinelander <jason@imaginary.ca>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n\nThis header provides a few useful tools for writing examples or tests that want to check and/or\ndisplay object instance lifetimes.  It requires that you include this header and add the following\nfunction calls to constructors:\n\n    class MyClass {\n        MyClass() { ...; print_default_created(this); }\n        ~MyClass() { ...; print_destroyed(this); }\n        MyClass(const MyClass &c) { ...; print_copy_created(this); }\n        MyClass(MyClass &&c) { ...; print_move_created(this); }\n        MyClass(int a, int b) { ...; print_created(this, a, b); }\n        MyClass &operator=(const MyClass &c) { ...; print_copy_assigned(this); }\n        MyClass &operator=(MyClass &&c) { ...; print_move_assigned(this); }\n\n        ...\n    }\n\nYou can find various examples of these in several of the existing testing .cpp files.  (Of course\nyou don't need to add any of the above constructors/operators that you don't actually have, except\nfor the destructor).\n\nEach of these will print an appropriate message such as:\n\n    ### MyClass @ 0x2801910 created via default constructor\n    ### MyClass @ 0x27fa780 created 100 200\n    ### MyClass @ 0x2801910 destroyed\n    ### MyClass @ 0x27fa780 destroyed\n\nYou can also include extra arguments (such as the 100, 200 in the output above, coming from the\nvalue constructor) for all of the above methods which will be included in the output.\n\nFor testing, each of these also keeps track the created instances and allows you to check how many\nof the various constructors have been invoked from the Python side via code such as:\n\n    from pybind11_tests import ConstructorStats\n    cstats = ConstructorStats.get(MyClass)\n    print(cstats.alive())\n    print(cstats.default_constructions)\n\nNote that `.alive()` should usually be the first thing you call as it invokes Python's garbage\ncollector to actually destroy objects that aren't yet referenced.\n\nFor everything except copy and move constructors and destructors, any extra values given to the\nprint_...() function is stored in a class-specific values list which you can retrieve and inspect\nfrom the ConstructorStats instance `.values()` method.\n\nIn some cases, when you need to track instances of a C++ class not registered with pybind11, you\nneed to add a function returning the ConstructorStats for the C++ class; this can be done with:\n\n    m.def(\"get_special_cstats\", &ConstructorStats::get<SpecialClass>,\npy::return_value_policy::reference)\n\nFinally, you can suppress the output messages, but keep the constructor tracking (for\ninspection/testing in python) by using the functions with `print_` replaced with `track_` (e.g.\n`track_copy_created(this)`).\n\n*/\n\n#include \"pybind11_tests.h\"\n\n#include <list>\n#include <sstream>\n#include <typeindex>\n#include <unordered_map>\n\nclass ConstructorStats {\nprotected:\n    std::unordered_map<void *, int> _instances; // Need a map rather than set because members can\n                                                // shared address with parents\n    std::list<std::string> _values;             // Used to track values\n                                                // (e.g. of value constructors)\npublic:\n    int default_constructions = 0;\n    int copy_constructions = 0;\n    int move_constructions = 0;\n    int copy_assignments = 0;\n    int move_assignments = 0;\n\n    void copy_created(void *inst) {\n        created(inst);\n        copy_constructions++;\n    }\n\n    void move_created(void *inst) {\n        created(inst);\n        move_constructions++;\n    }\n\n    void default_created(void *inst) {\n        created(inst);\n        default_constructions++;\n    }\n\n    void created(void *inst) { ++_instances[inst]; }\n\n    void destroyed(void *inst) {\n        if (--_instances[inst] < 0) {\n            throw std::runtime_error(\"cstats.destroyed() called with unknown \"\n                                     \"instance; potential double-destruction \"\n                                     \"or a missing cstats.created()\");\n        }\n    }\n\n    static void gc() {\n        // Force garbage collection to ensure any pending destructors are invoked:\n#if defined(PYPY_VERSION)\n        PyObject *globals = PyEval_GetGlobals();\n        PyObject *result = PyRun_String(\"import gc\\n\"\n                                        \"for i in range(2):\\n\"\n                                        \"    gc.collect()\\n\",\n                                        Py_file_input,\n                                        globals,\n                                        globals);\n        if (result == nullptr)\n            throw py::error_already_set();\n        Py_DECREF(result);\n#else\n        py::module_::import(\"gc\").attr(\"collect\")();\n#endif\n    }\n\n    int alive() {\n        gc();\n        int total = 0;\n        for (const auto &p : _instances) {\n            if (p.second > 0) {\n                total += p.second;\n            }\n        }\n        return total;\n    }\n\n    void value() {} // Recursion terminator\n    // Takes one or more values, converts them to strings, then stores them.\n    template <typename T, typename... Tmore>\n    void value(const T &v, Tmore &&...args) {\n        std::ostringstream oss;\n        oss << v;\n        _values.push_back(oss.str());\n        value(std::forward<Tmore>(args)...);\n    }\n\n    // Move out stored values\n    py::list values() {\n        py::list l;\n        for (const auto &v : _values) {\n            l.append(py::cast(v));\n        }\n        _values.clear();\n        return l;\n    }\n\n    // Gets constructor stats from a C++ type index\n    static ConstructorStats &get(std::type_index type) {\n        static std::unordered_map<std::type_index, ConstructorStats> all_cstats;\n        return all_cstats[type];\n    }\n\n    // Gets constructor stats from a C++ type\n    template <typename T>\n    static ConstructorStats &get() {\n#if defined(PYPY_VERSION)\n        gc();\n#endif\n        return get(typeid(T));\n    }\n\n    // Gets constructor stats from a Python class\n    static ConstructorStats &get(py::object class_) {\n        auto &internals = py::detail::get_internals();\n        const std::type_index *t1 = nullptr, *t2 = nullptr;\n        try {\n            auto *type_info\n                = internals.registered_types_py.at((PyTypeObject *) class_.ptr()).at(0);\n            for (auto &p : internals.registered_types_cpp) {\n                if (p.second == type_info) {\n                    if (t1) {\n                        t2 = &p.first;\n                        break;\n                    }\n                    t1 = &p.first;\n                }\n            }\n        } catch (const std::out_of_range &) { // NOLINT(bugprone-empty-catch)\n        }\n        if (!t1) {\n            throw std::runtime_error(\"Unknown class passed to ConstructorStats::get()\");\n        }\n        auto &cs1 = get(*t1);\n        // If we have both a t1 and t2 match, one is probably the trampoline class; return\n        // whichever has more constructions (typically one or the other will be 0)\n        if (t2) {\n            auto &cs2 = get(*t2);\n            int cs1_total = cs1.default_constructions + cs1.copy_constructions\n                            + cs1.move_constructions + (int) cs1._values.size();\n            int cs2_total = cs2.default_constructions + cs2.copy_constructions\n                            + cs2.move_constructions + (int) cs2._values.size();\n            if (cs2_total > cs1_total) {\n                return cs2;\n            }\n        }\n        return cs1;\n    }\n};\n\n// To track construction/destruction, you need to call these methods from the various\n// constructors/operators.  The ones that take extra values record the given values in the\n// constructor stats values for later inspection.\ntemplate <class T>\nvoid track_copy_created(T *inst) {\n    ConstructorStats::get<T>().copy_created(inst);\n}\ntemplate <class T>\nvoid track_move_created(T *inst) {\n    ConstructorStats::get<T>().move_created(inst);\n}\ntemplate <class T, typename... Values>\nvoid track_copy_assigned(T *, Values &&...values) {\n    auto &cst = ConstructorStats::get<T>();\n    cst.copy_assignments++;\n    cst.value(std::forward<Values>(values)...);\n}\ntemplate <class T, typename... Values>\nvoid track_move_assigned(T *, Values &&...values) {\n    auto &cst = ConstructorStats::get<T>();\n    cst.move_assignments++;\n    cst.value(std::forward<Values>(values)...);\n}\ntemplate <class T, typename... Values>\nvoid track_default_created(T *inst, Values &&...values) {\n    auto &cst = ConstructorStats::get<T>();\n    cst.default_created(inst);\n    cst.value(std::forward<Values>(values)...);\n}\ntemplate <class T, typename... Values>\nvoid track_created(T *inst, Values &&...values) {\n    auto &cst = ConstructorStats::get<T>();\n    cst.created(inst);\n    cst.value(std::forward<Values>(values)...);\n}\ntemplate <class T, typename... Values>\nvoid track_destroyed(T *inst) {\n    ConstructorStats::get<T>().destroyed(inst);\n}\ntemplate <class T, typename... Values>\nvoid track_values(T *, Values &&...values) {\n    ConstructorStats::get<T>().value(std::forward<Values>(values)...);\n}\n\n/// Don't cast pointers to Python, print them as strings\ninline const char *format_ptrs(const char *p) { return p; }\ntemplate <typename T>\npy::str format_ptrs(T *p) {\n    return \"{:#x}\"_s.format(reinterpret_cast<std::uintptr_t>(p));\n}\ntemplate <typename T>\nauto format_ptrs(T &&x) -> decltype(std::forward<T>(x)) {\n    return std::forward<T>(x);\n}\n\ntemplate <class T, typename... Output>\nvoid print_constr_details(T *inst, const std::string &action, Output &&...output) {\n    py::print(\"###\",\n              py::type_id<T>(),\n              \"@\",\n              format_ptrs(inst),\n              action,\n              format_ptrs(std::forward<Output>(output))...);\n}\n\n// Verbose versions of the above:\ntemplate <class T, typename... Values>\nvoid print_copy_created(T *inst,\n                        Values &&...values) { // NB: this prints, but doesn't store, given values\n    print_constr_details(inst, \"created via copy constructor\", values...);\n    track_copy_created(inst);\n}\ntemplate <class T, typename... Values>\nvoid print_move_created(T *inst,\n                        Values &&...values) { // NB: this prints, but doesn't store, given values\n    print_constr_details(inst, \"created via move constructor\", values...);\n    track_move_created(inst);\n}\ntemplate <class T, typename... Values>\nvoid print_copy_assigned(T *inst, Values &&...values) {\n    print_constr_details(inst, \"assigned via copy assignment\", values...);\n    track_copy_assigned(inst, values...);\n}\ntemplate <class T, typename... Values>\nvoid print_move_assigned(T *inst, Values &&...values) {\n    print_constr_details(inst, \"assigned via move assignment\", values...);\n    track_move_assigned(inst, values...);\n}\ntemplate <class T, typename... Values>\nvoid print_default_created(T *inst, Values &&...values) {\n    print_constr_details(inst, \"created via default constructor\", values...);\n    track_default_created(inst, values...);\n}\ntemplate <class T, typename... Values>\nvoid print_created(T *inst, Values &&...values) {\n    print_constr_details(inst, \"created\", values...);\n    track_created(inst, values...);\n}\ntemplate <class T, typename... Values>\nvoid print_destroyed(T *inst, Values &&...values) { // Prints but doesn't store given values\n    /*\n     * On GraalPy, destructors can trigger anywhere and this can cause random\n     * failures in unrelated tests.\n     */\n#if !defined(GRAALVM_PYTHON)\n    print_constr_details(inst, \"destroyed\", values...);\n    track_destroyed(inst);\n#else\n    py::detail::silence_unused_warnings(inst, values...);\n#endif\n}\ntemplate <class T, typename... Values>\nvoid print_values(T *inst, Values &&...values) {\n    print_constr_details(inst, \":\", values...);\n    track_values(inst, values...);\n}\n"
  },
  {
    "path": "tests/cross_module_gil_utils.cpp",
    "content": "/*\n    tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module\n\n    Copyright (c) 2019 Google LLC\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n#if defined(PYBIND11_INTERNALS_VERSION)\n#    undef PYBIND11_INTERNALS_VERSION\n#endif\n#define PYBIND11_INTERNALS_VERSION 21814642 // Ensure this module has its own `internals` instance.\n#include <pybind11/pybind11.h>\n\n#include <cstdint>\n#include <string>\n#include <thread>\n\n// This file mimics a DSO that makes pybind11 calls but does not define a\n// PYBIND11_MODULE. The purpose is to test that such a DSO can create a\n// py::gil_scoped_acquire when the running thread is in a GIL-released state.\n//\n// Note that we define a Python module here for convenience, but in general\n// this need not be the case. The typical scenario would be a DSO that implements\n// shared logic used internally by multiple pybind11 modules.\n\nnamespace {\n\nnamespace py = pybind11;\n\nvoid gil_acquire() { py::gil_scoped_acquire gil; }\n\nstd::string gil_multi_acquire_release(unsigned bits) {\n    if ((bits & 0x1u) != 0u) {\n        py::gil_scoped_acquire gil;\n    }\n    if ((bits & 0x2u) != 0u) {\n        py::gil_scoped_release gil;\n    }\n    if ((bits & 0x4u) != 0u) {\n        py::gil_scoped_acquire gil;\n    }\n    if ((bits & 0x8u) != 0u) {\n        py::gil_scoped_release gil;\n    }\n    return PYBIND11_INTERNALS_ID;\n}\n\nstruct CustomAutoGIL {\n    CustomAutoGIL() : gstate(PyGILState_Ensure()) {}\n    ~CustomAutoGIL() { PyGILState_Release(gstate); }\n\n    PyGILState_STATE gstate;\n};\nstruct CustomAutoNoGIL {\n    CustomAutoNoGIL() : save(PyEval_SaveThread()) {}\n    ~CustomAutoNoGIL() { PyEval_RestoreThread(save); }\n\n    PyThreadState *save;\n};\n\ntemplate <typename Acquire, typename Release>\nvoid gil_acquire_inner() {\n    Acquire acquire_outer;\n    Acquire acquire_inner;\n    Release release;\n}\n\ntemplate <typename Acquire, typename Release>\nvoid gil_acquire_nested() {\n    Acquire acquire_outer;\n    Acquire acquire_inner;\n    Release release;\n    auto thread = std::thread(&gil_acquire_inner<Acquire, Release>);\n    thread.join();\n}\n\nconstexpr char kModuleName[] = \"cross_module_gil_utils\";\n\nstruct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr};\n\n} // namespace\n\n#define ADD_FUNCTION(Name, ...)                                                                   \\\n    PyModule_AddObject(m, Name, PyLong_FromVoidPtr(reinterpret_cast<void *>(&__VA_ARGS__)));\n\nextern \"C\" PYBIND11_EXPORT PyObject *PyInit_cross_module_gil_utils() {\n\n    PyObject *m = PyModule_Create(&moduledef);\n\n    if (m != nullptr) {\n        static_assert(sizeof(&gil_acquire) == sizeof(void *),\n                      \"Function pointer must have the same size as void*\");\n#ifdef Py_GIL_DISABLED\n        PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n#endif\n        ADD_FUNCTION(\"gil_acquire_funcaddr\", gil_acquire)\n        ADD_FUNCTION(\"gil_multi_acquire_release_funcaddr\", gil_multi_acquire_release)\n        ADD_FUNCTION(\"gil_acquire_inner_custom_funcaddr\",\n                     gil_acquire_inner<CustomAutoGIL, CustomAutoNoGIL>)\n        ADD_FUNCTION(\"gil_acquire_nested_custom_funcaddr\",\n                     gil_acquire_nested<CustomAutoGIL, CustomAutoNoGIL>)\n        ADD_FUNCTION(\"gil_acquire_inner_pybind11_funcaddr\",\n                     gil_acquire_inner<py::gil_scoped_acquire, py::gil_scoped_release>)\n        ADD_FUNCTION(\"gil_acquire_nested_pybind11_funcaddr\",\n                     gil_acquire_nested<py::gil_scoped_acquire, py::gil_scoped_release>)\n    }\n\n    return m;\n}\n"
  },
  {
    "path": "tests/cross_module_interleaved_error_already_set.cpp",
    "content": "/*\n    Copyright (c) 2022 Google LLC\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/pybind11.h>\n\n// This file mimics a DSO that makes pybind11 calls but does not define a PYBIND11_MODULE,\n// so that the first call of cross_module_error_already_set() triggers the first call of\n// pybind11::detail::get_internals().\n\nnamespace {\n\nnamespace py = pybind11;\n\nvoid interleaved_error_already_set() {\n    py::set_error(PyExc_RuntimeError, \"1st error.\");\n    try {\n        throw py::error_already_set();\n    } catch (const py::error_already_set &) {\n        // The 2nd error could be conditional in a real application.\n        py::set_error(PyExc_RuntimeError, \"2nd error.\");\n    } // Here the 1st error is destroyed before the 2nd error is fetched.\n    // The error_already_set dtor triggers a pybind11::detail::get_internals()\n    // call via pybind11::gil_scoped_acquire.\n    if (PyErr_Occurred()) {\n        throw py::error_already_set();\n    }\n}\n\nconstexpr char kModuleName[] = \"cross_module_interleaved_error_already_set\";\n\nstruct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT, kModuleName, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr};\n\n} // namespace\n\nextern \"C\" PYBIND11_EXPORT PyObject *PyInit_cross_module_interleaved_error_already_set() {\n    PyObject *m = PyModule_Create(&moduledef);\n    if (m != nullptr) {\n        static_assert(sizeof(&interleaved_error_already_set) == sizeof(void *),\n                      \"Function pointer must have the same size as void *\");\n#ifdef Py_GIL_DISABLED\n        PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n#endif\n        PyModule_AddObject(\n            m,\n            \"funcaddr\",\n            PyLong_FromVoidPtr(reinterpret_cast<void *>(&interleaved_error_already_set)));\n    }\n    return m;\n}\n"
  },
  {
    "path": "tests/custom_exceptions.py",
    "content": "from __future__ import annotations\n\n\nclass PythonMyException7(Exception):\n    def __init__(self, message):\n        self.message = message\n        super().__init__(message)\n\n    def __str__(self):\n        return \"[PythonMyException7]: \" + self.message.a\n"
  },
  {
    "path": "tests/eigen_tensor_avoid_stl_array.cpp",
    "content": "/*\n    tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#ifndef EIGEN_AVOID_STL_ARRAY\n#    define EIGEN_AVOID_STL_ARRAY\n#endif\n\n#include \"test_eigen_tensor.inl\"\n\nPYBIND11_MODULE(eigen_tensor_avoid_stl_array, m, pybind11::mod_gil_not_used()) {\n    eigen_tensor_test::test_module(m);\n}\n"
  },
  {
    "path": "tests/env.py",
    "content": "from __future__ import annotations\n\nimport platform\nimport sys\nimport sysconfig\n\nimport pytest\n\nANDROID = sys.platform.startswith(\"android\")\nIOS = sys.platform.startswith(\"ios\")\nLINUX = sys.platform.startswith(\"linux\")\nMACOS = sys.platform.startswith(\"darwin\")\nWIN = sys.platform.startswith(\"win32\") or sys.platform.startswith(\"cygwin\")\nFREEBSD = sys.platform.startswith(\"freebsd\")\n\nMUSLLINUX = False\nMANYLINUX = False\nif LINUX:\n\n    def _is_musl() -> bool:\n        libc, _ = platform.libc_ver()\n        return libc == \"musl\" or (libc != \"glibc\" and libc != \"\")\n\n    MUSLLINUX = _is_musl()\n    MANYLINUX = not MUSLLINUX\n    del _is_musl\n\nCPYTHON = platform.python_implementation() == \"CPython\"\nPYPY = platform.python_implementation() == \"PyPy\"\nGRAALPY = sys.implementation.name == \"graalpy\"\n_graalpy_version = (\n    sys.modules[\"__graalpython__\"].get_graalvm_version() if GRAALPY else \"0.0.0\"\n)\nGRAALPY_VERSION = tuple(int(t) for t in _graalpy_version.split(\"-\")[0].split(\".\")[:3])\n\n# Compile-time config (what the binary was built for)\nPY_GIL_DISABLED = bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\"))\n# Runtime state (what's actually happening now)\nsys_is_gil_enabled = getattr(sys, \"_is_gil_enabled\", lambda: True)\n\nTYPES_ARE_IMMORTAL = (\n    PYPY\n    or GRAALPY\n    or (CPYTHON and PY_GIL_DISABLED and (3, 13) <= sys.version_info < (3, 14))\n)\n\n\ndef check_script_success_in_subprocess(code: str, *, rerun: int = 8) -> None:\n    \"\"\"Runs the given code in a subprocess.\"\"\"\n    import os\n    import subprocess\n    import sys\n    import textwrap\n\n    if ANDROID or IOS or sys.platform.startswith(\"emscripten\"):\n        pytest.skip(\"Requires subprocess support\")\n\n    code = textwrap.dedent(code).strip()\n    try:\n        for _ in range(rerun):  # run flakily failing test multiple times\n            subprocess.check_output(\n                [sys.executable, \"-c\", code],\n                cwd=os.getcwd(),\n                stderr=subprocess.STDOUT,\n                text=True,\n            )\n    except subprocess.CalledProcessError as ex:\n        raise RuntimeError(\n            f\"Subprocess failed with exit code {ex.returncode}.\\n\\n\"\n            f\"Code:\\n\"\n            f\"```python\\n\"\n            f\"{code}\\n\"\n            f\"```\\n\\n\"\n            f\"Output:\\n\"\n            f\"{ex.output}\"\n        ) from None\n"
  },
  {
    "path": "tests/exo_planet_c_api.cpp",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n// In production situations it is totally fine to build with\n// C++ Exception Handling enabled. However, here we want to ensure that\n// C++ Exception Handling is not required.\n#if defined(_MSC_VER) || defined(__EMSCRIPTEN__)\n// Too much trouble making the required cmake changes (see PR #5375).\n#else\n#    ifdef __cpp_exceptions\n// https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations#__cpp_exceptions\n#    error This test is meant to be built with C++ Exception Handling disabled, but __cpp_exceptions is defined.\n#    endif\n#    ifdef __EXCEPTIONS\n// https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html\n#    error This test is meant to be built with C++ Exception Handling disabled, but __EXCEPTIONS is defined.\n#    endif\n#endif\n\n// THIS MUST STAY AT THE TOP!\n#include <pybind11/conduit/pybind11_conduit_v1.h> // VERY light-weight dependency.\n\n#include \"test_cpp_conduit_traveler_types.h\"\n\n#include <Python.h>\n\nnamespace {\n\nextern \"C\" PyObject *wrapGetLuggage(PyObject * /*self*/, PyObject *traveler) {\n    const auto *cpp_traveler = pybind11_conduit_v1::get_type_pointer_ephemeral<\n        pybind11_tests::test_cpp_conduit::Traveler>(traveler);\n    if (cpp_traveler == nullptr) {\n        return nullptr;\n    }\n    return PyUnicode_FromString(cpp_traveler->luggage.c_str());\n}\n\nextern \"C\" PyObject *wrapGetPoints(PyObject * /*self*/, PyObject *premium_traveler) {\n    const auto *cpp_premium_traveler = pybind11_conduit_v1::get_type_pointer_ephemeral<\n        pybind11_tests::test_cpp_conduit::PremiumTraveler>(premium_traveler);\n    if (cpp_premium_traveler == nullptr) {\n        return nullptr;\n    }\n    return PyLong_FromLong(static_cast<long>(cpp_premium_traveler->points));\n}\n\nPyMethodDef ThisMethodDef[] = {{\"GetLuggage\", wrapGetLuggage, METH_O, nullptr},\n                               {\"GetPoints\", wrapGetPoints, METH_O, nullptr},\n                               {nullptr, nullptr, 0, nullptr}};\n\nstruct PyModuleDef ThisModuleDef = {\n    PyModuleDef_HEAD_INIT, // m_base\n    \"exo_planet_c_api\",    // m_name\n    nullptr,               // m_doc\n    -1,                    // m_size\n    ThisMethodDef,         // m_methods\n    nullptr,               // m_slots\n    nullptr,               // m_traverse\n    nullptr,               // m_clear\n    nullptr                // m_free\n};\n\n} // namespace\n\n#if defined(WIN32) || defined(_WIN32)\n#    define EXO_PLANET_C_API_EXPORT __declspec(dllexport)\n#else\n#    define EXO_PLANET_C_API_EXPORT __attribute__((visibility(\"default\")))\n#endif\n\nextern \"C\" EXO_PLANET_C_API_EXPORT PyObject *PyInit_exo_planet_c_api() {\n    PyObject *m = PyModule_Create(&ThisModuleDef);\n    if (m == nullptr) {\n        return nullptr;\n    }\n    return m;\n}\n"
  },
  {
    "path": "tests/exo_planet_pybind11.cpp",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#if defined(PYBIND11_INTERNALS_VERSION)\n#    undef PYBIND11_INTERNALS_VERSION\n#endif\n#define PYBIND11_INTERNALS_VERSION 900000001\n\n#include \"test_cpp_conduit_traveler_bindings.h\"\n\nnamespace pybind11_tests {\nnamespace test_cpp_conduit {\n\nPYBIND11_MODULE(exo_planet_pybind11, m) {\n    wrap_traveler(m);\n    m.def(\"wrap_very_lonely_traveler\", [m]() { wrap_very_lonely_traveler(m); });\n}\n\n} // namespace test_cpp_conduit\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/extra_python_package/pytest.ini",
    "content": ""
  },
  {
    "path": "tests/extra_python_package/test_files.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tarfile\nimport zipfile\nfrom pathlib import Path\nfrom typing import Generator\n\n# These tests must be run explicitly\n\nDIR = Path(__file__).parent.resolve()\nMAIN_DIR = DIR.parent.parent\n\nFILENAME_VERSION = re.compile(r\"[-_]((\\d+\\.\\d+\\.\\d+)(?:[a-z]+\\d*)?)(?:-|\\.tar\\.gz$)\")\n\n# Newer pytest has global path setting, but keeping old pytest for now\nsys.path.append(str(MAIN_DIR / \"tools\"))\n\nfrom make_global import get_global  # noqa: E402\n\nHAS_UV = shutil.which(\"uv\") is not None\nUV_ARGS = [\"--installer=uv\"] if HAS_UV else []\n\nPKGCONFIG = \"\"\"\\\nprefix=${{pcfiledir}}/../../\nincludedir=${{prefix}}/include\n\nName: pybind11\nDescription: Seamless operability between C++11 and Python\nVersion: {VERSION}\nCflags: -I${{includedir}}\n\"\"\"\n\n\nmain_headers = {\n    \"include/pybind11/attr.h\",\n    \"include/pybind11/buffer_info.h\",\n    \"include/pybind11/cast.h\",\n    \"include/pybind11/chrono.h\",\n    \"include/pybind11/common.h\",\n    \"include/pybind11/complex.h\",\n    \"include/pybind11/critical_section.h\",\n    \"include/pybind11/eigen.h\",\n    \"include/pybind11/embed.h\",\n    \"include/pybind11/eval.h\",\n    \"include/pybind11/functional.h\",\n    \"include/pybind11/gil.h\",\n    \"include/pybind11/gil_safe_call_once.h\",\n    \"include/pybind11/gil_simple.h\",\n    \"include/pybind11/iostream.h\",\n    \"include/pybind11/native_enum.h\",\n    \"include/pybind11/numpy.h\",\n    \"include/pybind11/operators.h\",\n    \"include/pybind11/options.h\",\n    \"include/pybind11/pybind11.h\",\n    \"include/pybind11/pytypes.h\",\n    \"include/pybind11/subinterpreter.h\",\n    \"include/pybind11/stl.h\",\n    \"include/pybind11/stl_bind.h\",\n    \"include/pybind11/trampoline_self_life_support.h\",\n    \"include/pybind11/type_caster_pyobject_ptr.h\",\n    \"include/pybind11/typing.h\",\n    \"include/pybind11/warnings.h\",\n}\n\nconduit_headers = {\n    \"include/pybind11/conduit/README.txt\",\n    \"include/pybind11/conduit/pybind11_conduit_v1.h\",\n    \"include/pybind11/conduit/pybind11_platform_abi_id.h\",\n    \"include/pybind11/conduit/wrap_include_python_h.h\",\n}\n\ndetail_headers = {\n    \"include/pybind11/detail/argument_vector.h\",\n    \"include/pybind11/detail/class.h\",\n    \"include/pybind11/detail/common.h\",\n    \"include/pybind11/detail/cpp_conduit.h\",\n    \"include/pybind11/detail/descr.h\",\n    \"include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h\",\n    \"include/pybind11/detail/function_record_pyobject.h\",\n    \"include/pybind11/detail/function_ref.h\",\n    \"include/pybind11/detail/holder_caster_foreign_helpers.h\",\n    \"include/pybind11/detail/init.h\",\n    \"include/pybind11/detail/internals.h\",\n    \"include/pybind11/detail/native_enum_data.h\",\n    \"include/pybind11/detail/pybind11_namespace_macros.h\",\n    \"include/pybind11/detail/struct_smart_holder.h\",\n    \"include/pybind11/detail/type_caster_base.h\",\n    \"include/pybind11/detail/typeid.h\",\n    \"include/pybind11/detail/using_smart_holder.h\",\n    \"include/pybind11/detail/value_and_holder.h\",\n    \"include/pybind11/detail/exception_translation.h\",\n}\n\neigen_headers = {\n    \"include/pybind11/eigen/common.h\",\n    \"include/pybind11/eigen/matrix.h\",\n    \"include/pybind11/eigen/tensor.h\",\n}\n\nstl_headers = {\n    \"include/pybind11/stl/filesystem.h\",\n}\n\ncmake_files = {\n    \"share/cmake/pybind11/FindPythonLibsNew.cmake\",\n    \"share/cmake/pybind11/pybind11Common.cmake\",\n    \"share/cmake/pybind11/pybind11Config.cmake\",\n    \"share/cmake/pybind11/pybind11ConfigVersion.cmake\",\n    \"share/cmake/pybind11/pybind11GuessPythonExtSuffix.cmake\",\n    \"share/cmake/pybind11/pybind11NewTools.cmake\",\n    \"share/cmake/pybind11/pybind11Targets.cmake\",\n    \"share/cmake/pybind11/pybind11Tools.cmake\",\n}\n\npkgconfig_files = {\n    \"share/pkgconfig/pybind11.pc\",\n}\n\npy_files = {\n    \"__init__.py\",\n    \"__main__.py\",\n    \"_version.py\",\n    \"commands.py\",\n    \"py.typed\",\n    \"setup_helpers.py\",\n    \"share/__init__.py\",\n    \"share/pkgconfig/__init__.py\",\n}\n\nheaders = main_headers | conduit_headers | detail_headers | eigen_headers | stl_headers\ngenerated_files = cmake_files | pkgconfig_files\nall_files = headers | generated_files | py_files\n\nsdist_files = {\n    \"pyproject.toml\",\n    \"LICENSE\",\n    \"README.rst\",\n    \"PKG-INFO\",\n    \"SECURITY.md\",\n}\n\n\n@contextlib.contextmanager\ndef preserve_file(filename: Path) -> Generator[str, None, None]:\n    old_stat = filename.stat()\n    old_file = filename.read_text(encoding=\"utf-8\")\n    try:\n        yield old_file\n    finally:\n        filename.write_text(old_file, encoding=\"utf-8\")\n        os.utime(filename, (old_stat.st_atime, old_stat.st_mtime))\n\n\n@contextlib.contextmanager\ndef build_global() -> Generator[None, None, None]:\n    \"\"\"\n    Build global SDist and wheel.\n    \"\"\"\n\n    pyproject = MAIN_DIR / \"pyproject.toml\"\n    with preserve_file(pyproject):\n        newer_txt = get_global()\n        pyproject.write_text(newer_txt, encoding=\"utf-8\")\n        yield\n\n\ndef read_tz_file(tar: tarfile.TarFile, name: str) -> bytes:\n    start = tar.getnames()[0].split(\"/\")[0] + \"/\"\n    inner_file = tar.extractfile(tar.getmember(f\"{start}{name}\"))\n    assert inner_file\n    with contextlib.closing(inner_file) as f:\n        return f.read()\n\n\ndef normalize_line_endings(value: bytes) -> bytes:\n    return value.replace(os.linesep.encode(\"utf-8\"), b\"\\n\")\n\n\ndef test_build_sdist(monkeypatch, tmpdir):\n    monkeypatch.chdir(MAIN_DIR)\n\n    subprocess.run(\n        [sys.executable, \"-m\", \"build\", \"--sdist\", f\"--outdir={tmpdir}\", *UV_ARGS],\n        check=True,\n    )\n\n    (sdist,) = tmpdir.visit(\"*.tar.gz\")\n    version = FILENAME_VERSION.search(sdist.basename).group(1)\n\n    with tarfile.open(str(sdist), \"r:gz\") as tar:\n        simpler = {n.split(\"/\", 1)[-1] for n in tar.getnames()[1:]}\n        (pkg_info_path,) = (n for n in simpler if n.endswith(\"PKG-INFO\"))\n\n        pyproject_toml = read_tz_file(tar, \"pyproject.toml\")\n        pkg_info = read_tz_file(tar, pkg_info_path).decode(\"utf-8\")\n\n    files = headers | sdist_files\n    assert files <= simpler\n\n    assert b'name = \"pybind11\"' in pyproject_toml\n    assert f\"Version: {version}\" in pkg_info\n    assert \"License-Expression: BSD-3-Clause\" in pkg_info\n    assert \"License-File: LICENSE\" in pkg_info\n    assert \"Provides-Extra: global\" in pkg_info\n    assert f'Requires-Dist: pybind11-global=={version}; extra == \"global\"' in pkg_info\n\n\ndef test_build_global_dist(monkeypatch, tmpdir):\n    monkeypatch.chdir(MAIN_DIR)\n    with build_global():\n        subprocess.run(\n            [\n                sys.executable,\n                \"-m\",\n                \"build\",\n                \"--sdist\",\n                \"--outdir\",\n                str(tmpdir),\n                *UV_ARGS,\n            ],\n            check=True,\n        )\n\n    (sdist,) = tmpdir.visit(\"*.tar.gz\")\n    version = FILENAME_VERSION.search(sdist.basename).group(2)\n\n    with tarfile.open(str(sdist), \"r:gz\") as tar:\n        simpler = {n.split(\"/\", 1)[-1] for n in tar.getnames()[1:]}\n        (pkg_info_path,) = (n for n in simpler if n.endswith(\"PKG-INFO\"))\n\n        pyproject_toml = read_tz_file(tar, \"pyproject.toml\")\n        pkg_info = read_tz_file(tar, pkg_info_path).decode(\"utf-8\")\n\n    files = headers | sdist_files\n    assert files <= simpler\n\n    assert b'name = \"pybind11-global\"' in pyproject_toml\n    assert f\"Version: {version}\" in pkg_info\n    assert \"License-Expression: BSD-3-Clause\" in pkg_info\n    assert \"License-File: LICENSE\" in pkg_info\n    assert \"Provides-Extra: global\" not in pkg_info\n    assert 'Requires-Dist: pybind11-global; extra == \"global\"' not in pkg_info\n\n\ndef tests_build_wheel(monkeypatch, tmpdir):\n    monkeypatch.chdir(MAIN_DIR)\n\n    subprocess.run(\n        [sys.executable, \"-m\", \"build\", \"--wheel\", \"--outdir\", str(tmpdir), *UV_ARGS],\n        check=True,\n    )\n\n    (wheel,) = tmpdir.visit(\"*.whl\")\n    version, simple_version = FILENAME_VERSION.search(wheel.basename).groups()\n\n    files = {f\"pybind11/{n}\" for n in all_files}\n    files |= {\n        \"dist-info/licenses/LICENSE\",\n        \"dist-info/METADATA\",\n        \"dist-info/RECORD\",\n        \"dist-info/WHEEL\",\n        \"dist-info/entry_points.txt\",\n    }\n\n    with zipfile.ZipFile(str(wheel)) as z:\n        names = z.namelist()\n        share = zipfile.Path(z, \"pybind11/share\")\n        pkgconfig = (share / \"pkgconfig/pybind11.pc\").read_text(encoding=\"utf-8\")\n        cmakeconfig = (share / \"cmake/pybind11/pybind11Config.cmake\").read_text(\n            encoding=\"utf-8\"\n        )\n        (pkg_info_path,) = (n for n in names if n.endswith(\"METADATA\"))\n        pkg_info = zipfile.Path(z, pkg_info_path).read_text(encoding=\"utf-8\")\n\n    trimmed = {n for n in names if \"dist-info\" not in n}\n    trimmed |= {f\"dist-info/{n.split('/', 1)[-1]}\" for n in names if \"dist-info\" in n}\n\n    assert files == trimmed\n\n    assert 'set(pybind11_INCLUDE_DIR \"${PACKAGE_PREFIX_DIR}/include\")' in cmakeconfig\n\n    pkgconfig_expected = PKGCONFIG.format(VERSION=simple_version)\n    assert pkgconfig_expected == pkgconfig\n\n    assert f\"Version: {version}\" in pkg_info\n    assert \"License-Expression: BSD-3-Clause\" in pkg_info\n    assert \"License-File: LICENSE\" in pkg_info\n    assert \"Provides-Extra: global\" in pkg_info\n    assert f'Requires-Dist: pybind11-global=={version}; extra == \"global\"' in pkg_info\n\n\ndef tests_build_global_wheel(monkeypatch, tmpdir):\n    monkeypatch.chdir(MAIN_DIR)\n    with build_global():\n        subprocess.run(\n            [\n                sys.executable,\n                \"-m\",\n                \"build\",\n                \"--wheel\",\n                \"--outdir\",\n                str(tmpdir),\n                *UV_ARGS,\n            ],\n            check=True,\n        )\n\n    (wheel,) = tmpdir.visit(\"*.whl\")\n    version, simple_version = FILENAME_VERSION.search(wheel.basename).groups()\n\n    files = {f\"data/data/{n}\" for n in headers}\n    files |= {f\"data/headers/{n[8:]}\" for n in headers}\n    files |= {f\"data/data/{n}\" for n in generated_files}\n    files |= {\n        \"dist-info/licenses/LICENSE\",\n        \"dist-info/METADATA\",\n        \"dist-info/WHEEL\",\n        \"dist-info/RECORD\",\n    }\n\n    with zipfile.ZipFile(str(wheel)) as z:\n        names = z.namelist()\n        beginning = names[0].split(\"/\", 1)[0].rsplit(\".\", 1)[0]\n\n        share = zipfile.Path(z, f\"{beginning}.data/data/share\")\n        pkgconfig = (share / \"pkgconfig/pybind11.pc\").read_text(encoding=\"utf-8\")\n        cmakeconfig = (share / \"cmake/pybind11/pybind11Config.cmake\").read_text(\n            encoding=\"utf-8\"\n        )\n\n        (pkg_info_path,) = (n for n in names if n.endswith(\"METADATA\"))\n        pkg_info = zipfile.Path(z, pkg_info_path).read_text(encoding=\"utf-8\")\n\n    assert f\"Version: {version}\" in pkg_info\n    assert \"License-Expression: BSD-3-Clause\" in pkg_info\n    assert \"License-File: LICENSE\" in pkg_info\n    assert \"Provides-Extra: global\" not in pkg_info\n    assert 'Requires-Dist: pybind11-global; extra == \"global\"' not in pkg_info\n\n    trimmed = {n[len(beginning) + 1 :] for n in names}\n\n    assert files == trimmed\n\n    assert 'set(pybind11_INCLUDE_DIR \"${PACKAGE_PREFIX_DIR}/include\")' in cmakeconfig\n\n    pkgconfig_expected = PKGCONFIG.format(VERSION=simple_version)\n    assert pkgconfig_expected == pkgconfig\n\n\ndef test_version_matches():\n    header = MAIN_DIR / \"include/pybind11/detail/common.h\"\n    text = header.read_text()\n\n    # Extract the relevant macro values\n    regex_prefix = r\"#\\s*define\\s+PYBIND11_VERSION_\"\n    micro = re.search(rf\"{regex_prefix}MICRO\\s+(\\d+)\\b\", text).group(1)\n    release_level = re.search(rf\"{regex_prefix}RELEASE_LEVEL\\s+(\\w+)\\b\", text).group(1)\n    release_serial = re.search(\n        rf\"{regex_prefix}RELEASE_SERIAL\\s+(\\d+)\\b\",\n        text,\n    ).group(1)\n    patch = re.search(rf\"{regex_prefix}PATCH\\s+([\\w.-]+)\\b\", text).group(1)\n\n    # Map release level macro to string\n    level_map = {\n        \"PY_RELEASE_LEVEL_ALPHA\": \"a\",\n        \"PY_RELEASE_LEVEL_BETA\": \"b\",\n        \"PY_RELEASE_LEVEL_GAMMA\": \"rc\",\n        \"PY_RELEASE_LEVEL_FINAL\": \"\",\n    }\n    level_str = level_map[release_level]\n\n    if release_level == \"PY_RELEASE_LEVEL_FINAL\":\n        assert level_str == \"\"\n        assert release_serial == \"0\"\n        expected_patch = micro\n    else:\n        expected_patch = f\"{micro}{level_str}{release_serial}\"\n\n    assert patch == expected_patch\n"
  },
  {
    "path": "tests/extra_setuptools/pytest.ini",
    "content": ""
  },
  {
    "path": "tests/extra_setuptools/test_setuphelper.py",
    "content": "from __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nfrom textwrap import dedent\n\nimport pytest\n\nDIR = os.path.abspath(os.path.dirname(__file__))\nMAIN_DIR = os.path.dirname(os.path.dirname(DIR))\nWIN = sys.platform.startswith(\"win32\") or sys.platform.startswith(\"cygwin\")\n\n\n@pytest.mark.parametrize(\"parallel\", [False, True])\n@pytest.mark.parametrize(\"std\", [11, 0])\ndef test_simple_setup_py(monkeypatch, tmpdir, parallel, std):\n    monkeypatch.chdir(tmpdir)\n    monkeypatch.syspath_prepend(MAIN_DIR)\n\n    (tmpdir / \"setup.py\").write_text(\n        dedent(\n            f\"\"\"\\\n            import sys\n            sys.path.append({MAIN_DIR!r})\n\n            from setuptools import setup, Extension\n            from pybind11.setup_helpers import build_ext, Pybind11Extension\n\n            std = {std}\n\n            ext_modules = [\n                Pybind11Extension(\n                    \"simple_setup\",\n                    sorted([\"main.cpp\"]),\n                    cxx_std=std,\n                ),\n            ]\n\n            cmdclass = dict()\n            if std == 0:\n                cmdclass[\"build_ext\"] = build_ext\n\n\n            parallel = {parallel}\n            if parallel:\n                from pybind11.setup_helpers import ParallelCompile\n                ParallelCompile().install()\n\n            setup(\n                name=\"simple_setup_package\",\n                cmdclass=cmdclass,\n                ext_modules=ext_modules,\n            )\n            \"\"\"\n        ),\n        encoding=\"ascii\",\n    )\n\n    (tmpdir / \"main.cpp\").write_text(\n        dedent(\n            \"\"\"\\\n            #include <pybind11/pybind11.h>\n\n            int f(int x) {\n                return x * 3;\n            }\n            PYBIND11_MODULE(simple_setup, m) {\n                m.def(\"f\", &f);\n            }\n            \"\"\"\n        ),\n        encoding=\"ascii\",\n    )\n\n    out = subprocess.check_output(\n        [sys.executable, \"setup.py\", \"build_ext\", \"--inplace\"],\n    )\n    if not WIN:\n        assert b\"-g0\" in out\n    out = subprocess.check_output(\n        [sys.executable, \"setup.py\", \"build_ext\", \"--inplace\", \"--force\"],\n        env=dict(os.environ, CFLAGS=\"-g\"),\n    )\n    if not WIN:\n        assert b\"-g0\" not in out\n\n    # Debug helper printout, normally hidden\n    print(out)\n    for item in tmpdir.listdir():\n        print(item.basename)\n\n    assert (\n        len([f for f in tmpdir.listdir() if f.basename.startswith(\"simple_setup\")]) == 1\n    )\n    assert len(list(tmpdir.listdir())) == 4  # two files + output + build_dir\n\n    (tmpdir / \"test.py\").write_text(\n        dedent(\n            \"\"\"\\\n            import simple_setup\n            assert simple_setup.f(3) == 9\n            \"\"\"\n        ),\n        encoding=\"ascii\",\n    )\n\n    subprocess.check_call(\n        [sys.executable, \"test.py\"], stdout=sys.stdout, stderr=sys.stderr\n    )\n\n\ndef test_intree_extensions(monkeypatch, tmpdir):\n    monkeypatch.syspath_prepend(MAIN_DIR)\n\n    from pybind11.setup_helpers import intree_extensions\n\n    monkeypatch.chdir(tmpdir)\n    root = tmpdir\n    root.ensure_dir()\n    subdir = root / \"dir\"\n    subdir.ensure_dir()\n    src = subdir / \"ext.cpp\"\n    src.ensure()\n    relpath = src.relto(tmpdir)\n    (ext,) = intree_extensions([relpath])\n    assert ext.name == \"ext\"\n    subdir.ensure(\"__init__.py\")\n    (ext,) = intree_extensions([relpath])\n    assert ext.name == \"dir.ext\"\n\n\ndef test_intree_extensions_package_dir(monkeypatch, tmpdir):\n    monkeypatch.syspath_prepend(MAIN_DIR)\n\n    from pybind11.setup_helpers import intree_extensions\n\n    monkeypatch.chdir(tmpdir)\n    root = tmpdir / \"src\"\n    root.ensure_dir()\n    subdir = root / \"dir\"\n    subdir.ensure_dir()\n    src = subdir / \"ext.cpp\"\n    src.ensure()\n    (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={\"\": \"src\"})\n    assert ext.name == \"dir.ext\"\n    (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={\"foo\": \"src\"})\n    assert ext.name == \"foo.dir.ext\"\n    subdir.ensure(\"__init__.py\")\n    (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={\"\": \"src\"})\n    assert ext.name == \"dir.ext\"\n    (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={\"foo\": \"src\"})\n    assert ext.name == \"foo.dir.ext\"\n"
  },
  {
    "path": "tests/home_planet_very_lonely_traveler.cpp",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#include \"test_cpp_conduit_traveler_bindings.h\"\n\nnamespace pybind11_tests {\nnamespace test_cpp_conduit {\n\nPYBIND11_MODULE(home_planet_very_lonely_traveler, m) {\n    m.def(\"wrap_very_lonely_traveler\", [m]() { wrap_very_lonely_traveler(m); });\n}\n\n} // namespace test_cpp_conduit\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/local_bindings.h",
    "content": "#pragma once\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\n/// Simple class used to test py::local:\ntemplate <int>\nclass LocalBase {\npublic:\n    explicit LocalBase(int i) : i(i) {}\n    int i = -1;\n};\n\n/// Registered with py::module_local in both main and secondary modules:\nusing LocalType = LocalBase<0>;\n/// Registered without py::module_local in both modules:\nusing NonLocalType = LocalBase<1>;\n/// A second non-local type (for stl_bind tests):\nusing NonLocal2 = LocalBase<2>;\n/// Tests within-module, different-compilation-unit local definition conflict:\nusing LocalExternal = LocalBase<3>;\n/// Mixed: registered local first, then global\nusing MixedLocalGlobal = LocalBase<4>;\n/// Mixed: global first, then local\nusing MixedGlobalLocal = LocalBase<5>;\n\n/// Registered with py::module_local only in the secondary module:\nusing ExternalType1 = LocalBase<6>; // default holder\nusing ExternalType2 = LocalBase<7>; // held by std::shared_ptr\nusing ExternalType3 = LocalBase<8>; // held by smart_holder\n\nusing LocalVec = std::vector<LocalType>;\nusing LocalVec2 = std::vector<NonLocal2>;\nusing LocalMap = std::unordered_map<std::string, LocalType>;\nusing NonLocalVec = std::vector<NonLocalType>;\nusing NonLocalVec2 = std::vector<NonLocal2>;\nusing NonLocalMap = std::unordered_map<std::string, NonLocalType>;\nusing NonLocalMap2 = std::unordered_map<std::string, uint8_t>;\n\n// Exception that will be caught via the module local translator.\nclass LocalException : public std::exception {\npublic:\n    explicit LocalException(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\n// Exception that will be registered with register_local_exception_translator\nclass LocalSimpleException : public std::exception {\npublic:\n    explicit LocalSimpleException(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\nPYBIND11_MAKE_OPAQUE(LocalVec)\nPYBIND11_MAKE_OPAQUE(LocalVec2)\nPYBIND11_MAKE_OPAQUE(LocalMap)\nPYBIND11_MAKE_OPAQUE(NonLocalVec)\n// PYBIND11_MAKE_OPAQUE(NonLocalVec2) // same type as LocalVec2\nPYBIND11_MAKE_OPAQUE(NonLocalMap)\nPYBIND11_MAKE_OPAQUE(NonLocalMap2)\n\n// Simple bindings (used with the above):\ntemplate <typename T, int Adjust = 0, typename Holder = std::unique_ptr<T>, typename... Args>\npy::class_<T, Holder> bind_local(Args &&...args) {\n    return py::class_<T, Holder>(std::forward<Args>(args)...)\n        .def(py::init<int>())\n        .def(\"get\", [](T &i) { return i.i + Adjust; });\n}\n\n// Simulate a foreign library base class (to match the example in the docs):\nnamespace pets {\nclass Pet {\npublic:\n    explicit Pet(std::string name) : name_(std::move(name)) {}\n    std::string name_;\n    const std::string &name() const { return name_; }\n};\n} // namespace pets\n\nstruct MixGL {\n    int i;\n    explicit MixGL(int i) : i{i} {}\n};\nstruct MixGL2 {\n    int i;\n    explicit MixGL2(int i) : i{i} {}\n};\n"
  },
  {
    "path": "tests/mod_per_interpreter_gil.cpp",
    "content": "#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\n/* Simple test module/test class to check that the referenced internals data of external pybind11\n * modules are different across subinterpreters\n */\n\nPYBIND11_MODULE(mod_per_interpreter_gil,\n                m,\n                py::mod_gil_not_used(),\n                py::multiple_interpreters::per_interpreter_gil()) {\n    m.def(\"internals_at\",\n          []() { return reinterpret_cast<uintptr_t>(&py::detail::get_internals()); });\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = true;\n#else\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = false;\n#endif\n}\n"
  },
  {
    "path": "tests/mod_per_interpreter_gil_with_singleton.cpp",
    "content": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <vector>\n\nnamespace py = pybind11;\n\n#ifdef PYBIND11_HAS_NATIVE_ENUM\n#    include <pybind11/native_enum.h>\n#endif\n\nnamespace pybind11_tests {\nnamespace mod_per_interpreter_gil_with_singleton {\n// A singleton class that holds references to certain Python objects\n// This singleton is per-interpreter using gil_safe_call_once_and_store\nclass MySingleton {\npublic:\n    MySingleton() = default;\n    ~MySingleton() = default;\n    MySingleton(const MySingleton &) = delete;\n    MySingleton &operator=(const MySingleton &) = delete;\n    MySingleton(MySingleton &&) = default;\n    MySingleton &operator=(MySingleton &&) = default;\n\n    static MySingleton &get_instance() {\n        PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<MySingleton> storage;\n        return storage\n            .call_once_and_store_result([]() -> MySingleton {\n                MySingleton instance{};\n\n                auto emplace = [&instance](const py::handle &obj) -> void {\n                    obj.inc_ref(); // Ensure the object is not GC'd while interpreter is alive\n                    instance.objects.emplace_back(obj);\n                };\n\n                // Example objects to store in the singleton\n                emplace(py::type::handle_of(py::none()));                        // static type\n                emplace(py::type::handle_of(py::tuple()));                       // static type\n                emplace(py::type::handle_of(py::list()));                        // static type\n                emplace(py::type::handle_of(py::dict()));                        // static type\n                emplace(py::module_::import(\"collections\").attr(\"OrderedDict\")); // static type\n                emplace(py::module_::import(\"collections\").attr(\"defaultdict\")); // heap type\n                emplace(py::module_::import(\"collections\").attr(\"deque\"));       // heap type\n\n                assert(instance.objects.size() == 7);\n                return instance;\n            })\n            .get_stored();\n    }\n\n    std::vector<py::handle> &get_objects() { return objects; }\n\n    static void init() {\n        // Ensure the singleton is created\n        auto &instance = get_instance();\n        (void) instance; // suppress unused variable warning\n        assert(instance.objects.size() == 7);\n        // Register cleanup at interpreter exit\n        py::module_::import(\"atexit\").attr(\"register\")(py::cpp_function(&MySingleton::clear));\n    }\n\n    static void clear() {\n        auto &instance = get_instance();\n        (void) instance; // suppress unused variable warning\n        assert(instance.objects.size() == 7);\n        for (const auto &obj : instance.objects) {\n            obj.dec_ref();\n        }\n        instance.objects.clear();\n    }\n\nprivate:\n    std::vector<py::handle> objects;\n};\n\nclass MyClass {\npublic:\n    explicit MyClass(py::ssize_t v) : value(v) {}\n    py::ssize_t get_value() const { return value; }\n\nprivate:\n    py::ssize_t value;\n};\n\nclass MyGlobalError : public std::runtime_error {\npublic:\n    using std::runtime_error::runtime_error;\n};\n\nclass MyLocalError : public std::runtime_error {\npublic:\n    using std::runtime_error::runtime_error;\n};\n\nenum class MyEnum : int {\n    ONE = 1,\n    TWO = 2,\n    THREE = 3,\n};\n} // namespace mod_per_interpreter_gil_with_singleton\n} // namespace pybind11_tests\n\nPYBIND11_MODULE(mod_per_interpreter_gil_with_singleton,\n                m,\n                py::mod_gil_not_used(),\n                py::multiple_interpreters::per_interpreter_gil()) {\n    using namespace pybind11_tests::mod_per_interpreter_gil_with_singleton;\n\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = true;\n#else\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = false;\n#endif\n\n    MySingleton::init();\n\n    // Ensure py::multiple_interpreters::per_interpreter_gil() works with singletons using\n    // py::gil_safe_call_once_and_store\n    m.def(\n        \"get_objects_in_singleton\",\n        []() -> std::vector<py::handle> { return MySingleton::get_instance().get_objects(); },\n        \"Get the list of objects stored in the singleton\");\n\n    // Ensure py::multiple_interpreters::per_interpreter_gil() works with class bindings\n    py::class_<MyClass>(m, \"MyClass\")\n        .def(py::init<py::ssize_t>())\n        .def(\"get_value\", &MyClass::get_value);\n\n    // Ensure py::multiple_interpreters::per_interpreter_gil() works with global exceptions\n    py::register_exception<MyGlobalError>(m, \"MyGlobalError\");\n    // Ensure py::multiple_interpreters::per_interpreter_gil() works with local exceptions\n    py::register_local_exception<MyLocalError>(m, \"MyLocalError\");\n\n#ifdef PYBIND11_HAS_NATIVE_ENUM\n    // Ensure py::multiple_interpreters::per_interpreter_gil() works with native_enum\n    py::native_enum<MyEnum>(m, \"MyEnum\", \"enum.IntEnum\")\n        .value(\"ONE\", MyEnum::ONE)\n        .value(\"TWO\", MyEnum::TWO)\n        .value(\"THREE\", MyEnum::THREE)\n        .finalize();\n#else\n    py::enum_<MyEnum>(m, \"MyEnum\")\n        .value(\"ONE\", MyEnum::ONE)\n        .value(\"TWO\", MyEnum::TWO)\n        .value(\"THREE\", MyEnum::THREE);\n#endif\n}\n"
  },
  {
    "path": "tests/mod_shared_interpreter_gil.cpp",
    "content": "#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\n/* Simple test module/test class to check that the referenced internals data of external pybind11\n * modules are different across subinterpreters\n */\n\nPYBIND11_MODULE(mod_shared_interpreter_gil, m, py::multiple_interpreters::shared_gil()) {\n    m.def(\"internals_at\",\n          []() { return reinterpret_cast<uintptr_t>(&py::detail::get_internals()); });\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = true;\n#else\n    m.attr(\"defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT\") = false;\n#endif\n}\n"
  },
  {
    "path": "tests/object.h",
    "content": "#if !defined(__OBJECT_H)\n#    define __OBJECT_H\n\n#    include \"constructor_stats.h\"\n\n#    include <atomic>\n\n/// Reference counted object base class\nclass Object {\npublic:\n    /// Default constructor\n    Object() { print_default_created(this); }\n\n    /// Copy constructor\n    Object(const Object &) : m_refCount(0) { print_copy_created(this); }\n\n    /// Return the current reference count\n    int getRefCount() const { return m_refCount; };\n\n    /// Increase the object's reference count by one\n    void incRef() const { ++m_refCount; }\n\n    /** \\brief Decrease the reference count of\n     * the object and possibly deallocate it.\n     *\n     * The object will automatically be deallocated once\n     * the reference count reaches zero.\n     */\n    void decRef(bool dealloc = true) const {\n        --m_refCount;\n        if (m_refCount == 0 && dealloc) {\n            delete this;\n        } else if (m_refCount < 0) {\n            throw std::runtime_error(\"Internal error: reference count < 0!\");\n        }\n    }\n\n    virtual std::string toString() const = 0;\n\nprotected:\n    /** \\brief Virtual protected deconstructor.\n     * (Will only be called by \\ref ref)\n     */\n    virtual ~Object() { print_destroyed(this); }\n\nprivate:\n    mutable std::atomic<int> m_refCount{0};\n};\n\n// Tag class used to track constructions of ref objects.  When we track constructors, below, we\n// track and print out the actual class (e.g. ref<MyObject>), and *also* add a fake tracker for\n// ref_tag.  This lets us check that the total number of ref<Anything> constructors/destructors is\n// correct without having to check each individual ref<Whatever> type individually.\nclass ref_tag {};\n\n/**\n * \\brief Reference counting helper\n *\n * The \\a ref refeference template is a simple wrapper to store a\n * pointer to an object. It takes care of increasing and decreasing\n * the reference count of the object. When the last reference goes\n * out of scope, the associated object will be deallocated.\n *\n * \\ingroup libcore\n */\ntemplate <typename T>\nclass ref {\npublic:\n    /// Create a nullptr reference\n    ref() : m_ptr(nullptr) {\n        print_default_created(this);\n        track_default_created((ref_tag *) this);\n    }\n\n    /// Construct a reference from a pointer\n    explicit ref(T *ptr) : m_ptr(ptr) {\n        if (m_ptr) {\n            ((Object *) m_ptr)->incRef();\n        }\n\n        print_created(this, \"from pointer\", m_ptr);\n        track_created((ref_tag *) this, \"from pointer\");\n    }\n\n    /// Copy constructor\n    ref(const ref &r) : m_ptr(r.m_ptr) {\n        if (m_ptr) {\n            ((Object *) m_ptr)->incRef();\n        }\n\n        print_copy_created(this, \"with pointer\", m_ptr);\n        track_copy_created((ref_tag *) this);\n    }\n\n    /// Move constructor\n    ref(ref &&r) noexcept : m_ptr(r.m_ptr) {\n        r.m_ptr = nullptr;\n\n        print_move_created(this, \"with pointer\", m_ptr);\n        track_move_created((ref_tag *) this);\n    }\n\n    /// Destroy this reference\n    ~ref() {\n        if (m_ptr) {\n            ((Object *) m_ptr)->decRef();\n        }\n\n        print_destroyed(this);\n        track_destroyed((ref_tag *) this);\n    }\n\n    /// Move another reference into the current one\n    ref &operator=(ref &&r) noexcept {\n        print_move_assigned(this, \"pointer\", r.m_ptr);\n        track_move_assigned((ref_tag *) this);\n\n        if (*this == r) {\n            return *this;\n        }\n        if (m_ptr) {\n            ((Object *) m_ptr)->decRef();\n        }\n        m_ptr = r.m_ptr;\n        r.m_ptr = nullptr;\n        return *this;\n    }\n\n    /// Overwrite this reference with another reference\n    ref &operator=(const ref &r) {\n        if (this == &r) {\n            return *this;\n        }\n        print_copy_assigned(this, \"pointer\", r.m_ptr);\n        track_copy_assigned((ref_tag *) this);\n\n        if (m_ptr == r.m_ptr) {\n            return *this;\n        }\n        if (m_ptr) {\n            ((Object *) m_ptr)->decRef();\n        }\n        m_ptr = r.m_ptr;\n        if (m_ptr) {\n            ((Object *) m_ptr)->incRef();\n        }\n        return *this;\n    }\n\n    /// Overwrite this reference with a pointer to another object\n    ref &operator=(T *ptr) {\n        print_values(this, \"assigned pointer\");\n        track_values((ref_tag *) this, \"assigned pointer\");\n\n        if (m_ptr == ptr) {\n            return *this;\n        }\n        if (m_ptr) {\n            ((Object *) m_ptr)->decRef();\n        }\n        m_ptr = ptr;\n        if (m_ptr) {\n            ((Object *) m_ptr)->incRef();\n        }\n        return *this;\n    }\n\n    /// Compare this reference with another reference\n    bool operator==(const ref &r) const { return m_ptr == r.m_ptr; }\n\n    /// Compare this reference with another reference\n    bool operator!=(const ref &r) const { return m_ptr != r.m_ptr; }\n\n    /// Compare this reference with a pointer\n    bool operator==(const T *ptr) const { return m_ptr == ptr; }\n\n    /// Compare this reference with a pointer\n    bool operator!=(const T *ptr) const { return m_ptr != ptr; }\n\n    /// Access the object referenced by this reference\n    T *operator->() { return m_ptr; }\n\n    /// Access the object referenced by this reference\n    const T *operator->() const { return m_ptr; }\n\n    /// Return a C++ reference to the referenced object\n    T &operator*() { return *m_ptr; }\n\n    /// Return a const C++ reference to the referenced object\n    const T &operator*() const { return *m_ptr; }\n\n    /// Return a pointer to the referenced object\n    explicit operator T *() { return m_ptr; }\n\n    /// Return a const pointer to the referenced object\n    T *get_ptr() { return m_ptr; }\n\n    /// Return a pointer to the referenced object\n    const T *get_ptr() const { return m_ptr; }\n\nprivate:\n    T *m_ptr;\n};\n\n#endif /* __OBJECT_H */\n"
  },
  {
    "path": "tests/pure_cpp/CMakeLists.txt",
    "content": "find_package(Catch 2.13.10)\n\nif(CATCH_FOUND)\n  message(STATUS \"Building pure C++ tests (not depending on Python) using Catch v${CATCH_VERSION}\")\nelse()\n  message(STATUS \"Catch not detected. Interpreter tests will be skipped. Install Catch headers\"\n                 \" manually or use `cmake -DDOWNLOAD_CATCH=ON` to fetch them automatically.\")\n  return()\nendif()\n\nadd_executable(smart_holder_poc_test smart_holder_poc_test.cpp)\npybind11_enable_warnings(smart_holder_poc_test)\ntarget_link_libraries(smart_holder_poc_test PRIVATE pybind11::headers Catch2::Catch2)\n\nadd_custom_target(\n  test_pure_cpp\n  COMMAND \"$<TARGET_FILE:smart_holder_poc_test>\"\n  WORKING_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}\"\n  USES_TERMINAL # Ensures output is shown immediately (not buffered and possibly lost on crash)\n)\n\nadd_dependencies(check test_pure_cpp)\n"
  },
  {
    "path": "tests/pure_cpp/smart_holder_poc.h",
    "content": "// Copyright (c) 2020-2024 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#pragma once\n\n#include \"pybind11/detail/struct_smart_holder.h\"\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(memory)\nPYBIND11_NAMESPACE_BEGIN(smart_holder_poc) // Proof-of-Concept implementations.\n\n// NOLINTNEXTLINE(bugprone-incorrect-enable-shared-from-this)\nstruct PrivateESFT : private std::enable_shared_from_this<PrivateESFT> {};\nstatic_assert(!type_has_shared_from_this(static_cast<PrivateESFT *>(nullptr)),\n              \"should detect inaccessible base\");\n\ntemplate <typename T>\nT &as_lvalue_ref(const smart_holder &hld) {\n    static const char *context = \"as_lvalue_ref\";\n    hld.ensure_is_populated(context);\n    hld.ensure_has_pointee(context);\n    return *hld.as_raw_ptr_unowned<T>();\n}\n\ntemplate <typename T>\nT &&as_rvalue_ref(const smart_holder &hld) {\n    static const char *context = \"as_rvalue_ref\";\n    hld.ensure_is_populated(context);\n    hld.ensure_has_pointee(context);\n    return std::move(*hld.as_raw_ptr_unowned<T>());\n}\n\ntemplate <typename T>\nT *as_raw_ptr_release_ownership(smart_holder &hld,\n                                const char *context = \"as_raw_ptr_release_ownership\") {\n    hld.ensure_can_release_ownership(context);\n    T *raw_ptr = hld.as_raw_ptr_unowned<T>();\n    hld.release_ownership(get_guarded_delete);\n    return raw_ptr;\n}\n\ntemplate <typename T, typename D = std::default_delete<T>>\nstd::unique_ptr<T, D> as_unique_ptr(smart_holder &hld) {\n    static const char *context = \"as_unique_ptr\";\n    hld.ensure_compatible_uqp_del<T, D>(context);\n    hld.ensure_use_count_1(context);\n    T *raw_ptr = hld.as_raw_ptr_unowned<T>();\n    hld.release_ownership(get_guarded_delete);\n    // KNOWN DEFECT (see PR #4850): Does not copy the deleter.\n    return std::unique_ptr<T, D>(raw_ptr);\n}\n\nPYBIND11_NAMESPACE_END(smart_holder_poc)\nPYBIND11_NAMESPACE_END(memory)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n"
  },
  {
    "path": "tests/pure_cpp/smart_holder_poc_test.cpp",
    "content": "#include \"smart_holder_poc.h\"\n\n#include <cstddef>\n#include <functional>\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n// Catch uses _ internally, which breaks gettext style defines\n#ifdef _\n#    undef _\n#endif\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nusing pybind11::memory::guarded_delete;\nusing pybind11::memory::smart_holder;\nnamespace poc = pybind11::memory::smart_holder_poc;\n\nnamespace helpers {\n\nstruct movable_int {\n    int valu;\n    explicit movable_int(int v) : valu{v} {}\n    movable_int(movable_int &&other) noexcept : valu(other.valu) { other.valu = 91; }\n};\n\ntemplate <typename T>\nstruct functor_builtin_delete {\n    void operator()(T *ptr) { delete ptr; }\n#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 8)                                   \\\n    || (defined(__clang_major__) && __clang_major__ == 3 && __clang_minor__ == 6)\n    // Workaround for these errors:\n    // gcc 4.8.5: too many initializers for 'helpers::functor_builtin_delete<int>'\n    // clang 3.6: excess elements in struct initializer\n    functor_builtin_delete() = default;\n    functor_builtin_delete(const functor_builtin_delete &) {}\n    functor_builtin_delete(functor_builtin_delete &&) {}\n#endif\n};\n\ntemplate <typename T>\nstruct functor_other_delete : functor_builtin_delete<T> {};\n\nstruct indestructible_int {\n    int valu;\n    explicit indestructible_int(int v) : valu{v} {}\n\nprivate:\n    ~indestructible_int() = default;\n};\n\nstruct base {\n    virtual int get() { return 10; }\n    virtual ~base() = default;\n};\n\nstruct derived : public base {\n    int get() override { return 100; }\n};\n\n} // namespace helpers\n\nTEST_CASE(\"from_raw_ptr_unowned+as_raw_ptr_unowned\", \"[S]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE(*hld.as_raw_ptr_unowned<int>() == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_lvalue_ref\", \"[S]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_rvalue_ref\", \"[S]\") {\n    helpers::movable_int orig(19);\n    {\n        auto hld = smart_holder::from_raw_ptr_unowned(&orig);\n        helpers::movable_int othr(poc::as_rvalue_ref<helpers::movable_int>(hld));\n        REQUIRE(othr.valu == 19);\n        REQUIRE(orig.valu == 91);\n    }\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_raw_ptr_release_ownership\", \"[E]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE_THROWS_WITH(poc::as_raw_ptr_release_ownership<int>(hld),\n                        \"Cannot disown non-owning holder (as_raw_ptr_release_ownership).\");\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_unique_ptr\", \"[E]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld),\n                        \"Cannot disown non-owning holder (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_unique_ptr_with_deleter\", \"[E]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE_THROWS_WITH((poc::as_unique_ptr<int, helpers::functor_builtin_delete<int>>(hld)),\n                        \"Missing unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_raw_ptr_unowned+as_shared_ptr\", \"[S]\") {\n    static int value = 19;\n    auto hld = smart_holder::from_raw_ptr_unowned(&value);\n    REQUIRE(*hld.as_shared_ptr<int>() == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_lvalue_ref\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    REQUIRE(hld.has_pointee());\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_raw_ptr_release_ownership1\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    auto new_owner = std::unique_ptr<int>(poc::as_raw_ptr_release_ownership<int>(hld));\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_raw_ptr_release_ownership2\", \"[E]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    auto shd_ptr = hld.as_shared_ptr<int>();\n    REQUIRE_THROWS_WITH(poc::as_raw_ptr_release_ownership<int>(hld),\n                        \"Cannot disown use_count != 1 (as_raw_ptr_release_ownership).\");\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_unique_ptr1\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    std::unique_ptr<int> new_owner = poc::as_unique_ptr<int>(hld);\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_unique_ptr2\", \"[E]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    auto shd_ptr = hld.as_shared_ptr<int>();\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld),\n                        \"Cannot disown use_count != 1 (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_unique_ptr_with_deleter\", \"[E]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    REQUIRE_THROWS_WITH((poc::as_unique_ptr<int, helpers::functor_builtin_delete<int>>(hld)),\n                        \"Missing unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_shared_ptr\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    std::shared_ptr<int> new_owner = hld.as_shared_ptr<int>();\n    REQUIRE(hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+disown+reclaim_disowned\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    std::unique_ptr<int> new_owner(hld.as_raw_ptr_unowned<int>());\n    hld.disown(pybind11::memory::get_guarded_delete);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n    REQUIRE(*new_owner == 19);\n    // Manually verified: without this, clang++ -fsanitize=address reports\n    // \"detected memory leaks\".\n    hld.reclaim_disowned(pybind11::memory::get_guarded_delete);\n    // NOLINTNEXTLINE(bugprone-unused-return-value)\n    (void) new_owner.release(); // Manually verified: without this, clang++ -fsanitize=address\n                                // reports \"attempting double-free\".\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n    REQUIRE(new_owner.get() == nullptr);\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+disown+release_disowned\", \"[S]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    std::unique_ptr<int> new_owner(hld.as_raw_ptr_unowned<int>());\n    hld.disown(pybind11::memory::get_guarded_delete);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n    REQUIRE(*new_owner == 19);\n    hld.release_disowned();\n    REQUIRE(!hld.has_pointee());\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+disown+ensure_is_not_disowned\", \"[E]\") {\n    const char *context = \"test_case\";\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    hld.ensure_is_not_disowned(context); // Does not throw.\n    std::unique_ptr<int> new_owner(hld.as_raw_ptr_unowned<int>());\n    hld.disown(pybind11::memory::get_guarded_delete);\n    REQUIRE_THROWS_WITH(hld.ensure_is_not_disowned(context),\n                        \"Holder was disowned already (test_case).\");\n}\n\nTEST_CASE(\"from_unique_ptr+as_lvalue_ref\", \"[S]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_unique_ptr+as_raw_ptr_release_ownership1\", \"[S]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    auto new_owner = std::unique_ptr<int>(poc::as_raw_ptr_release_ownership<int>(hld));\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_unique_ptr+as_raw_ptr_release_ownership2\", \"[E]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    auto shd_ptr = hld.as_shared_ptr<int>();\n    REQUIRE_THROWS_WITH(poc::as_raw_ptr_release_ownership<int>(hld),\n                        \"Cannot disown use_count != 1 (as_raw_ptr_release_ownership).\");\n}\n\nTEST_CASE(\"from_unique_ptr+as_unique_ptr1\", \"[S]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    std::unique_ptr<int> new_owner = poc::as_unique_ptr<int>(hld);\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_unique_ptr+as_unique_ptr2\", \"[E]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    auto shd_ptr = hld.as_shared_ptr<int>();\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld),\n                        \"Cannot disown use_count != 1 (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_unique_ptr+as_unique_ptr_with_deleter\", \"[E]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE_THROWS_WITH((poc::as_unique_ptr<int, helpers::functor_builtin_delete<int>>(hld)),\n                        \"Incompatible unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_unique_ptr+as_shared_ptr\", \"[S]\") {\n    std::unique_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    std::shared_ptr<int> new_owner = hld.as_shared_ptr<int>();\n    REQUIRE(hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_unique_ptr_derived+as_unique_ptr_base\", \"[S]\") {\n    std::unique_ptr<helpers::derived> orig_owner(new helpers::derived());\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    std::unique_ptr<helpers::base> new_owner = poc::as_unique_ptr<helpers::base>(hld);\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(new_owner->get() == 100);\n}\n\nTEST_CASE(\"from_unique_ptr_derived+as_unique_ptr_base2\", \"[E]\") {\n    std::unique_ptr<helpers::derived, helpers::functor_other_delete<helpers::derived>> orig_owner(\n        new helpers::derived());\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE_THROWS_WITH(\n        (poc::as_unique_ptr<helpers::base, helpers::functor_builtin_delete<helpers::base>>(hld)),\n        \"Incompatible unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_lvalue_ref\", \"[S]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_unique_ptr_with_std_function_deleter+as_lvalue_ref\", \"[S]\") {\n    std::unique_ptr<int, std::function<void(const int *)>> orig_owner(\n        new int(19), [](const int *raw_ptr) { delete raw_ptr; });\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_raw_ptr_release_ownership\", \"[E]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE_THROWS_WITH(poc::as_raw_ptr_release_ownership<int>(hld),\n                        \"Cannot disown custom deleter (as_raw_ptr_release_ownership).\");\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_unique_ptr\", \"[E]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld),\n                        \"Incompatible unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_unique_ptr_with_deleter1\", \"[S]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> new_owner\n        = poc::as_unique_ptr<int, helpers::functor_builtin_delete<int>>(hld);\n    REQUIRE(!hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_unique_ptr_with_deleter2\", \"[E]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    REQUIRE_THROWS_WITH((poc::as_unique_ptr<int, helpers::functor_other_delete<int>>(hld)),\n                        \"Incompatible unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_shared_ptr\", \"[S]\") {\n    std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n    auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n    REQUIRE(orig_owner.get() == nullptr);\n    std::shared_ptr<int> new_owner = hld.as_shared_ptr<int>();\n    REQUIRE(hld.has_pointee());\n    REQUIRE(*new_owner == 19);\n}\n\nTEST_CASE(\"from_shared_ptr+as_lvalue_ref\", \"[S]\") {\n    std::shared_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_shared_ptr(orig_owner);\n    REQUIRE(poc::as_lvalue_ref<int>(hld) == 19);\n}\n\nTEST_CASE(\"from_shared_ptr+as_raw_ptr_release_ownership\", \"[E]\") {\n    std::shared_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_shared_ptr(orig_owner);\n    REQUIRE_THROWS_WITH(poc::as_raw_ptr_release_ownership<int>(hld),\n                        \"Cannot disown external shared_ptr (as_raw_ptr_release_ownership).\");\n}\n\nTEST_CASE(\"from_shared_ptr+as_unique_ptr\", \"[E]\") {\n    std::shared_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_shared_ptr(orig_owner);\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld),\n                        \"Cannot disown external shared_ptr (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_shared_ptr+as_unique_ptr_with_deleter\", \"[E]\") {\n    std::shared_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_shared_ptr(orig_owner);\n    REQUIRE_THROWS_WITH((poc::as_unique_ptr<int, helpers::functor_builtin_delete<int>>(hld)),\n                        \"Missing unique_ptr deleter (as_unique_ptr).\");\n}\n\nTEST_CASE(\"from_shared_ptr+as_shared_ptr\", \"[S]\") {\n    std::shared_ptr<int> orig_owner(new int(19));\n    auto hld = smart_holder::from_shared_ptr(orig_owner);\n    REQUIRE(*hld.as_shared_ptr<int>() == 19);\n}\n\nTEST_CASE(\"error_unpopulated_holder\", \"[E]\") {\n    smart_holder hld;\n    REQUIRE_THROWS_WITH(poc::as_lvalue_ref<int>(hld), \"Unpopulated holder (as_lvalue_ref).\");\n}\n\nTEST_CASE(\"error_disowned_holder\", \"[E]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    poc::as_unique_ptr<int>(hld);\n    REQUIRE_THROWS_WITH(poc::as_lvalue_ref<int>(hld), \"Disowned holder (as_lvalue_ref).\");\n}\n\nTEST_CASE(\"error_cannot_disown_nullptr\", \"[E]\") {\n    auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n    poc::as_unique_ptr<int>(hld);\n    REQUIRE_THROWS_WITH(poc::as_unique_ptr<int>(hld), \"Cannot disown nullptr (as_unique_ptr).\");\n}\n\nTEST_CASE(\"indestructible_int-from_raw_ptr_unowned+as_raw_ptr_unowned\", \"[S]\") {\n    using zombie = helpers::indestructible_int;\n\n// This is from C++17\n#ifdef __cpp_lib_byte\n    using raw_byte = std::byte;\n#else\n    using raw_byte = char;\n#endif\n\n    // Using placement new instead of plain new, to not trigger leak sanitizer errors.\n    alignas(zombie) raw_byte memory_block[sizeof(zombie)];\n\n    auto *value = new (memory_block) zombie(19);\n    auto hld = smart_holder::from_raw_ptr_unowned(value);\n    REQUIRE(hld.as_raw_ptr_unowned<zombie>()->valu == 19);\n}\n\nTEST_CASE(\"indestructible_int-from_raw_ptr_take_ownership\", \"[E]\") {\n    helpers::indestructible_int *value = nullptr;\n    REQUIRE_THROWS_WITH(smart_holder::from_raw_ptr_take_ownership(value),\n                        \"Pointee is not destructible (from_raw_ptr_take_ownership).\");\n}\n\nTEST_CASE(\"from_raw_ptr_take_ownership+as_shared_ptr-outliving_smart_holder\", \"[S]\") {\n    // Exercises guarded_builtin_delete flag_ptr validity past destruction of smart_holder.\n    std::shared_ptr<int> longer_living;\n    {\n        auto hld = smart_holder::from_raw_ptr_take_ownership(new int(19));\n        longer_living = hld.as_shared_ptr<int>();\n    }\n    REQUIRE(*longer_living == 19);\n}\n\nTEST_CASE(\"from_unique_ptr_with_deleter+as_shared_ptr-outliving_smart_holder\", \"[S]\") {\n    // Exercises guarded_custom_deleter flag_ptr validity past destruction of smart_holder.\n    std::shared_ptr<int> longer_living;\n    {\n        std::unique_ptr<int, helpers::functor_builtin_delete<int>> orig_owner(new int(19));\n        auto hld = smart_holder::from_unique_ptr(std::move(orig_owner));\n        longer_living = hld.as_shared_ptr<int>();\n    }\n    REQUIRE(*longer_living == 19);\n}\n"
  },
  {
    "path": "tests/pybind11_cross_module_tests.cpp",
    "content": "/*\n    tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules\n\n    Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl_bind.h>\n\n#include \"local_bindings.h\"\n#include \"pybind11_tests.h\"\n#include \"test_exceptions.h\"\n\n#include <numeric>\n#include <utility>\n\nclass CrossDSOClass {\npublic:\n    CrossDSOClass() = default;\n    virtual ~CrossDSOClass();\n    CrossDSOClass(const CrossDSOClass &) = default;\n};\n\nCrossDSOClass::~CrossDSOClass() = default;\n\nPYBIND11_MODULE(pybind11_cross_module_tests, m, py::mod_gil_not_used()) {\n    m.doc() = \"pybind11 cross-module test module\";\n\n    // test_local_bindings.py tests:\n    //\n    // Definitions here are tested by importing both this module and the\n    // relevant pybind11_tests submodule from a test_whatever.py\n\n    // test_load_external\n    bind_local<ExternalType1>(m, \"ExternalType1\", py::module_local());\n    bind_local<ExternalType2, 0, std::shared_ptr<ExternalType2>>(\n        m, \"ExternalType2\", py::module_local());\n    bind_local<ExternalType3, 0, py::smart_holder>(m, \"ExternalType3\", py::module_local());\n\n    // test_exceptions.py\n    py::register_local_exception<LocalSimpleException>(m, \"LocalSimpleException\");\n    m.def(\"raise_runtime_error\", []() {\n        py::set_error(PyExc_RuntimeError, \"My runtime error\");\n        throw py::error_already_set();\n    });\n    m.def(\"raise_value_error\", []() {\n        py::set_error(PyExc_ValueError, \"My value error\");\n        throw py::error_already_set();\n    });\n    m.def(\"throw_pybind_value_error\", []() { throw py::value_error(\"pybind11 value error\"); });\n    m.def(\"throw_pybind_type_error\", []() { throw py::type_error(\"pybind11 type error\"); });\n    m.def(\"throw_stop_iteration\", []() { throw py::stop_iteration(); });\n    m.def(\"throw_local_error\", []() { throw LocalException(\"just local\"); });\n    m.def(\"throw_local_simple_error\", []() { throw LocalSimpleException(\"external mod\"); });\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const shared_exception &e) {\n            py::set_error(PyExc_KeyError, e.what());\n        }\n    });\n\n    // translate the local exception into a key error but only in this module\n    py::register_local_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const LocalException &e) {\n            py::set_error(PyExc_KeyError, e.what());\n        }\n    });\n\n    // test_local_bindings.py\n    // Local to both:\n    bind_local<LocalType, 1>(m, \"LocalType\", py::module_local()).def(\"get2\", [](LocalType &t) {\n        return t.i + 2;\n    });\n\n    // Can only be called with our python type:\n    m.def(\"local_value\", [](LocalType &l) { return l.i; });\n\n    // test_nonlocal_failure\n    // This registration will fail (global registration when LocalFail is already registered\n    // globally in the main test module):\n    m.def(\"register_nonlocal\", [m]() { bind_local<NonLocalType, 0>(m, \"NonLocalType\"); });\n\n    // test_stl_bind_local\n    // stl_bind.h binders defaults to py::module_local if the types are local or converting:\n    py::bind_vector<LocalVec>(m, \"LocalVec\");\n    py::bind_map<LocalMap>(m, \"LocalMap\");\n\n    // test_stl_bind_global\n    // and global if the type (or one of the types, for the map) is global (so these will fail,\n    // assuming pybind11_tests is already loaded):\n    m.def(\"register_nonlocal_vec\", [m]() { py::bind_vector<NonLocalVec>(m, \"NonLocalVec\"); });\n    m.def(\"register_nonlocal_map\", [m]() { py::bind_map<NonLocalMap>(m, \"NonLocalMap\"); });\n    // The default can, however, be overridden to global using `py::module_local()` or\n    // `py::module_local(false)`.\n    // Explicitly made local:\n    py::bind_vector<NonLocalVec2>(m, \"NonLocalVec2\", py::module_local());\n    // Explicitly made global (and so will fail to bind):\n    m.def(\"register_nonlocal_map2\",\n          [m]() { py::bind_map<NonLocalMap2>(m, \"NonLocalMap2\", py::module_local(false)); });\n\n    // test_mixed_local_global\n    // We try this both with the global type registered first and vice versa (the order shouldn't\n    // matter).\n    m.def(\"register_mixed_global_local\",\n          [m]() { bind_local<MixedGlobalLocal, 200>(m, \"MixedGlobalLocal\", py::module_local()); });\n    m.def(\"register_mixed_local_global\", [m]() {\n        bind_local<MixedLocalGlobal, 2000>(m, \"MixedLocalGlobal\", py::module_local(false));\n    });\n    m.def(\"get_mixed_gl\", [](int i) { return MixedGlobalLocal(i); });\n    m.def(\"get_mixed_lg\", [](int i) { return MixedLocalGlobal(i); });\n\n    // test_internal_locals_differ\n    m.def(\"local_cpp_types_addr\",\n          []() { return (uintptr_t) &py::detail::get_local_internals().registered_types_cpp; });\n\n    // test_stl_caster_vs_stl_bind\n    py::bind_vector<std::vector<int>>(m, \"VectorInt\");\n\n    m.def(\"load_vector_via_binding\",\n          [](std::vector<int> &v) { return std::accumulate(v.begin(), v.end(), 0); });\n\n    // test_cross_module_calls\n    m.def(\"return_self\", [](LocalVec *v) { return v; });\n    m.def(\"return_copy\", [](const LocalVec &v) { return LocalVec(v); });\n\n    class Dog : public pets::Pet {\n    public:\n        explicit Dog(std::string name) : Pet(std::move(name)) {}\n    };\n    py::class_<pets::Pet>(m, \"Pet\", py::module_local()).def(\"name\", &pets::Pet::name);\n    // Binding for local extending class:\n    py::class_<Dog, pets::Pet>(m, \"Dog\").def(py::init<std::string>());\n    m.def(\"pet_name\", [](pets::Pet &p) { return p.name(); });\n\n    py::class_<MixGL>(m, \"MixGL\", py::module_local()).def(py::init<int>());\n    m.def(\"get_gl_value\", [](MixGL &o) { return o.i + 100; });\n\n    py::class_<MixGL2>(m, \"MixGL2\", py::module_local()).def(py::init<int>());\n\n    // test_vector_bool\n    // We can't test both stl.h and stl_bind.h conversions of `std::vector<bool>` within\n    // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool`\n    // is defined here and tested in `test_stl_binders.py`.\n    py::bind_vector<std::vector<bool>>(m, \"VectorBool\");\n\n    // test_missing_header_message\n    // The main module already includes stl.h, but we need to test the error message\n    // which appears when this header is missing.\n    m.def(\"missing_header_arg\", [](const std::vector<float> &) {});\n    m.def(\"missing_header_return\", []() { return std::vector<float>(); });\n\n    // test_class_cross_module_use_after_one_module_dealloc\n    m.def(\"consume_cross_dso_class\", [](const CrossDSOClass &) {});\n}\n"
  },
  {
    "path": "tests/pybind11_tests.cpp",
    "content": "/*\n    tests/pybind11_tests.cpp -- pybind example plugin\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\n#include \"constructor_stats.h\"\n\n#include <functional>\n#include <list>\n\n/*\nFor testing purposes, we define a static global variable here in a function that each individual\ntest .cpp calls with its initialization lambda.  It's convenient here because we can just not\ncompile some test files to disable/ignore some of the test code.\n\nIt is NOT recommended as a way to use pybind11 in practice, however: the initialization order will\nbe essentially random, which is okay for our test scripts (there are no dependencies between the\nindividual pybind11 test .cpp files), but most likely not what you want when using pybind11\nproductively.\n\nInstead, see the \"How can I reduce the build time?\" question in the \"Frequently asked questions\"\nsection of the documentation for good practice on splitting binding code over multiple files.\n*/\nstd::list<std::function<void(py::module_ &)>> &initializers() {\n    static std::list<std::function<void(py::module_ &)>> inits;\n    return inits;\n}\n\ntest_initializer::test_initializer(Initializer init) { initializers().emplace_back(init); }\n\ntest_initializer::test_initializer(const char *submodule_name, Initializer init) {\n    initializers().emplace_back([=](py::module_ &parent) {\n        auto m = parent.def_submodule(submodule_name);\n        init(m);\n    });\n}\n\nvoid bind_ConstructorStats(py::module_ &m) {\n    py::class_<ConstructorStats>(m, \"ConstructorStats\")\n        .def(\"alive\", &ConstructorStats::alive)\n        .def(\"values\", &ConstructorStats::values)\n        .def_readwrite(\"default_constructions\", &ConstructorStats::default_constructions)\n        .def_readwrite(\"copy_assignments\", &ConstructorStats::copy_assignments)\n        .def_readwrite(\"move_assignments\", &ConstructorStats::move_assignments)\n        .def_readwrite(\"copy_constructions\", &ConstructorStats::copy_constructions)\n        .def_readwrite(\"move_constructions\", &ConstructorStats::move_constructions)\n        .def_static(\"get\",\n                    (ConstructorStats & (*) (py::object)) & ConstructorStats::get,\n                    py::return_value_policy::reference_internal)\n\n        // Not exactly ConstructorStats, but related: expose the internal pybind number of\n        // registered instances to allow instance cleanup checks (invokes a GC first)\n        .def_static(\"detail_reg_inst\", []() {\n            ConstructorStats::gc();\n            return py::detail::num_registered_instances();\n        });\n}\n\nconst char *cpp_std() {\n    return\n#if defined(PYBIND11_CPP20)\n        \"C++20\";\n#elif defined(PYBIND11_CPP17)\n        \"C++17\";\n#elif defined(PYBIND11_CPP14)\n        \"C++14\";\n#else\n        \"C++11\";\n#endif\n}\n\nPYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {\n    m.doc() = \"pybind11 test module\";\n\n    // Intentionally kept minimal to not create a maintenance chore\n    // (\"just enough\" to be conclusive).\n#if defined(__VERSION__)\n    m.attr(\"compiler_info\") = __VERSION__;\n#elif defined(_MSC_FULL_VER)\n    m.attr(\"compiler_info\") = \"MSVC \" PYBIND11_TOSTRING(_MSC_FULL_VER);\n#else\n    m.attr(\"compiler_info\") = py::none();\n#endif\n    m.attr(\"cpp_std\") = cpp_std();\n    m.attr(\"PYBIND11_INTERNALS_ID\") = PYBIND11_INTERNALS_ID;\n    // Free threaded Python uses UINT32_MAX for immortal objects.\n    m.attr(\"PYBIND11_SIMPLE_GIL_MANAGEMENT\") =\n#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)\n        true;\n#else\n        false;\n#endif\n\n    bind_ConstructorStats(m);\n\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n    m.attr(\"detailed_error_messages_enabled\") = true;\n#else\n    m.attr(\"detailed_error_messages_enabled\") = false;\n#endif\n\n    py::class_<UserType>(m, \"UserType\", \"A `py::class_` type for testing\")\n        .def(py::init<>())\n        .def(py::init<int>())\n        .def(\"get_value\", &UserType::value, \"Get value using a method\")\n        .def(\"set_value\", &UserType::set, \"Set value using a method\")\n        .def_property(\"value\", &UserType::value, &UserType::set, \"Get/set value using a property\")\n        .def(\"__repr__\", [](const UserType &u) { return \"UserType({})\"_s.format(u.value()); });\n\n    py::class_<IncType, UserType>(m, \"IncType\")\n        .def(py::init<>())\n        .def(py::init<int>())\n        .def(\"__repr__\", [](const IncType &u) { return \"IncType({})\"_s.format(u.value()); });\n\n    for (const auto &initializer : initializers()) {\n        initializer(m);\n    }\n\n    py::class_<TestContext>(m, \"TestContext\")\n        .def(py::init<>(&TestContext::createNewContextForInit))\n        .def(\"__enter__\", &TestContext::contextEnter)\n        .def(\"__exit__\", &TestContext::contextExit);\n}\n"
  },
  {
    "path": "tests/pybind11_tests.h",
    "content": "#pragma once\n\n#include <pybind11/eval.h>\n#include <pybind11/pybind11.h>\n\n#include <memory>\n\nnamespace py = pybind11;\nusing namespace pybind11::literals;\n\nclass test_initializer {\n    using Initializer = void (*)(py::module_ &);\n\npublic:\n    explicit test_initializer(Initializer init);\n    test_initializer(const char *submodule_name, Initializer init);\n};\n\n#define TEST_SUBMODULE(name, variable)                                                            \\\n    void test_submodule_##name(py::module_ &);                                                    \\\n    test_initializer name(#name, test_submodule_##name);                                          \\\n    void test_submodule_##name(py::module_ &(variable))\n\n/// Dummy type which is not exported anywhere -- something to trigger a conversion error\nstruct UnregisteredType {};\n\n/// A user-defined type which is exported and can be used by any test\nclass UserType {\npublic:\n    UserType() = default;\n    explicit UserType(int i) : i(i) {}\n\n    int value() const { return i; }\n    void set(int set) { i = set; }\n\nprivate:\n    int i = -1;\n};\n\n/// Like UserType, but increments `value` on copy for quick reference vs. copy tests\nclass IncType : public UserType {\npublic:\n    using UserType::UserType;\n    IncType() = default;\n    IncType(const IncType &other) : IncType(other.value() + 1) {}\n    IncType(IncType &&) = delete;\n    IncType &operator=(const IncType &) = delete;\n    IncType &operator=(IncType &&) = delete;\n};\n\n/// A simple union for basic testing\nunion IntFloat {\n    int i;\n    float f;\n};\n\nclass UnusualOpRef {\npublic:\n    using NonTrivialType = std::shared_ptr<int>; // Almost any non-trivial type will do.\n    // Overriding operator& should not break pybind11.\n    NonTrivialType operator&() { return non_trivial_member; }\n    NonTrivialType operator&() const { return non_trivial_member; }\n\nprivate:\n    NonTrivialType non_trivial_member;\n};\n\n/// Custom cast-only type that casts to a string \"rvalue\" or \"lvalue\" depending on the cast\n/// context. Used to test recursive casters (e.g. std::tuple, stl containers).\nstruct RValueCaster {};\nPYBIND11_NAMESPACE_BEGIN(pybind11)\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <>\nclass type_caster<RValueCaster> {\npublic:\n    PYBIND11_TYPE_CASTER(RValueCaster, const_name(\"RValueCaster\"));\n    static handle cast(RValueCaster &&, return_value_policy, handle) {\n        return py::str(\"rvalue\").release();\n    }\n    static handle cast(const RValueCaster &, return_value_policy, handle) {\n        return py::str(\"lvalue\").release();\n    }\n};\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(pybind11)\n\ntemplate <typename F>\nvoid ignoreOldStyleInitWarnings(F &&body) {\n    py::exec(R\"(\n    message = \"pybind11-bound class '.+' is using an old-style placement-new '(?:__init__|__setstate__)' which has been deprecated\"\n\n    import warnings\n    with warnings.catch_warnings():\n        warnings.filterwarnings(\"ignore\", message=message, category=FutureWarning)\n        body()\n    )\",\n             py::dict(py::arg(\"body\") = py::cpp_function(body)));\n}\n\n// See PR #5419 for background.\nclass TestContext {\npublic:\n    TestContext() = delete;\n    TestContext(const TestContext &) = delete;\n    TestContext(TestContext &&) = delete;\n    static TestContext *createNewContextForInit() { return new TestContext(\"new-context\"); }\n\n    pybind11::object contextEnter() {\n        py::object contextObj = py::cast(*this);\n        return contextObj;\n    }\n    void contextExit(const pybind11::object & /*excType*/,\n                     const pybind11::object & /*excVal*/,\n                     const pybind11::object & /*excTb*/) {}\n\nprivate:\n    explicit TestContext(const std::string &context) : context(context) {}\n    std::string context;\n};\n"
  },
  {
    "path": "tests/pyproject.toml",
    "content": "# Warning: this is currently used to test cross-compilation, and is not a general\n# out-of-tree builder for the tests (yet). Specifically, wheels can't be built from\n# SDists.\n\n[build-system]\nrequires = [\"scikit-build-core\"]\nbuild-backend = \"scikit_build_core.build\"\n\n[project]\nname = \"pybind11_tests\"\nversion = \"0.0.1\"\ndependencies = [\"pytest\", \"pytest-timeout\"]\n\n\n[dependency-groups]\nnumpy = [\"numpy\"]\nscipy = [\"scipy\"]\n\n\n[tool.scikit-build]\nbuild.verbose = true\nlogging.level = \"INFO\"\n\n[tool.scikit-build.cmake.define]\nPYBIND11_FINDPYTHON = true\n\n\n[tool.cibuildwheel]\ntest-sources = [\"tests\", \"pyproject.toml\"]\ntest-command = \"python -m pytest -v -o timeout=120 -p no:cacheprovider tests\"\n# Pyodide doesn't have signal.setitimer, so pytest-timeout can't work with timeout > 0\npyodide.test-command = \"python -m pytest -v -o timeout=0 -p no:cacheprovider tests\"\nenvironment.PIP_ONLY_BINARY = \"numpy\"\nenvironment.PIP_PREFER_BINARY = \"1\"\n\nandroid.environment.ANDROID_API_LEVEL = \"24\"  # Needed to include libc++ in the wheel.\npyodide.test-groups = [\"numpy\", \"scipy\"]\nios.test-groups = [\"numpy\"]\nios.xbuild-tools = [\"cmake\", \"ninja\"]\nios.environment.PIP_EXTRA_INDEX_URL = \"https://pypi.anaconda.org/beeware/simple\"\n"
  },
  {
    "path": "tests/pytest.ini",
    "content": "[pytest]\nminversion = 6\nnorecursedirs = test_* extra_*\nxfail_strict = True\naddopts =\n    # show summary of tests\n    -ra\n    # capture only Python print and C++ py::print, but not C output (low-level Python errors)\n    --capture=sys\n    # Show local info when a failure occurs\n    --showlocals\nlog_level = INFO\nfilterwarnings =\n    # make warnings into errors but ignore certain third-party extension issues\n    error\n    # somehow, some DeprecationWarnings do not get turned into errors\n    always::DeprecationWarning\n    # importing scipy submodules on some version of Python\n    ignore::ImportWarning\n    # bogus numpy ABI warning (see numpy/#432)\n    ignore:.*numpy.dtype size changed.*:RuntimeWarning\n    ignore:.*numpy.ufunc size changed.*:RuntimeWarning\n"
  },
  {
    "path": "tests/requirements.txt",
    "content": "--extra-index-url=https://www.graalvm.org/python/wheels\n--only-binary=:all:\nbuild>=1\nnumpy~=1.23.0; python_version==\"3.8\" and platform_python_implementation==\"PyPy\"\nnumpy~=1.25.0; python_version==\"3.9\" and platform_python_implementation==\"PyPy\"\nnumpy~=2.2.0; python_version==\"3.10\" and platform_python_implementation==\"PyPy\"\nnumpy~=1.26.0; platform_python_implementation==\"GraalVM\" and sys_platform==\"linux\"\nnumpy~=1.21.5; platform_python_implementation==\"CPython\" and python_version>=\"3.8\" and python_version<\"3.10\"\nnumpy~=1.22.2; platform_python_implementation==\"CPython\" and python_version==\"3.10\"\nnumpy~=1.26.0; platform_python_implementation==\"CPython\" and python_version>=\"3.11\" and python_version<\"3.13\" and platform_machine!=\"ARM64\"\nnumpy>=2.3.0; platform_python_implementation==\"CPython\" and python_version>=\"3.11\" and platform_machine==\"ARM64\"\nnumpy~=2.2.0; platform_python_implementation==\"CPython\" and python_version==\"3.13\" and platform_machine!=\"ARM64\"\nnumpy>=2.4.0; platform_python_implementation==\"CPython\" and python_version>=\"3.14\"\npytest>=6\npytest-timeout\nscipy~=1.5.4; platform_python_implementation==\"CPython\" and python_version<\"3.10\"\nscipy~=1.8.0; platform_python_implementation==\"CPython\" and python_version==\"3.10\" and sys_platform!=\"win32\"\nscipy~=1.11.1; platform_python_implementation==\"CPython\" and python_version>=\"3.11\" and python_version<\"3.13\" and sys_platform!=\"win32\"\nscipy~=1.15.2; platform_python_implementation==\"CPython\" and python_version==\"3.13\" and sys_platform!=\"win32\"\ntomlkit\n"
  },
  {
    "path": "tests/test_async.cpp",
    "content": "/*\n    tests/test_async.cpp -- __await__ support\n\n    Copyright (c) 2019 Google Inc.\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(async_module, m) {\n    struct DoesNotSupportAsync {};\n    py::class_<DoesNotSupportAsync>(m, \"DoesNotSupportAsync\").def(py::init<>());\n    struct SupportsAsync {};\n    py::class_<SupportsAsync>(m, \"SupportsAsync\")\n        .def(py::init<>())\n        .def(\"__await__\", [](const SupportsAsync &self) -> py::object {\n            static_cast<void>(self);\n            py::object loop = py::module_::import(\"asyncio.events\").attr(\"get_event_loop\")();\n            py::object f = loop.attr(\"create_future\")();\n            f.attr(\"set_result\")(5);\n            return f.attr(\"__await__\")();\n        });\n}\n"
  },
  {
    "path": "tests/test_async.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\n\nasyncio = pytest.importorskip(\"asyncio\")\nm = pytest.importorskip(\"pybind11_tests.async_module\")\n\nif sys.platform.startswith(\"emscripten\"):\n    pytest.skip(\"Can't run a new event_loop in pyodide\", allow_module_level=True)\n\n\n@pytest.fixture\ndef event_loop():\n    loop = asyncio.new_event_loop()\n    yield loop\n    loop.close()\n\n\nasync def get_await_result(x):\n    return await x\n\n\ndef test_await(event_loop):\n    assert event_loop.run_until_complete(get_await_result(m.SupportsAsync())) == 5\n\n\ndef test_await_missing(event_loop):\n    with pytest.raises(TypeError):\n        event_loop.run_until_complete(get_await_result(m.DoesNotSupportAsync()))\n"
  },
  {
    "path": "tests/test_buffers.cpp",
    "content": "/*\n    tests/test_buffers.cpp -- supporting Pythons' buffer protocol\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/complex.h>\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(buffers, m) {\n    m.attr(\"long_double_and_double_have_same_size\") = (sizeof(long double) == sizeof(double));\n\n    m.def(\"format_descriptor_format_buffer_info_equiv\",\n          [](const std::string &cpp_name, const py::buffer &buffer) {\n              // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables\n              static auto *format_table = new std::map<std::string, std::string>;\n              static auto *equiv_table\n                  = new std::map<std::string, bool (py::buffer_info::*)() const>;\n              if (format_table->empty()) {\n#define PYBIND11_ASSIGN_HELPER(...)                                                               \\\n    (*format_table)[#__VA_ARGS__] = py::format_descriptor<__VA_ARGS__>::format();                 \\\n    (*equiv_table)[#__VA_ARGS__] = &py::buffer_info::item_type_is_equivalent_to<__VA_ARGS__>;\n                  PYBIND11_ASSIGN_HELPER(PyObject *)\n                  PYBIND11_ASSIGN_HELPER(bool)\n                  PYBIND11_ASSIGN_HELPER(std::int8_t)\n                  PYBIND11_ASSIGN_HELPER(std::uint8_t)\n                  PYBIND11_ASSIGN_HELPER(std::int16_t)\n                  PYBIND11_ASSIGN_HELPER(std::uint16_t)\n                  PYBIND11_ASSIGN_HELPER(std::int32_t)\n                  PYBIND11_ASSIGN_HELPER(std::uint32_t)\n                  PYBIND11_ASSIGN_HELPER(std::int64_t)\n                  PYBIND11_ASSIGN_HELPER(std::uint64_t)\n                  PYBIND11_ASSIGN_HELPER(float)\n                  PYBIND11_ASSIGN_HELPER(double)\n                  PYBIND11_ASSIGN_HELPER(long double)\n                  PYBIND11_ASSIGN_HELPER(std::complex<float>)\n                  PYBIND11_ASSIGN_HELPER(std::complex<double>)\n                  PYBIND11_ASSIGN_HELPER(std::complex<long double>)\n#undef PYBIND11_ASSIGN_HELPER\n              }\n              return std::pair<std::string, bool>(\n                  (*format_table)[cpp_name], (buffer.request().*((*equiv_table)[cpp_name]))());\n          });\n\n    // test_from_python / test_to_python:\n    class Matrix {\n    public:\n        Matrix(py::ssize_t rows, py::ssize_t cols) : m_rows(rows), m_cols(cols) {\n            print_created(this, std::to_string(m_rows) + \"x\" + std::to_string(m_cols) + \" matrix\");\n            // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n            m_data = new float[(size_t) (rows * cols)];\n            memset(m_data, 0, sizeof(float) * (size_t) (rows * cols));\n        }\n\n        Matrix(const Matrix &s) : m_rows(s.m_rows), m_cols(s.m_cols) {\n            print_copy_created(this,\n                               std::to_string(m_rows) + \"x\" + std::to_string(m_cols) + \" matrix\");\n            // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n            m_data = new float[(size_t) (m_rows * m_cols)];\n            memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols));\n        }\n\n        Matrix(Matrix &&s) noexcept : m_rows(s.m_rows), m_cols(s.m_cols), m_data(s.m_data) {\n            print_move_created(this);\n            s.m_rows = 0;\n            s.m_cols = 0;\n            s.m_data = nullptr;\n        }\n\n        ~Matrix() {\n            print_destroyed(this,\n                            std::to_string(m_rows) + \"x\" + std::to_string(m_cols) + \" matrix\");\n            delete[] m_data;\n        }\n\n        Matrix &operator=(const Matrix &s) {\n            if (this == &s) {\n                return *this;\n            }\n            print_copy_assigned(this,\n                                std::to_string(m_rows) + \"x\" + std::to_string(m_cols) + \" matrix\");\n            delete[] m_data;\n            m_rows = s.m_rows;\n            m_cols = s.m_cols;\n            m_data = new float[(size_t) (m_rows * m_cols)];\n            memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols));\n            return *this;\n        }\n\n        Matrix &operator=(Matrix &&s) noexcept {\n            print_move_assigned(this,\n                                std::to_string(m_rows) + \"x\" + std::to_string(m_cols) + \" matrix\");\n            if (&s != this) {\n                delete[] m_data;\n                m_rows = s.m_rows;\n                m_cols = s.m_cols;\n                m_data = s.m_data;\n                s.m_rows = 0;\n                s.m_cols = 0;\n                s.m_data = nullptr;\n            }\n            return *this;\n        }\n\n        float operator()(py::ssize_t i, py::ssize_t j) const {\n            return m_data[(size_t) (i * m_cols + j)];\n        }\n\n        float &operator()(py::ssize_t i, py::ssize_t j) {\n            return m_data[(size_t) (i * m_cols + j)];\n        }\n\n        float *data() { return m_data; }\n\n        py::ssize_t rows() const { return m_rows; }\n        py::ssize_t cols() const { return m_cols; }\n\n    private:\n        py::ssize_t m_rows;\n        py::ssize_t m_cols;\n        float *m_data;\n    };\n    py::class_<Matrix>(m, \"Matrix\", py::buffer_protocol())\n        .def(py::init<py::ssize_t, py::ssize_t>())\n        /// Construct from a buffer\n        .def(py::init([](const py::buffer &b) {\n            py::buffer_info info = b.request();\n            if (info.format != py::format_descriptor<float>::format() || info.ndim != 2) {\n                throw std::runtime_error(\"Incompatible buffer format!\");\n            }\n\n            auto *v = new Matrix(info.shape[0], info.shape[1]);\n            memcpy(v->data(), info.ptr, sizeof(float) * (size_t) (v->rows() * v->cols()));\n            return v;\n        }))\n\n        .def(\"rows\", &Matrix::rows)\n        .def(\"cols\", &Matrix::cols)\n\n        /// Bare bones interface\n        .def(\"__getitem__\",\n             [](const Matrix &m, std::pair<py::ssize_t, py::ssize_t> i) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 return m(i.first, i.second);\n             })\n        .def(\"__setitem__\",\n             [](Matrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 m(i.first, i.second) = v;\n             })\n        /// Provide buffer access\n        .def_buffer([](Matrix &m) -> py::buffer_info {\n            return py::buffer_info(\n                m.data(),                          /* Pointer to buffer */\n                {m.rows(), m.cols()},              /* Buffer dimensions */\n                {sizeof(float) * size_t(m.cols()), /* Strides (in bytes) for each index */\n                 sizeof(float)});\n        });\n\n    // A matrix that uses Fortran storage order.\n    class FortranMatrix : public Matrix {\n    public:\n        FortranMatrix(py::ssize_t rows, py::ssize_t cols) : Matrix(cols, rows) {\n            print_created(this,\n                          std::to_string(rows) + \"x\" + std::to_string(cols) + \" Fortran matrix\");\n        }\n\n        float operator()(py::ssize_t i, py::ssize_t j) const { return Matrix::operator()(j, i); }\n\n        float &operator()(py::ssize_t i, py::ssize_t j) { return Matrix::operator()(j, i); }\n\n        using Matrix::data;\n\n        py::ssize_t rows() const { return Matrix::cols(); }\n        py::ssize_t cols() const { return Matrix::rows(); }\n    };\n    py::class_<FortranMatrix, Matrix>(m, \"FortranMatrix\", py::buffer_protocol())\n        .def(py::init<py::ssize_t, py::ssize_t>())\n\n        .def(\"rows\", &FortranMatrix::rows)\n        .def(\"cols\", &FortranMatrix::cols)\n\n        /// Bare bones interface\n        .def(\"__getitem__\",\n             [](const FortranMatrix &m, std::pair<py::ssize_t, py::ssize_t> i) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 return m(i.first, i.second);\n             })\n        .def(\"__setitem__\",\n             [](FortranMatrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 m(i.first, i.second) = v;\n             })\n        /// Provide buffer access\n        .def_buffer([](FortranMatrix &m) -> py::buffer_info {\n            return py::buffer_info(m.data(),             /* Pointer to buffer */\n                                   {m.rows(), m.cols()}, /* Buffer dimensions */\n                                   /* Strides (in bytes) for each index */\n                                   {sizeof(float), sizeof(float) * size_t(m.rows())});\n        });\n\n    // A matrix that uses a discontiguous underlying memory block.\n    class DiscontiguousMatrix : public Matrix {\n    public:\n        DiscontiguousMatrix(py::ssize_t rows,\n                            py::ssize_t cols,\n                            py::ssize_t row_factor,\n                            py::ssize_t col_factor)\n            : Matrix(rows * row_factor, cols * col_factor), m_row_factor(row_factor),\n              m_col_factor(col_factor) {\n            print_created(this,\n                          std::to_string(rows) + \"(*\" + std::to_string(row_factor) + \")x\"\n                              + std::to_string(cols) + \"(*\" + std::to_string(col_factor)\n                              + \") matrix\");\n        }\n        DiscontiguousMatrix(const DiscontiguousMatrix &) = delete;\n        ~DiscontiguousMatrix() {\n            print_destroyed(this,\n                            std::to_string(rows() / m_row_factor) + \"(*\"\n                                + std::to_string(m_row_factor) + \")x\"\n                                + std::to_string(cols() / m_col_factor) + \"(*\"\n                                + std::to_string(m_col_factor) + \") matrix\");\n        }\n\n        float operator()(py::ssize_t i, py::ssize_t j) const {\n            return Matrix::operator()(i * m_row_factor, j * m_col_factor);\n        }\n\n        float &operator()(py::ssize_t i, py::ssize_t j) {\n            return Matrix::operator()(i * m_row_factor, j * m_col_factor);\n        }\n\n        using Matrix::data;\n\n        py::ssize_t rows() const { return Matrix::rows() / m_row_factor; }\n        py::ssize_t cols() const { return Matrix::cols() / m_col_factor; }\n        py::ssize_t row_factor() const { return m_row_factor; }\n        py::ssize_t col_factor() const { return m_col_factor; }\n\n    private:\n        py::ssize_t m_row_factor;\n        py::ssize_t m_col_factor;\n    };\n    py::class_<DiscontiguousMatrix, Matrix>(m, \"DiscontiguousMatrix\", py::buffer_protocol())\n        .def(py::init<py::ssize_t, py::ssize_t, py::ssize_t, py::ssize_t>())\n\n        .def(\"rows\", &DiscontiguousMatrix::rows)\n        .def(\"cols\", &DiscontiguousMatrix::cols)\n\n        /// Bare bones interface\n        .def(\"__getitem__\",\n             [](const DiscontiguousMatrix &m, std::pair<py::ssize_t, py::ssize_t> i) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 return m(i.first, i.second);\n             })\n        .def(\"__setitem__\",\n             [](DiscontiguousMatrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) {\n                 if (i.first >= m.rows() || i.second >= m.cols()) {\n                     throw py::index_error();\n                 }\n                 m(i.first, i.second) = v;\n             })\n        /// Provide buffer access\n        .def_buffer([](DiscontiguousMatrix &m) -> py::buffer_info {\n            return py::buffer_info(m.data(),             /* Pointer to buffer */\n                                   {m.rows(), m.cols()}, /* Buffer dimensions */\n                                   /* Strides (in bytes) for each index */\n                                   {size_t(m.col_factor()) * sizeof(float) * size_t(m.cols())\n                                        * size_t(m.row_factor()),\n                                    size_t(m.col_factor()) * sizeof(float)});\n        });\n\n    class BrokenMatrix : public Matrix {\n    public:\n        BrokenMatrix(py::ssize_t rows, py::ssize_t cols) : Matrix(rows, cols) {}\n        void throw_runtime_error() { throw std::runtime_error(\"See PR #5324 for context.\"); }\n    };\n    py::class_<BrokenMatrix>(m, \"BrokenMatrix\", py::buffer_protocol())\n        .def(py::init<py::ssize_t, py::ssize_t>())\n        .def_buffer([](BrokenMatrix &m) {\n            m.throw_runtime_error();\n            return py::buffer_info();\n        });\n\n    // test_inherited_protocol\n    class SquareMatrix : public Matrix {\n    public:\n        explicit SquareMatrix(py::ssize_t n) : Matrix(n, n) {}\n    };\n    // Derived classes inherit the buffer protocol and the buffer access function\n    py::class_<SquareMatrix, Matrix>(m, \"SquareMatrix\").def(py::init<py::ssize_t>());\n\n    // test_pointer_to_member_fn\n    // Tests that passing a pointer to member to the base class works in\n    // the derived class.\n    struct Buffer {\n        int32_t value = 0;\n\n        py::buffer_info get_buffer_info() {\n            return py::buffer_info(\n                &value, sizeof(value), py::format_descriptor<int32_t>::format(), 1);\n        }\n    };\n    py::class_<Buffer>(m, \"Buffer\", py::buffer_protocol())\n        .def(py::init<>())\n        .def_readwrite(\"value\", &Buffer::value)\n        .def_buffer(&Buffer::get_buffer_info);\n\n    class ConstBuffer {\n        std::unique_ptr<int32_t> value;\n\n    public:\n        int32_t get_value() const { return *value; }\n        void set_value(int32_t v) { *value = v; }\n\n        py::buffer_info get_buffer_info() const {\n            return py::buffer_info(\n                value.get(), sizeof(*value), py::format_descriptor<int32_t>::format(), 1);\n        }\n\n        ConstBuffer() : value(new int32_t{0}) {}\n    };\n    py::class_<ConstBuffer>(m, \"ConstBuffer\", py::buffer_protocol())\n        .def(py::init<>())\n        .def_property(\"value\", &ConstBuffer::get_value, &ConstBuffer::set_value)\n        .def_buffer(&ConstBuffer::get_buffer_info);\n\n    struct DerivedBuffer : public Buffer {};\n    py::class_<DerivedBuffer>(m, \"DerivedBuffer\", py::buffer_protocol())\n        .def(py::init<>())\n        .def_readwrite(\"value\", (int32_t DerivedBuffer::*) &DerivedBuffer::value)\n        .def_buffer(&DerivedBuffer::get_buffer_info);\n\n    struct BufferReadOnly {\n        const uint8_t value = 0;\n        explicit BufferReadOnly(uint8_t value) : value(value) {}\n\n        py::buffer_info get_buffer_info() { return py::buffer_info(&value, 1); }\n    };\n    py::class_<BufferReadOnly>(m, \"BufferReadOnly\", py::buffer_protocol())\n        .def(py::init<uint8_t>())\n        .def_buffer(&BufferReadOnly::get_buffer_info);\n\n    struct BufferReadOnlySelect {\n        uint8_t value = 0;\n        bool readonly = false;\n\n        py::buffer_info get_buffer_info() { return py::buffer_info(&value, 1, readonly); }\n    };\n    py::class_<BufferReadOnlySelect>(m, \"BufferReadOnlySelect\", py::buffer_protocol())\n        .def(py::init<>())\n        .def_readwrite(\"value\", &BufferReadOnlySelect::value)\n        .def_readwrite(\"readonly\", &BufferReadOnlySelect::readonly)\n        .def_buffer(&BufferReadOnlySelect::get_buffer_info);\n\n    // Expose buffer_info for testing.\n    py::class_<py::buffer_info>(m, \"buffer_info\")\n        .def(py::init<>())\n        .def_readonly(\"itemsize\", &py::buffer_info::itemsize)\n        .def_readonly(\"size\", &py::buffer_info::size)\n        .def_readonly(\"format\", &py::buffer_info::format)\n        .def_readonly(\"ndim\", &py::buffer_info::ndim)\n        .def_readonly(\"shape\", &py::buffer_info::shape)\n        .def_readonly(\"strides\", &py::buffer_info::strides)\n        .def_readonly(\"readonly\", &py::buffer_info::readonly)\n        .def(\"__repr__\", [](py::handle self) {\n            return py::str(\"itemsize={0.itemsize!r}, size={0.size!r}, format={0.format!r}, \"\n                           \"ndim={0.ndim!r}, shape={0.shape!r}, strides={0.strides!r}, \"\n                           \"readonly={0.readonly!r}\")\n                .format(self);\n        });\n\n    m.def(\"get_buffer_info\", [](const py::buffer &buffer) { return buffer.request(); });\n\n    // Expose Py_buffer for testing.\n    m.attr(\"PyBUF_FORMAT\") = PyBUF_FORMAT;\n    m.attr(\"PyBUF_SIMPLE\") = PyBUF_SIMPLE;\n    m.attr(\"PyBUF_ND\") = PyBUF_ND;\n    m.attr(\"PyBUF_STRIDES\") = PyBUF_STRIDES;\n    m.attr(\"PyBUF_INDIRECT\") = PyBUF_INDIRECT;\n    m.attr(\"PyBUF_C_CONTIGUOUS\") = PyBUF_C_CONTIGUOUS;\n    m.attr(\"PyBUF_F_CONTIGUOUS\") = PyBUF_F_CONTIGUOUS;\n    m.attr(\"PyBUF_ANY_CONTIGUOUS\") = PyBUF_ANY_CONTIGUOUS;\n\n    m.def(\"get_py_buffer\", [](const py::object &object, int flags) {\n        Py_buffer buffer;\n        memset(&buffer, 0, sizeof(Py_buffer));\n        if (PyObject_GetBuffer(object.ptr(), &buffer, flags) == -1) {\n            throw py::error_already_set();\n        }\n\n        auto SimpleNamespace = py::module_::import(\"types\").attr(\"SimpleNamespace\");\n        py::object result = SimpleNamespace(\"len\"_a = buffer.len,\n                                            \"readonly\"_a = buffer.readonly,\n                                            \"itemsize\"_a = buffer.itemsize,\n                                            \"format\"_a = buffer.format,\n                                            \"ndim\"_a = buffer.ndim,\n                                            \"shape\"_a = py::none(),\n                                            \"strides\"_a = py::none(),\n                                            \"suboffsets\"_a = py::none());\n        if (buffer.shape != nullptr) {\n            py::list l;\n            for (auto i = 0; i < buffer.ndim; i++) {\n                l.append(buffer.shape[i]);\n            }\n            py::setattr(result, \"shape\", l);\n        }\n        if (buffer.strides != nullptr) {\n            py::list l;\n            for (auto i = 0; i < buffer.ndim; i++) {\n                l.append(buffer.strides[i]);\n            }\n            py::setattr(result, \"strides\", l);\n        }\n        if (buffer.suboffsets != nullptr) {\n            py::list l;\n            for (auto i = 0; i < buffer.ndim; i++) {\n                l.append(buffer.suboffsets[i]);\n            }\n            py::setattr(result, \"suboffsets\", l);\n        }\n\n        PyBuffer_Release(&buffer);\n        return result;\n    });\n}\n"
  },
  {
    "path": "tests/test_buffers.py",
    "content": "from __future__ import annotations\n\nimport ctypes\nimport io\nimport struct\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import buffers as m\n\nnp = pytest.importorskip(\"numpy\")\n\nif m.long_double_and_double_have_same_size:\n    # Determined by the compiler used to build the pybind11 tests\n    # (e.g. MSVC gets here, but MinGW might not).\n    np_float128 = None\n    np_complex256 = None\nelse:\n    # Determined by the compiler used to build numpy (e.g. MinGW).\n    np_float128 = getattr(np, *[\"float128\"] * 2)\n    np_complex256 = getattr(np, *[\"complex256\"] * 2)\n\nCPP_NAME_FORMAT_NP_DTYPE_TABLE = [\n    (\"PyObject *\", \"O\", object),\n    (\"bool\", \"?\", np.bool_),\n    (\"std::int8_t\", \"b\", np.int8),\n    (\"std::uint8_t\", \"B\", np.uint8),\n    (\"std::int16_t\", \"h\", np.int16),\n    (\"std::uint16_t\", \"H\", np.uint16),\n    (\"std::int32_t\", \"i\", np.int32),\n    (\"std::uint32_t\", \"I\", np.uint32),\n    (\"std::int64_t\", \"q\", np.int64),\n    (\"std::uint64_t\", \"Q\", np.uint64),\n    (\"float\", \"f\", np.float32),\n    (\"double\", \"d\", np.float64),\n    (\"long double\", \"g\", np_float128),\n    (\"std::complex<float>\", \"Zf\", np.complex64),\n    (\"std::complex<double>\", \"Zd\", np.complex128),\n    (\"std::complex<long double>\", \"Zg\", np_complex256),\n]\nCPP_NAME_FORMAT_TABLE = [\n    (cpp_name, format)\n    for cpp_name, format, np_dtype in CPP_NAME_FORMAT_NP_DTYPE_TABLE\n    if np_dtype is not None\n]\nCPP_NAME_NP_DTYPE_TABLE = [\n    (cpp_name, np_dtype) for cpp_name, _, np_dtype in CPP_NAME_FORMAT_NP_DTYPE_TABLE\n]\n\n\n@pytest.mark.parametrize((\"cpp_name\", \"np_dtype\"), CPP_NAME_NP_DTYPE_TABLE)\ndef test_format_descriptor_format_buffer_info_equiv(cpp_name, np_dtype):\n    if np_dtype is None:\n        pytest.skip(\n            f\"cpp_name=`{cpp_name}`: `long double` and `double` have same size.\"\n        )\n    if isinstance(np_dtype, str):\n        pytest.skip(f\"np.{np_dtype} does not exist.\")\n    np_array = np.array([], dtype=np_dtype)\n    for other_cpp_name, expected_format in CPP_NAME_FORMAT_TABLE:\n        format, np_array_is_matching = m.format_descriptor_format_buffer_info_equiv(\n            other_cpp_name, np_array\n        )\n        assert format == expected_format\n        if other_cpp_name == cpp_name:\n            assert np_array_is_matching\n        else:\n            assert not np_array_is_matching\n\n\ndef test_from_python():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.Matrix(np.array([1, 2, 3]))  # trying to assign a 1D array\n    assert str(excinfo.value) == \"Incompatible buffer format!\"\n\n    m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\n    m4 = m.Matrix(m3)\n\n    for i in range(m4.rows()):\n        for j in range(m4.cols()):\n            assert m3[i, j] == m4[i, j]\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n    cstats = ConstructorStats.get(m.Matrix)\n    assert cstats.alive() == 1\n    del m3, m4\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"2x3 matrix\"]\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0  # Don't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2444\n# TODO: fix on recent PyPy\n@pytest.mark.xfail(\n    env.PYPY, reason=\"PyPy 7.3.7 doesn't clear this anymore\", strict=False\n)\ndef test_to_python():\n    mat = m.Matrix(5, 4)\n    assert memoryview(mat).shape == (5, 4)\n\n    assert mat[2, 3] == 0\n    mat[2, 3] = 4.0\n    mat[3, 2] = 7.0\n    assert mat[2, 3] == 4\n    assert mat[3, 2] == 7\n    assert struct.unpack_from(\"f\", mat, (3 * 4 + 2) * 4) == (7,)\n    assert struct.unpack_from(\"f\", mat, (2 * 4 + 3) * 4) == (4,)\n\n    mat2 = np.array(mat, copy=False)\n    assert mat2.shape == (5, 4)\n    assert abs(mat2).sum() == 11\n    assert mat2[2, 3] == 4\n    assert mat2[3, 2] == 7\n    mat2[2, 3] = 5\n    assert mat2[2, 3] == 5\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n    cstats = ConstructorStats.get(m.Matrix)\n    assert cstats.alive() == 1\n    del mat\n    pytest.gc_collect()\n    assert cstats.alive() == 1\n    del mat2  # holds a mat reference\n    pytest.gc_collect()\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"5x4 matrix\"]\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0  # Don't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n\ndef test_inherited_protocol():\n    \"\"\"SquareMatrix is derived from Matrix and inherits the buffer protocol\"\"\"\n\n    matrix = m.SquareMatrix(5)\n    assert memoryview(matrix).shape == (5, 5)\n    assert np.asarray(matrix).shape == (5, 5)\n\n\ndef test_pointer_to_member_fn():\n    for cls in [m.Buffer, m.ConstBuffer, m.DerivedBuffer]:\n        buf = cls()\n        buf.value = 0x12345678\n        value = struct.unpack(\"i\", bytearray(buf))[0]\n        assert value == 0x12345678\n\n\ndef test_readonly_buffer():\n    buf = m.BufferReadOnly(0x64)\n    view = memoryview(buf)\n    assert view[0] == 0x64\n    assert view.readonly\n    with pytest.raises(TypeError):\n        view[0] = 0\n\n\ndef test_selective_readonly_buffer():\n    buf = m.BufferReadOnlySelect()\n\n    memoryview(buf)[0] = 0x64\n    assert buf.value == 0x64\n\n    io.BytesIO(b\"A\").readinto(buf)\n    assert buf.value == ord(b\"A\")\n\n    buf.readonly = True\n    with pytest.raises(TypeError):\n        memoryview(buf)[0] = 0\n    with pytest.raises(TypeError):\n        io.BytesIO(b\"1\").readinto(buf)\n\n\ndef test_ctypes_array_1d():\n    char1d = (ctypes.c_char * 10)()\n    int1d = (ctypes.c_int * 15)()\n    long1d = (ctypes.c_long * 7)()\n\n    for carray in (char1d, int1d, long1d):\n        info = m.get_buffer_info(carray)\n        assert info.itemsize == ctypes.sizeof(carray._type_)\n        assert info.size == len(carray)\n        assert info.ndim == 1\n        assert info.shape == [info.size]\n        assert info.strides == [info.itemsize]\n        assert not info.readonly\n\n\ndef test_ctypes_array_2d():\n    char2d = ((ctypes.c_char * 10) * 4)()\n    int2d = ((ctypes.c_int * 15) * 3)()\n    long2d = ((ctypes.c_long * 7) * 2)()\n\n    for carray in (char2d, int2d, long2d):\n        info = m.get_buffer_info(carray)\n        assert info.itemsize == ctypes.sizeof(carray[0]._type_)\n        assert info.size == len(carray) * len(carray[0])\n        assert info.ndim == 2\n        assert info.shape == [len(carray), len(carray[0])]\n        assert info.strides == [info.itemsize * len(carray[0]), info.itemsize]\n        assert not info.readonly\n\n\ndef test_ctypes_from_buffer():\n    test_pystr = b\"0123456789\"\n    for pyarray in (test_pystr, bytearray(test_pystr)):\n        pyinfo = m.get_buffer_info(pyarray)\n\n        if pyinfo.readonly:\n            cbytes = (ctypes.c_char * len(pyarray)).from_buffer_copy(pyarray)\n            cinfo = m.get_buffer_info(cbytes)\n        else:\n            cbytes = (ctypes.c_char * len(pyarray)).from_buffer(pyarray)\n            cinfo = m.get_buffer_info(cbytes)\n\n        assert cinfo.size == pyinfo.size\n        assert cinfo.ndim == pyinfo.ndim\n        assert cinfo.shape == pyinfo.shape\n        assert cinfo.strides == pyinfo.strides\n        assert not cinfo.readonly\n\n\ndef test_buffer_docstring(doc, backport_typehints):\n    assert (\n        backport_typehints(doc(m.get_buffer_info))\n        == \"get_buffer_info(arg0: collections.abc.Buffer) -> m.buffers.buffer_info\"\n    )\n\n\ndef test_buffer_exception():\n    with pytest.raises(BufferError, match=\"Error getting buffer\") as excinfo:\n        memoryview(m.BrokenMatrix(1, 1))\n    assert isinstance(excinfo.value.__cause__, RuntimeError)\n    assert \"for context\" in str(excinfo.value.__cause__)\n\n\n@pytest.mark.parametrize(\"type\", [\"pybind11\", \"numpy\"])\ndef test_c_contiguous_to_pybuffer(type):\n    if type == \"pybind11\":\n        mat = m.Matrix(5, 4)\n    elif type == \"numpy\":\n        mat = np.empty((5, 4), dtype=np.float32)\n    else:\n        raise ValueError(f\"Unknown parametrization {type}\")\n\n    info = m.get_py_buffer(mat, m.PyBUF_SIMPLE)\n    assert info.format is None\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 0  # See discussion on PR #5407.\n    assert info.shape is None\n    assert info.strides is None\n    assert info.suboffsets is None\n    assert not info.readonly\n    info = m.get_py_buffer(mat, m.PyBUF_SIMPLE | m.PyBUF_FORMAT)\n    assert info.format == \"f\"\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 0  # See discussion on PR #5407.\n    assert info.shape is None\n    assert info.strides is None\n    assert info.suboffsets is None\n    assert not info.readonly\n    info = m.get_py_buffer(mat, m.PyBUF_ND)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides is None\n    assert info.suboffsets is None\n    assert not info.readonly\n    info = m.get_py_buffer(mat, m.PyBUF_STRIDES)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides == [4 * info.itemsize, info.itemsize]\n    assert info.suboffsets is None\n    assert not info.readonly\n    info = m.get_py_buffer(mat, m.PyBUF_INDIRECT)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides == [4 * info.itemsize, info.itemsize]\n    assert info.suboffsets is None  # Should be filled in here, but we don't use it.\n    assert not info.readonly\n\n\n@pytest.mark.parametrize(\"type\", [\"pybind11\", \"numpy\"])\ndef test_fortran_contiguous_to_pybuffer(type):\n    if type == \"pybind11\":\n        mat = m.FortranMatrix(5, 4)\n    elif type == \"numpy\":\n        mat = np.empty((5, 4), dtype=np.float32, order=\"F\")\n    else:\n        raise ValueError(f\"Unknown parametrization {type}\")\n\n    # A Fortran-shaped buffer can only be accessed at PyBUF_STRIDES level or higher.\n    info = m.get_py_buffer(mat, m.PyBUF_STRIDES)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides == [info.itemsize, 5 * info.itemsize]\n    assert info.suboffsets is None\n    assert not info.readonly\n    info = m.get_py_buffer(mat, m.PyBUF_INDIRECT)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides == [info.itemsize, 5 * info.itemsize]\n    assert info.suboffsets is None  # Should be filled in here, but we don't use it.\n    assert not info.readonly\n\n\n@pytest.mark.parametrize(\"type\", [\"pybind11\", \"numpy\"])\ndef test_discontiguous_to_pybuffer(type):\n    if type == \"pybind11\":\n        mat = m.DiscontiguousMatrix(5, 4, 2, 3)\n    elif type == \"numpy\":\n        mat = np.empty((5 * 2, 4 * 3), dtype=np.float32)[::2, ::3]\n    else:\n        raise ValueError(f\"Unknown parametrization {type}\")\n\n    info = m.get_py_buffer(mat, m.PyBUF_STRIDES)\n    assert info.itemsize == ctypes.sizeof(ctypes.c_float)\n    assert info.len == 5 * 4 * info.itemsize\n    assert info.ndim == 2\n    assert info.shape == [5, 4]\n    assert info.strides == [2 * 4 * 3 * info.itemsize, 3 * info.itemsize]\n    assert info.suboffsets is None\n    assert not info.readonly\n\n\n@pytest.mark.parametrize(\"type\", [\"pybind11\", \"numpy\"])\ndef test_to_pybuffer_contiguity(type):\n    def check_strides(mat):\n        # The full block is memset to 0, so fill it with non-zero in real spots.\n        expected = np.arange(1, 5 * 4 + 1).reshape((5, 4))\n        for i in range(5):\n            for j in range(4):\n                mat[i, j] = expected[i, j]\n        # If all strides are correct, the exposed buffer should match the input.\n        np.testing.assert_array_equal(np.array(mat), expected)\n\n    if type == \"pybind11\":\n        cmat = m.Matrix(5, 4)  # C contiguous.\n        fmat = m.FortranMatrix(5, 4)  # Fortran contiguous.\n        dmat = m.DiscontiguousMatrix(5, 4, 2, 3)  # Not contiguous.\n        expected_exception = BufferError\n    elif type == \"numpy\":\n        cmat = np.empty((5, 4), dtype=np.float32)  # C contiguous.\n        fmat = np.empty((5, 4), dtype=np.float32, order=\"F\")  # Fortran contiguous.\n        dmat = np.empty((5 * 2, 4 * 3), dtype=np.float32)[::2, ::3]  # Not contiguous.\n        # NumPy incorrectly raises ValueError; when the minimum NumPy requirement is\n        # above the version that fixes https://github.com/numpy/numpy/issues/3634 then\n        # BufferError can be used everywhere.\n        expected_exception = (BufferError, ValueError)\n    else:\n        raise ValueError(f\"Unknown parametrization {type}\")\n\n    check_strides(cmat)\n    # Should work in C-contiguous mode, but not Fortran order.\n    m.get_py_buffer(cmat, m.PyBUF_C_CONTIGUOUS)\n    m.get_py_buffer(cmat, m.PyBUF_ANY_CONTIGUOUS)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(cmat, m.PyBUF_F_CONTIGUOUS)\n\n    check_strides(fmat)\n    # These flags imply C-contiguity, so won't work.\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(fmat, m.PyBUF_SIMPLE)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(fmat, m.PyBUF_ND)\n    # Should work in Fortran-contiguous mode, but not C order.\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(fmat, m.PyBUF_C_CONTIGUOUS)\n    m.get_py_buffer(fmat, m.PyBUF_ANY_CONTIGUOUS)\n    m.get_py_buffer(fmat, m.PyBUF_F_CONTIGUOUS)\n\n    check_strides(dmat)\n    # Should never work.\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(dmat, m.PyBUF_SIMPLE)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(dmat, m.PyBUF_ND)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(dmat, m.PyBUF_C_CONTIGUOUS)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(dmat, m.PyBUF_ANY_CONTIGUOUS)\n    with pytest.raises(expected_exception):\n        m.get_py_buffer(dmat, m.PyBUF_F_CONTIGUOUS)\n"
  },
  {
    "path": "tests/test_builtin_casters.cpp",
    "content": "/*\n    tests/test_builtin_casters.cpp -- Casters available without any additional headers\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/complex.h>\n\n#include \"pybind11_tests.h\"\n\nstruct ConstRefCasted {\n    int tag;\n};\n\nPYBIND11_NAMESPACE_BEGIN(pybind11)\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <>\nclass type_caster<ConstRefCasted> {\npublic:\n    static constexpr auto name = const_name<ConstRefCasted>();\n\n    // Input is unimportant, a new value will always be constructed based on the\n    // cast operator.\n    bool load(handle, bool) { return true; }\n\n    explicit operator ConstRefCasted &&() {\n        value = {1};\n        // NOLINTNEXTLINE(performance-move-const-arg)\n        return std::move(value);\n    }\n    explicit operator ConstRefCasted &() {\n        value = {2};\n        return value;\n    }\n    explicit operator ConstRefCasted *() {\n        value = {3};\n        return &value;\n    }\n\n    explicit operator const ConstRefCasted &() {\n        value = {4};\n        return value;\n    }\n    explicit operator const ConstRefCasted *() {\n        value = {5};\n        return &value;\n    }\n\n    // custom cast_op to explicitly propagate types to the conversion operators.\n    template <typename T_>\n    using cast_op_type =\n        /// const\n        conditional_t<\n            std::is_same<remove_reference_t<T_>, const ConstRefCasted *>::value,\n            const ConstRefCasted *,\n            conditional_t<\n                std::is_same<T_, const ConstRefCasted &>::value,\n                const ConstRefCasted &,\n                /// non-const\n                conditional_t<std::is_same<remove_reference_t<T_>, ConstRefCasted *>::value,\n                              ConstRefCasted *,\n                              conditional_t<std::is_same<T_, ConstRefCasted &>::value,\n                                            ConstRefCasted &,\n                                            /* else */ ConstRefCasted &&>>>>;\n\nprivate:\n    ConstRefCasted value = {0};\n};\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(pybind11)\n\nTEST_SUBMODULE(builtin_casters, m) {\n    PYBIND11_WARNING_PUSH\n    PYBIND11_WARNING_DISABLE_MSVC(4127)\n\n    // test_simple_string\n    m.def(\"string_roundtrip\", [](const char *s) { return s; });\n\n    // test_unicode_conversion\n    // Some test characters in utf16 and utf32 encodings.  The last one (the 𝐀) contains a null\n    // byte\n    char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*‽*/, cake32 = 0x1f382 /*🎂*/,\n             mathbfA32 = 0x1d400 /*𝐀*/;\n    char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82,\n             mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00;\n    std::wstring wstr;\n    wstr.push_back(0x61);   // a\n    wstr.push_back(0x2e18); // ⸘\n    if (sizeof(wchar_t) == 2) {\n        wstr.push_back(mathbfA16_1);\n        wstr.push_back(mathbfA16_2);\n    } // 𝐀, utf16\n    else {\n        wstr.push_back((wchar_t) mathbfA32);\n    } // 𝐀, utf32\n    wstr.push_back(0x7a); // z\n\n    m.def(\"good_utf8_string\", []() {\n        return std::string((const char *) u8\"Say utf8\\u203d \\U0001f382 \\U0001d400\");\n    }); // Say utf8‽ 🎂 𝐀\n    m.def(\"good_utf16_string\", [=]() {\n        return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16});\n    }); // b‽🎂𝐀z\n    m.def(\"good_utf32_string\",\n          [=]() { return std::u32string({a32, mathbfA32, cake32, ib32, z32}); }); // a𝐀🎂‽z\n    m.def(\"good_wchar_string\", [=]() { return wstr; });                           // a‽𝐀z\n    m.def(\"bad_utf8_string\", []() {\n        return std::string(\"abc\\xd0\"\n                           \"def\");\n    });\n    m.def(\"bad_utf16_string\", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); });\n    // Under Python 2.7, invalid unicode UTF-32 characters didn't appear to trigger\n    // UnicodeDecodeError\n    m.def(\"bad_utf32_string\", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });\n    if (sizeof(wchar_t) == 2) {\n        m.def(\"bad_wchar_string\",\n              [=]() { return std::wstring({wchar_t(0x61), wchar_t(0xd800)}); });\n    }\n    m.def(\"u8_Z\", []() -> char { return 'Z'; });\n    m.def(\"u8_eacute\", []() -> char { return '\\xe9'; });\n    m.def(\"u16_ibang\", [=]() -> char16_t { return ib16; });\n    m.def(\"u32_mathbfA\", [=]() -> char32_t { return mathbfA32; });\n    m.def(\"wchar_heart\", []() -> wchar_t { return 0x2665; });\n\n    // test_single_char_arguments\n    m.attr(\"wchar_size\") = py::cast(sizeof(wchar_t));\n    m.def(\"ord_char\", [](char c) -> int { return static_cast<unsigned char>(c); });\n    m.def(\"ord_char_lv\", [](char &c) -> int { return static_cast<unsigned char>(c); });\n    m.def(\"ord_char16\", [](char16_t c) -> uint16_t { return c; });\n    m.def(\"ord_char16_lv\", [](char16_t &c) -> uint16_t { return c; });\n    m.def(\"ord_char32\", [](char32_t c) -> uint32_t { return c; });\n    m.def(\"ord_wchar\", [](wchar_t c) -> int { return c; });\n\n    // test_bytes_to_string\n    m.def(\"strlen\", [](char *s) { return strlen(s); });\n    m.def(\"string_length\", [](const std::string &s) { return s.length(); });\n\n#ifdef PYBIND11_HAS_U8STRING\n    m.attr(\"has_u8string\") = true;\n    m.def(\"good_utf8_u8string\", []() {\n        return std::u8string(u8\"Say utf8\\u203d \\U0001f382 \\U0001d400\");\n    }); // Say utf8‽ 🎂 𝐀\n    m.def(\"bad_utf8_u8string\", []() {\n        return std::u8string((const char8_t *) \"abc\\xd0\"\n                                               \"def\");\n    });\n\n    m.def(\"u8_char8_Z\", []() -> char8_t { return u8'Z'; });\n\n    // test_single_char_arguments\n    m.def(\"ord_char8\", [](char8_t c) -> int { return static_cast<unsigned char>(c); });\n    m.def(\"ord_char8_lv\", [](char8_t &c) -> int { return static_cast<unsigned char>(c); });\n#endif\n\n    // test_string_view\n#ifdef PYBIND11_HAS_STRING_VIEW\n    m.attr(\"has_string_view\") = true;\n    m.def(\"string_view_print\", [](std::string_view s) { py::print(s, s.size()); });\n    m.def(\"string_view16_print\", [](std::u16string_view s) { py::print(s, s.size()); });\n    m.def(\"string_view32_print\", [](std::u32string_view s) { py::print(s, s.size()); });\n    m.def(\"string_view_chars\", [](std::string_view s) {\n        py::list l;\n        for (auto c : s) {\n            l.append((std::uint8_t) c);\n        }\n        return l;\n    });\n    m.def(\"string_view16_chars\", [](std::u16string_view s) {\n        py::list l;\n        for (auto c : s) {\n            l.append((int) c);\n        }\n        return l;\n    });\n    m.def(\"string_view32_chars\", [](std::u32string_view s) {\n        py::list l;\n        for (auto c : s) {\n            l.append((int) c);\n        }\n        return l;\n    });\n    m.def(\"string_view_return\",\n          []() { return std::string_view((const char *) u8\"utf8 secret \\U0001f382\"); });\n    m.def(\"string_view16_return\",\n          []() { return std::u16string_view(u\"utf16 secret \\U0001f382\"); });\n    m.def(\"string_view32_return\",\n          []() { return std::u32string_view(U\"utf32 secret \\U0001f382\"); });\n\n    // The inner lambdas here are to also test implicit conversion\n    using namespace std::literals;\n    m.def(\"string_view_bytes\",\n          []() { return [](py::bytes b) { return b; }(\"abc \\x80\\x80 def\"sv); });\n    m.def(\"string_view_str\",\n          []() { return [](py::str s) { return s; }(\"abc \\342\\200\\275 def\"sv); });\n    m.def(\"string_view_from_bytes\",\n          [](const py::bytes &b) { return [](std::string_view s) { return s; }(b); });\n    m.def(\"string_view_memoryview\", []() {\n        static constexpr auto val = \"Have some \\360\\237\\216\\202\"sv;\n        return py::memoryview::from_memory(val);\n    });\n\n#    ifdef PYBIND11_HAS_U8STRING\n    m.def(\"string_view8_print\", [](std::u8string_view s) { py::print(s, s.size()); });\n    m.def(\"string_view8_chars\", [](std::u8string_view s) {\n        py::list l;\n        for (auto c : s)\n            l.append((std::uint8_t) c);\n        return l;\n    });\n    m.def(\"string_view8_return\", []() { return std::u8string_view(u8\"utf8 secret \\U0001f382\"); });\n    m.def(\"string_view8_str\", []() { return py::str{std::u8string_view{u8\"abc ‽ def\"}}; });\n#    endif\n\n    struct TypeWithBothOperatorStringAndStringView {\n        // NOLINTNEXTLINE(google-explicit-constructor)\n        operator std::string() const { return \"success\"; }\n        // NOLINTNEXTLINE(google-explicit-constructor)\n        operator std::string_view() const { return \"failure\"; }\n    };\n    m.def(\"bytes_from_type_with_both_operator_string_and_string_view\",\n          []() { return py::bytes(TypeWithBothOperatorStringAndStringView()); });\n    m.def(\"str_from_type_with_both_operator_string_and_string_view\",\n          []() { return py::str(TypeWithBothOperatorStringAndStringView()); });\n#endif\n\n    // test_integer_casting\n    m.def(\"i32_str\", [](std::int32_t v) { return std::to_string(v); });\n    m.def(\"u32_str\", [](std::uint32_t v) { return std::to_string(v); });\n    m.def(\"i64_str\", [](std::int64_t v) { return std::to_string(v); });\n    m.def(\"u64_str\", [](std::uint64_t v) { return std::to_string(v); });\n\n    // test_int_convert\n    m.def(\"int_passthrough\", [](int arg) { return arg; });\n    m.def(\"int_passthrough_noconvert\", [](int arg) { return arg; }, py::arg{}.noconvert());\n\n    // test_float_convert\n    m.def(\"float_passthrough\", [](float arg) { return arg; });\n    m.def(\"float_passthrough_noconvert\", [](float arg) { return arg; }, py::arg{}.noconvert());\n\n    // test_tuple\n    m.def(\n        \"pair_passthrough\",\n        [](const std::pair<bool, std::string> &input) {\n            return std::make_pair(input.second, input.first);\n        },\n        \"Return a pair in reversed order\");\n    m.def(\n        \"tuple_passthrough\",\n        [](std::tuple<bool, std::string, int> input) {\n            return std::make_tuple(std::get<2>(input), std::get<1>(input), std::get<0>(input));\n        },\n        \"Return a triple in reversed order\");\n    m.def(\"empty_tuple\", []() { return std::tuple<>(); });\n    static std::pair<RValueCaster, RValueCaster> lvpair;\n    static std::tuple<RValueCaster, RValueCaster, RValueCaster> lvtuple;\n    static std::pair<RValueCaster, std::tuple<RValueCaster, std::pair<RValueCaster, RValueCaster>>>\n        lvnested;\n    m.def(\"rvalue_pair\", []() { return std::make_pair(RValueCaster{}, RValueCaster{}); });\n    m.def(\"lvalue_pair\", []() -> const decltype(lvpair) & { return lvpair; });\n    m.def(\"rvalue_tuple\",\n          []() { return std::make_tuple(RValueCaster{}, RValueCaster{}, RValueCaster{}); });\n    m.def(\"lvalue_tuple\", []() -> const decltype(lvtuple) & { return lvtuple; });\n    m.def(\"rvalue_nested\", []() {\n        return std::make_pair(\n            RValueCaster{},\n            std::make_tuple(RValueCaster{}, std::make_pair(RValueCaster{}, RValueCaster{})));\n    });\n    m.def(\"lvalue_nested\", []() -> const decltype(lvnested) & { return lvnested; });\n\n    m.def(\n        \"int_string_pair\",\n        []() {\n            // Using no-destructor idiom to side-step warnings from overzealous compilers.\n            static auto *int_string_pair = new std::pair<int, std::string>{2, \"items\"};\n            return int_string_pair;\n        },\n        py::return_value_policy::reference);\n\n    // test_builtins_cast_return_none\n    m.def(\"return_none_string\", []() -> std::string * { return nullptr; });\n    m.def(\"return_none_char\", []() -> const char * { return nullptr; });\n    m.def(\"return_none_bool\", []() -> bool * { return nullptr; });\n    m.def(\"return_none_int\", []() -> int * { return nullptr; });\n    m.def(\"return_none_float\", []() -> float * { return nullptr; });\n    m.def(\"return_none_pair\", []() -> std::pair<int, int> * { return nullptr; });\n\n    // test_none_deferred\n    m.def(\"defer_none_cstring\", [](char *) { return false; });\n    m.def(\"defer_none_cstring\", [](const py::none &) { return true; });\n    m.def(\"defer_none_custom\", [](UserType *) { return false; });\n    m.def(\"defer_none_custom\", [](const py::none &) { return true; });\n    m.def(\"nodefer_none_void\", [](void *) { return true; });\n    m.def(\"nodefer_none_void\", [](const py::none &) { return false; });\n\n    // test_void_caster\n    m.def(\"load_nullptr_t\", [](std::nullptr_t) {}); // not useful, but it should still compile\n    m.def(\"cast_nullptr_t\", []() { return std::nullptr_t{}; });\n\n    // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.\n\n    // test_bool_caster\n    m.def(\"bool_passthrough\", [](bool arg) { return arg; });\n    m.def(\"bool_passthrough_noconvert\", [](bool arg) { return arg; }, py::arg{}.noconvert());\n\n    // TODO: This should be disabled and fixed in future Intel compilers\n#if !defined(__INTEL_COMPILER)\n    // Test \"bool_passthrough_noconvert\" again, but using () instead of {} to construct py::arg\n    // When compiled with the Intel compiler, this results in segmentation faults when importing\n    // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when\n    // a newer version of icc is available.\n    m.def(\"bool_passthrough_noconvert2\", [](bool arg) { return arg; }, py::arg().noconvert());\n#endif\n\n    // test_reference_wrapper\n    m.def(\"refwrap_builtin\", [](std::reference_wrapper<int> p) { return 10 * p.get(); });\n    m.def(\"refwrap_usertype\", [](std::reference_wrapper<UserType> p) { return p.get().value(); });\n    m.def(\"refwrap_usertype_const\",\n          [](std::reference_wrapper<const UserType> p) { return p.get().value(); });\n\n    m.def(\"refwrap_lvalue\", []() -> std::reference_wrapper<UserType> {\n        static UserType x(1);\n        return std::ref(x);\n    });\n    m.def(\"refwrap_lvalue_const\", []() -> std::reference_wrapper<const UserType> {\n        static UserType x(1);\n        return std::cref(x);\n    });\n\n    // Not currently supported (std::pair caster has return-by-value cast operator);\n    // triggers static_assert failure.\n    // m.def(\"refwrap_pair\", [](std::reference_wrapper<std::pair<int, int>>) { });\n\n    m.def(\n        \"refwrap_list\",\n        [](bool copy) {\n            static IncType x1(1), x2(2);\n            py::list l;\n            for (const auto &f : {std::ref(x1), std::ref(x2)}) {\n                l.append(py::cast(\n                    f, copy ? py::return_value_policy::copy : py::return_value_policy::reference));\n            }\n            return l;\n        },\n        \"copy\"_a);\n\n    m.def(\"refwrap_iiw\", [](const IncType &w) { return w.value(); });\n    m.def(\"refwrap_call_iiw\", [](IncType &w, const py::function &f) {\n        py::list l;\n        l.append(f(std::ref(w)));\n        l.append(f(std::cref(w)));\n        IncType x(w.value());\n        l.append(f(std::ref(x)));\n        IncType y(w.value());\n        auto r3 = std::ref(y);\n        l.append(f(r3));\n        return l;\n    });\n\n    // test_complex\n    m.def(\"complex_cast\", [](float x) { return \"{}\"_s.format(x); });\n    m.def(\"complex_cast\",\n          [](std::complex<float> x) { return \"({}, {})\"_s.format(x.real(), x.imag()); });\n    m.def(\n        \"complex_cast_strict\",\n        [](std::complex<float> x) { return \"({}, {})\"_s.format(x.real(), x.imag()); },\n        py::arg{}.noconvert());\n\n    m.def(\"complex_convert\", [](std::complex<float> x) { return x; });\n    m.def(\"complex_noconvert\", [](std::complex<float> x) { return x; }, py::arg{}.noconvert());\n\n    // test_overload_resolution_float_int\n    // Test that float overload registered before int overload gets selected when passing int\n    // This documents the breaking change: int can now match float in strict mode\n    m.def(\"overload_resolution_test\", [](float x) { return \"float: \" + std::to_string(x); });\n    m.def(\"overload_resolution_test\", [](int x) { return \"int: \" + std::to_string(x); });\n\n    // Test with noconvert (strict mode) - this is the key breaking change\n    m.def(\n        \"overload_resolution_strict\",\n        [](float x) { return \"float_strict: \" + std::to_string(x); },\n        py::arg{}.noconvert());\n    m.def(\"overload_resolution_strict\", [](int x) { return \"int_strict: \" + std::to_string(x); });\n\n    // Test complex overload resolution: complex registered before float/int\n    m.def(\"overload_resolution_complex\", [](std::complex<float> x) {\n        return \"complex: (\" + std::to_string(x.real()) + \", \" + std::to_string(x.imag()) + \")\";\n    });\n    m.def(\"overload_resolution_complex\", [](float x) { return \"float: \" + std::to_string(x); });\n    m.def(\"overload_resolution_complex\", [](int x) { return \"int: \" + std::to_string(x); });\n\n    // test int vs. long (Python 2)\n    m.def(\"int_cast\", []() { return 42; });\n    m.def(\"long_cast\", []() { return (long) 42; });\n    m.def(\"longlong_cast\", []() { return ULLONG_MAX; });\n\n    /// test void* cast operator\n    m.def(\"test_void_caster\", []() -> bool {\n        void *v = (void *) 0xabcd;\n        py::object o = py::cast(v);\n        return py::cast<void *>(o) == v;\n    });\n\n    // Tests const/non-const propagation in cast_op.\n    m.def(\"takes\", [](ConstRefCasted x) { return x.tag; });\n    m.def(\"takes_move\", [](ConstRefCasted &&x) { return x.tag; });\n    m.def(\"takes_ptr\", [](ConstRefCasted *x) { return x->tag; });\n    m.def(\"takes_ref\", [](ConstRefCasted &x) { return x.tag; });\n    m.def(\"takes_ref_wrap\", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; });\n    m.def(\"takes_const_ptr\", [](const ConstRefCasted *x) { return x->tag; });\n    m.def(\"takes_const_ref\", [](const ConstRefCasted &x) { return x.tag; });\n    m.def(\"takes_const_ref_wrap\",\n          [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; });\n\n    PYBIND11_WARNING_POP\n}\n"
  },
  {
    "path": "tests/test_builtin_casters.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\n\nimport env\nfrom pybind11_tests import IncType, UserType\nfrom pybind11_tests import builtin_casters as m\n\n\ndef test_simple_string():\n    assert m.string_roundtrip(\"const char *\") == \"const char *\"\n\n\ndef test_unicode_conversion():\n    \"\"\"Tests unicode conversion and error reporting.\"\"\"\n    assert m.good_utf8_string() == \"Say utf8‽ 🎂 𝐀\"\n    assert m.good_utf16_string() == \"b‽🎂𝐀z\"\n    assert m.good_utf32_string() == \"a𝐀🎂‽z\"\n    assert m.good_wchar_string() == \"a⸘𝐀z\"\n    if hasattr(m, \"has_u8string\"):\n        assert m.good_utf8_u8string() == \"Say utf8‽ 🎂 𝐀\"\n\n    with pytest.raises(UnicodeDecodeError):\n        m.bad_utf8_string()\n\n    with pytest.raises(UnicodeDecodeError):\n        m.bad_utf16_string()\n\n    # These are provided only if they actually fail (they don't when 32-bit)\n    if hasattr(m, \"bad_utf32_string\"):\n        with pytest.raises(UnicodeDecodeError):\n            m.bad_utf32_string()\n    if hasattr(m, \"bad_wchar_string\"):\n        with pytest.raises(UnicodeDecodeError):\n            m.bad_wchar_string()\n    if hasattr(m, \"has_u8string\"):\n        with pytest.raises(UnicodeDecodeError):\n            m.bad_utf8_u8string()\n\n    assert m.u8_Z() == \"Z\"\n    assert m.u8_eacute() == \"é\"\n    assert m.u16_ibang() == \"‽\"\n    assert m.u32_mathbfA() == \"𝐀\"\n    assert m.wchar_heart() == \"♥\"\n    if hasattr(m, \"has_u8string\"):\n        assert m.u8_char8_Z() == \"Z\"\n\n\ndef test_single_char_arguments():\n    \"\"\"Tests failures for passing invalid inputs to char-accepting functions\"\"\"\n\n    def toobig_message(r):\n        return f\"Character code point not in range({r:#x})\"\n\n    toolong_message = \"Expected a character, but multi-character string found\"\n\n    assert m.ord_char(\"a\") == 0x61  # simple ASCII\n    assert m.ord_char_lv(\"b\") == 0x62\n    assert (\n        m.ord_char(\"é\") == 0xE9\n    )  # requires 2 bytes in utf-8, but can be stuffed in a char\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_char(\"Ā\") == 0x100  # requires 2 bytes, doesn't fit in a char\n    assert str(excinfo.value) == toobig_message(0x100)\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_char(\"ab\")\n    assert str(excinfo.value) == toolong_message\n\n    assert m.ord_char16(\"a\") == 0x61\n    assert m.ord_char16(\"é\") == 0xE9\n    assert m.ord_char16_lv(\"ê\") == 0xEA\n    assert m.ord_char16(\"Ā\") == 0x100\n    assert m.ord_char16(\"‽\") == 0x203D\n    assert m.ord_char16(\"♥\") == 0x2665\n    assert m.ord_char16_lv(\"♡\") == 0x2661\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_char16(\"🎂\") == 0x1F382  # requires surrogate pair\n    assert str(excinfo.value) == toobig_message(0x10000)\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_char16(\"aa\")\n    assert str(excinfo.value) == toolong_message\n\n    assert m.ord_char32(\"a\") == 0x61\n    assert m.ord_char32(\"é\") == 0xE9\n    assert m.ord_char32(\"Ā\") == 0x100\n    assert m.ord_char32(\"‽\") == 0x203D\n    assert m.ord_char32(\"♥\") == 0x2665\n    assert m.ord_char32(\"🎂\") == 0x1F382\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_char32(\"aa\")\n    assert str(excinfo.value) == toolong_message\n\n    assert m.ord_wchar(\"a\") == 0x61\n    assert m.ord_wchar(\"é\") == 0xE9\n    assert m.ord_wchar(\"Ā\") == 0x100\n    assert m.ord_wchar(\"‽\") == 0x203D\n    assert m.ord_wchar(\"♥\") == 0x2665\n    if m.wchar_size == 2:\n        with pytest.raises(ValueError) as excinfo:\n            assert m.ord_wchar(\"🎂\") == 0x1F382  # requires surrogate pair\n        assert str(excinfo.value) == toobig_message(0x10000)\n    else:\n        assert m.ord_wchar(\"🎂\") == 0x1F382\n    with pytest.raises(ValueError) as excinfo:\n        assert m.ord_wchar(\"aa\")\n    assert str(excinfo.value) == toolong_message\n\n    if hasattr(m, \"has_u8string\"):\n        assert m.ord_char8(\"a\") == 0x61  # simple ASCII\n        assert m.ord_char8_lv(\"b\") == 0x62\n        assert (\n            m.ord_char8(\"é\") == 0xE9\n        )  # requires 2 bytes in utf-8, but can be stuffed in a char\n        with pytest.raises(ValueError) as excinfo:\n            assert m.ord_char8(\"Ā\") == 0x100  # requires 2 bytes, doesn't fit in a char\n        assert str(excinfo.value) == toobig_message(0x100)\n        with pytest.raises(ValueError) as excinfo:\n            assert m.ord_char8(\"ab\")\n        assert str(excinfo.value) == toolong_message\n\n\ndef test_bytes_to_string():\n    \"\"\"Tests the ability to pass bytes to C++ string-accepting functions.  Note that this is\n    one-way: the only way to return bytes to Python is via the pybind11::bytes class.\"\"\"\n    # Issue #816\n\n    assert m.strlen(b\"hi\") == 2\n    assert m.string_length(b\"world\") == 5\n    assert m.string_length(b\"a\\x00b\") == 3\n    assert m.strlen(b\"a\\x00b\") == 1  # C-string limitation\n\n    # passing in a utf8 encoded string should work\n    assert m.string_length(\"💩\".encode()) == 4\n\n\ndef test_bytearray_to_string():\n    \"\"\"Tests the ability to pass bytearray to C++ string-accepting functions\"\"\"\n    assert m.string_length(bytearray(b\"Hi\")) == 2\n    assert m.strlen(bytearray(b\"bytearray\")) == 9\n    assert m.string_length(bytearray()) == 0\n    assert m.string_length(bytearray(\"🦜\", \"utf-8\", \"strict\")) == 4\n    assert m.string_length(bytearray(b\"\\x80\")) == 1\n\n\n@pytest.mark.skipif(not hasattr(m, \"has_string_view\"), reason=\"no <string_view>\")\ndef test_string_view(capture):\n    \"\"\"Tests support for C++17 string_view arguments and return values\"\"\"\n    assert m.string_view_chars(\"Hi\") == [72, 105]\n    assert m.string_view_chars(\"Hi 🎂\") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]\n    assert m.string_view16_chars(\"Hi 🎂\") == [72, 105, 32, 0xD83C, 0xDF82]\n    assert m.string_view32_chars(\"Hi 🎂\") == [72, 105, 32, 127874]\n    if hasattr(m, \"has_u8string\"):\n        assert m.string_view8_chars(\"Hi\") == [72, 105]\n        assert m.string_view8_chars(\"Hi 🎂\") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82]\n\n    assert m.string_view_return() == \"utf8 secret 🎂\"\n    assert m.string_view16_return() == \"utf16 secret 🎂\"\n    assert m.string_view32_return() == \"utf32 secret 🎂\"\n    if hasattr(m, \"has_u8string\"):\n        assert m.string_view8_return() == \"utf8 secret 🎂\"\n\n    with capture:\n        m.string_view_print(\"Hi\")\n        m.string_view_print(\"utf8 🎂\")\n        m.string_view16_print(\"utf16 🎂\")\n        m.string_view32_print(\"utf32 🎂\")\n    assert (\n        capture\n        == \"\"\"\n        Hi 2\n        utf8 🎂 9\n        utf16 🎂 8\n        utf32 🎂 7\n    \"\"\"\n    )\n    if hasattr(m, \"has_u8string\"):\n        with capture:\n            m.string_view8_print(\"Hi\")\n            m.string_view8_print(\"utf8 🎂\")\n        assert (\n            capture\n            == \"\"\"\n            Hi 2\n            utf8 🎂 9\n        \"\"\"\n        )\n\n    with capture:\n        m.string_view_print(\"Hi, ascii\")\n        m.string_view_print(\"Hi, utf8 🎂\")\n        m.string_view16_print(\"Hi, utf16 🎂\")\n        m.string_view32_print(\"Hi, utf32 🎂\")\n    assert (\n        capture\n        == \"\"\"\n        Hi, ascii 9\n        Hi, utf8 🎂 13\n        Hi, utf16 🎂 12\n        Hi, utf32 🎂 11\n    \"\"\"\n    )\n    if hasattr(m, \"has_u8string\"):\n        with capture:\n            m.string_view8_print(\"Hi, ascii\")\n            m.string_view8_print(\"Hi, utf8 🎂\")\n        assert (\n            capture\n            == \"\"\"\n            Hi, ascii 9\n            Hi, utf8 🎂 13\n        \"\"\"\n        )\n\n    assert m.string_view_bytes() == b\"abc \\x80\\x80 def\"\n    assert m.string_view_str() == \"abc ‽ def\"\n    assert m.string_view_from_bytes(\"abc ‽ def\".encode()) == \"abc ‽ def\"\n    if hasattr(m, \"has_u8string\"):\n        assert m.string_view8_str() == \"abc ‽ def\"\n    assert m.string_view_memoryview() == \"Have some 🎂\".encode()\n\n    assert m.bytes_from_type_with_both_operator_string_and_string_view() == b\"success\"\n    assert m.str_from_type_with_both_operator_string_and_string_view() == \"success\"\n\n\ndef test_integer_casting():\n    \"\"\"Issue #929 - out-of-range integer values shouldn't be accepted\"\"\"\n    assert m.i32_str(-1) == \"-1\"\n    assert m.i64_str(-1) == \"-1\"\n    assert m.i32_str(2000000000) == \"2000000000\"\n    assert m.u32_str(2000000000) == \"2000000000\"\n    assert m.i64_str(-999999999999) == \"-999999999999\"\n    assert m.u64_str(999999999999) == \"999999999999\"\n\n    with pytest.raises(TypeError) as excinfo:\n        m.u32_str(-1)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.u64_str(-1)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.i32_str(-3000000000)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.i32_str(3000000000)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n\ndef test_int_convert(doc):\n    class Int:\n        def __int__(self):\n            return 42\n\n    class NotInt:\n        pass\n\n    class Float:\n        def __float__(self):\n            return 41.99999\n\n    class Index:\n        def __index__(self):\n            return 42\n\n    class IntAndIndex:\n        def __int__(self):\n            return 42\n\n        def __index__(self):\n            return 0\n\n    class RaisingTypeErrorOnIndex:\n        def __index__(self):\n            raise TypeError\n\n        def __int__(self):\n            return 42\n\n    class RaisingValueErrorOnIndex:\n        def __index__(self):\n            raise ValueError\n\n        def __int__(self):\n            return 42\n\n    convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert\n\n    assert (\n        doc(convert)\n        == \"int_passthrough(arg0: typing.SupportsInt | typing.SupportsIndex) -> int\"\n    )\n    assert doc(noconvert) == \"int_passthrough_noconvert(arg0: int) -> int\"\n\n    def requires_conversion(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    def cant_convert(v):\n        pytest.raises(TypeError, convert, v)\n\n    assert convert(7) == 7\n    assert noconvert(7) == 7\n    cant_convert(3.14159)\n    # TODO: Avoid DeprecationWarning in `PyLong_AsLong` (and similar)\n    # TODO: PyPy 3.8 does not behave like CPython 3.8 here yet (7.3.7)\n    if sys.version_info < (3, 10) and env.CPYTHON:\n        with pytest.deprecated_call():\n            assert convert(Int()) == 42\n    else:\n        assert convert(Int()) == 42\n    requires_conversion(Int())\n    cant_convert(NotInt())\n    cant_convert(Float())\n\n    # Before Python 3.8, `PyLong_AsLong` does not pick up on `obj.__index__`,\n    # but pybind11 \"backports\" this behavior.\n    assert convert(Index()) == 42\n    assert isinstance(convert(Index()), int)\n    assert noconvert(Index()) == 42\n    assert convert(IntAndIndex()) == 0  # Fishy; `int(DoubleThought)` == 42\n    assert noconvert(IntAndIndex()) == 0\n    assert convert(RaisingTypeErrorOnIndex()) == 42\n    requires_conversion(RaisingTypeErrorOnIndex())\n    assert convert(RaisingValueErrorOnIndex()) == 42\n    requires_conversion(RaisingValueErrorOnIndex())\n\n    class IndexReturnsFloat:\n        def __index__(self):\n            return 3.14  # noqa: PLE0305  Wrong: should return int\n\n    class IntReturnsFloat:\n        def __int__(self):\n            return 3.14  # Wrong: should return int\n\n    class IndexFloatIntInt:\n        def __index__(self):\n            return 3.14  # noqa: PLE0305  Wrong: should return int\n\n        def __int__(self):\n            return 42  # Correct: returns int\n\n    class IndexIntIntFloat:\n        def __index__(self):\n            return 42  # Correct: returns int\n\n        def __int__(self):\n            return 3.14  # Wrong: should return int\n\n    class IndexFloatIntFloat:\n        def __index__(self):\n            return 3.14  # noqa: PLE0305  Wrong: should return int\n\n        def __int__(self):\n            return 2.71  # Wrong: should return int\n\n    cant_convert(IndexReturnsFloat())\n    requires_conversion(IndexReturnsFloat())\n\n    cant_convert(IntReturnsFloat())\n    requires_conversion(IntReturnsFloat())\n\n    assert convert(IndexFloatIntInt()) == 42  # convert: __index__ fails, uses __int__\n    requires_conversion(IndexFloatIntInt())  # noconvert: __index__ fails, no fallback\n\n    assert convert(IndexIntIntFloat()) == 42  # convert: __index__ succeeds\n    assert noconvert(IndexIntIntFloat()) == 42  # noconvert: __index__ succeeds\n\n    cant_convert(IndexFloatIntFloat())  # convert mode rejects (both fail)\n    requires_conversion(IndexFloatIntFloat())  # noconvert mode also rejects\n\n\ndef test_float_convert(doc):\n    class Int:\n        def __int__(self):\n            return -5\n\n    class Index:\n        def __index__(self) -> int:\n            return -7\n\n    class Float:\n        def __float__(self):\n            return 41.45\n\n    convert, noconvert = m.float_passthrough, m.float_passthrough_noconvert\n    assert (\n        doc(convert)\n        == \"float_passthrough(arg0: typing.SupportsFloat | typing.SupportsIndex) -> float\"\n    )\n    assert doc(noconvert) == \"float_passthrough_noconvert(arg0: float) -> float\"\n\n    def requires_conversion(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    def cant_convert(v):\n        pytest.raises(TypeError, convert, v)\n\n    requires_conversion(Float())\n    requires_conversion(Index())\n    assert pytest.approx(convert(Float())) == 41.45\n    assert pytest.approx(convert(Index())) == -7.0\n    assert isinstance(convert(Float()), float)\n    assert pytest.approx(convert(3)) == 3.0\n    assert pytest.approx(noconvert(3)) == 3.0\n    cant_convert(Int())\n\n\ndef test_numpy_int_convert():\n    np = pytest.importorskip(\"numpy\")\n\n    convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert\n\n    def require_implicit(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    # `np.intc` is an alias that corresponds to a C++ `int`\n    assert convert(np.intc(42)) == 42\n    assert noconvert(np.intc(42)) == 42\n\n    # The implicit conversion from np.float32 is undesirable but currently accepted.\n    # TODO: Avoid DeprecationWarning in `PyLong_AsLong` (and similar)\n    # TODO: PyPy 3.8 does not behave like CPython 3.8 here yet (7.3.7)\n    # https://github.com/pybind/pybind11/issues/3408\n    if (3, 8) <= sys.version_info < (3, 10) and env.CPYTHON:\n        with pytest.deprecated_call():\n            assert convert(np.float32(3.14159)) == 3\n    else:\n        assert convert(np.float32(3.14159)) == 3\n    require_implicit(np.float32(3.14159))\n\n\ndef test_tuple(doc):\n    \"\"\"std::pair <-> tuple & std::tuple <-> tuple\"\"\"\n    assert m.pair_passthrough((True, \"test\")) == (\"test\", True)\n    assert m.tuple_passthrough((True, \"test\", 5)) == (5, \"test\", True)\n    # Any sequence can be cast to a std::pair or std::tuple\n    assert m.pair_passthrough([True, \"test\"]) == (\"test\", True)\n    assert m.tuple_passthrough([True, \"test\", 5]) == (5, \"test\", True)\n    assert m.empty_tuple() == ()\n\n    assert (\n        doc(m.pair_passthrough)\n        == \"\"\"\n        pair_passthrough(arg0: tuple[bool, str]) -> tuple[str, bool]\n\n        Return a pair in reversed order\n    \"\"\"\n    )\n    assert (\n        doc(m.tuple_passthrough)\n        == \"\"\"\n        tuple_passthrough(arg0: tuple[bool, str, typing.SupportsInt | typing.SupportsIndex]) -> tuple[int, str, bool]\n\n        Return a triple in reversed order\n    \"\"\"\n    )\n\n    assert doc(m.empty_tuple) == \"\"\"empty_tuple() -> tuple[()]\"\"\"\n\n    assert m.rvalue_pair() == (\"rvalue\", \"rvalue\")\n    assert m.lvalue_pair() == (\"lvalue\", \"lvalue\")\n    assert m.rvalue_tuple() == (\"rvalue\", \"rvalue\", \"rvalue\")\n    assert m.lvalue_tuple() == (\"lvalue\", \"lvalue\", \"lvalue\")\n    assert m.rvalue_nested() == (\"rvalue\", (\"rvalue\", (\"rvalue\", \"rvalue\")))\n    assert m.lvalue_nested() == (\"lvalue\", (\"lvalue\", (\"lvalue\", \"lvalue\")))\n\n    assert m.int_string_pair() == (2, \"items\")\n\n\ndef test_builtins_cast_return_none():\n    \"\"\"Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None\"\"\"\n    assert m.return_none_string() is None\n    assert m.return_none_char() is None\n    assert m.return_none_bool() is None\n    assert m.return_none_int() is None\n    assert m.return_none_float() is None\n    assert m.return_none_pair() is None\n\n\ndef test_none_deferred():\n    \"\"\"None passed as various argument types should defer to other overloads\"\"\"\n    assert not m.defer_none_cstring(\"abc\")\n    assert m.defer_none_cstring(None)\n    assert not m.defer_none_custom(UserType())\n    assert m.defer_none_custom(None)\n    assert m.nodefer_none_void(None)\n\n\ndef test_void_caster():\n    assert m.load_nullptr_t(None) is None\n    assert m.cast_nullptr_t() is None\n\n\ndef test_reference_wrapper():\n    \"\"\"std::reference_wrapper for builtin and user types\"\"\"\n    assert m.refwrap_builtin(42) == 420\n    assert m.refwrap_usertype(UserType(42)) == 42\n    assert m.refwrap_usertype_const(UserType(42)) == 42\n\n    with pytest.raises(TypeError) as excinfo:\n        m.refwrap_builtin(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.refwrap_usertype(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    assert m.refwrap_lvalue().value == 1\n    assert m.refwrap_lvalue_const().value == 1\n\n    a1 = m.refwrap_list(copy=True)\n    a2 = m.refwrap_list(copy=True)\n    assert [x.value for x in a1] == [2, 3]\n    assert [x.value for x in a2] == [2, 3]\n    assert a1[0] is not a2[0]\n    assert a1[1] is not a2[1]\n\n    b1 = m.refwrap_list(copy=False)\n    b2 = m.refwrap_list(copy=False)\n    assert [x.value for x in b1] == [1, 2]\n    assert [x.value for x in b2] == [1, 2]\n    assert b1[0] is b2[0]\n    assert b1[1] is b2[1]\n\n    assert m.refwrap_iiw(IncType(5)) == 5\n    assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10]\n\n\ndef test_complex_cast(doc):\n    \"\"\"std::complex casts\"\"\"\n\n    class Complex:\n        def __complex__(self) -> complex:\n            return complex(5, 4)\n\n    class Float:\n        def __float__(self) -> float:\n            return 5.0\n\n    class Int:\n        def __int__(self) -> int:\n            return 3\n\n    class Index:\n        def __index__(self) -> int:\n            return 1\n\n    assert m.complex_cast(1) == \"1.0\"\n    assert m.complex_cast(1.0) == \"1.0\"\n    assert m.complex_cast(Complex()) == \"(5.0, 4.0)\"\n    assert m.complex_cast(2j) == \"(0.0, 2.0)\"\n\n    assert m.complex_cast_strict(1) == \"(1.0, 0.0)\"\n    assert m.complex_cast_strict(3.0) == \"(3.0, 0.0)\"\n    assert m.complex_cast_strict(complex(5, 4)) == \"(5.0, 4.0)\"\n    assert m.complex_cast_strict(2j) == \"(0.0, 2.0)\"\n\n    convert, noconvert = m.complex_convert, m.complex_noconvert\n\n    def requires_conversion(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    def cant_convert(v):\n        pytest.raises(TypeError, convert, v)\n\n    assert (\n        doc(convert)\n        == \"complex_convert(arg0: typing.SupportsComplex | typing.SupportsFloat | typing.SupportsIndex) -> complex\"\n    )\n    assert doc(noconvert) == \"complex_noconvert(arg0: complex) -> complex\"\n\n    assert convert(1) == 1.0\n    assert convert(2.0) == 2.0\n    assert convert(1 + 5j) == 1.0 + 5.0j\n    assert convert(Complex()) == 5.0 + 4j\n    assert convert(Float()) == 5.0\n    assert isinstance(convert(Float()), complex)\n    cant_convert(Int())\n    assert convert(Index()) == 1\n    assert isinstance(convert(Index()), complex)\n\n    assert noconvert(1) == 1.0\n    assert noconvert(2.0) == 2.0\n    assert noconvert(1 + 5j) == 1.0 + 5.0j\n    requires_conversion(Complex())\n    requires_conversion(Float())\n    requires_conversion(Index())\n\n\ndef test_complex_index_handling():\n    \"\"\"\n    Test __index__ handling in complex caster (added with PR #5879).\n\n    This test verifies that custom __index__ objects (not PyLong) work correctly\n    with complex conversion. The behavior should be consistent across CPython,\n    PyPy, and GraalPy.\n\n    - Custom __index__ objects work with convert (non-strict mode)\n    - Custom __index__ objects do NOT work with noconvert (strict mode)\n    - Regular int (PyLong) works with both convert and noconvert\n    \"\"\"\n\n    class CustomIndex:\n        \"\"\"Custom class with __index__ but not __int__ or __float__\"\"\"\n\n        def __index__(self) -> int:\n            return 42\n\n    class CustomIndexNegative:\n        \"\"\"Custom class with negative __index__\"\"\"\n\n        def __index__(self) -> int:\n            return -17\n\n    convert, noconvert = m.complex_convert, m.complex_noconvert\n\n    # Test that regular int (PyLong) works\n    assert convert(5) == 5.0 + 0j\n    assert noconvert(5) == 5.0 + 0j\n\n    # Test that custom __index__ objects work with convert (non-strict mode)\n    # This exercises the PyPy-specific path in complex.h\n    assert convert(CustomIndex()) == 42.0 + 0j\n    assert convert(CustomIndexNegative()) == -17.0 + 0j\n\n    # With noconvert (strict mode), custom __index__ objects are NOT accepted\n    # Strict mode only accepts complex, float, or int (PyLong), not custom __index__ objects\n    def requires_conversion(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    requires_conversion(CustomIndex())\n    requires_conversion(CustomIndexNegative())\n\n    # Verify the result is actually a complex\n    result = convert(CustomIndex())\n    assert isinstance(result, complex)\n    assert result.real == 42.0\n    assert result.imag == 0.0\n\n\ndef test_overload_resolution_float_int():\n    \"\"\"\n    Test overload resolution behavior when int can match float (added with PR #5879).\n\n    This test documents the breaking change in PR #5879: when a float overload is\n    registered before an int overload, passing a Python int will now match the float\n    overload (because int can be converted to float in strict mode per PEP 484).\n\n    Before PR #5879: int(42) would match int overload (if both existed)\n    After PR #5879: int(42) matches float overload (if registered first)\n\n    This is a breaking change because existing code that relied on int matching\n    int overloads may now match float overloads instead.\n    \"\"\"\n    # Test 1: float overload registered first, int second\n    # When passing int(42), pybind11 tries overloads in order:\n    # 1. float overload - can int(42) be converted? Yes (with PR #5879 changes)\n    # 2. Match! Use float overload (int overload never checked)\n    result = m.overload_resolution_test(42)\n    assert result == \"float: 42.000000\", (\n        f\"Expected int(42) to match float overload, got: {result}. \"\n        \"This documents the breaking change: int now matches float overloads.\"\n    )\n    assert m.overload_resolution_test(42.0) == \"float: 42.000000\"\n\n    # Test 2: With noconvert (strict mode) - this is the KEY breaking change\n    # Before PR #5879: int(42) would NOT match float overload with noconvert, would match int overload\n    # After PR #5879: int(42) DOES match float overload with noconvert (because int->float is now allowed)\n    result_strict = m.overload_resolution_strict(42)\n    assert result_strict == \"float_strict: 42.000000\", (\n        f\"Expected int(42) to match float overload with noconvert, got: {result_strict}. \"\n        \"This is the key breaking change: int now matches float even in strict mode.\"\n    )\n    assert m.overload_resolution_strict(42.0) == \"float_strict: 42.000000\"\n\n    # Test 3: complex overload registered first, then float, then int\n    # When passing int(5), pybind11 tries overloads in order:\n    # 1. complex overload - can int(5) be converted? Yes (with PR #5879 changes)\n    # 2. Match! Use complex overload\n    assert m.overload_resolution_complex(5) == \"complex: (5.000000, 0.000000)\"\n    assert m.overload_resolution_complex(5.0) == \"complex: (5.000000, 0.000000)\"\n    assert (\n        m.overload_resolution_complex(complex(3, 4)) == \"complex: (3.000000, 4.000000)\"\n    )\n\n    # Verify that the overloads are registered in the expected order\n    # The docstring should show float overload before int overload\n    doc = m.overload_resolution_test.__doc__\n    assert doc is not None\n    # Check that float overload appears before int overload in docstring\n    # The docstring uses \"typing.SupportsFloat\" and \"typing.SupportsInt\"\n    float_pos = doc.find(\"SupportsFloat\")\n    int_pos = doc.find(\"SupportsInt\")\n    assert float_pos != -1, f\"Could not find 'SupportsFloat' in docstring: {doc}\"\n    assert int_pos != -1, f\"Could not find 'SupportsInt' in docstring: {doc}\"\n    assert float_pos < int_pos, (\n        f\"Float overload should appear before int overload in docstring. \"\n        f\"Found 'SupportsFloat' at {float_pos}, 'SupportsInt' at {int_pos}. \"\n        f\"Docstring: {doc}\"\n    )\n\n\ndef test_bool_caster():\n    \"\"\"Test bool caster implicit conversions.\"\"\"\n    convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert\n\n    def require_implicit(v):\n        pytest.raises(TypeError, noconvert, v)\n\n    def cant_convert(v):\n        pytest.raises(TypeError, convert, v)\n\n    # straight up bool\n    assert convert(True) is True\n    assert convert(False) is False\n    assert noconvert(True) is True\n    assert noconvert(False) is False\n\n    # None requires implicit conversion\n    require_implicit(None)\n    assert convert(None) is False\n\n    class A:\n        def __init__(self, x):\n            self.x = x\n\n        def __nonzero__(self):\n            return self.x\n\n        def __bool__(self):\n            return self.x\n\n    class B:\n        pass\n\n    # Arbitrary objects are not accepted\n    cant_convert(object())\n    cant_convert(B())\n\n    # Objects with __nonzero__ / __bool__ defined can be converted\n    require_implicit(A(True))\n    assert convert(A(True)) is True\n    assert convert(A(False)) is False\n\n\ndef test_numpy_bool():\n    np = pytest.importorskip(\"numpy\")\n\n    convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert\n\n    def cant_convert(v):\n        pytest.raises(TypeError, convert, v)\n\n    # np.bool_ is not considered implicit\n    assert convert(np.bool_(True)) is True\n    assert convert(np.bool_(False)) is False\n    assert noconvert(np.bool_(True)) is True\n    assert noconvert(np.bool_(False)) is False\n    cant_convert(np.zeros(2, dtype=\"int\"))\n\n\ndef test_int_long():\n    assert isinstance(m.int_cast(), int)\n    assert isinstance(m.long_cast(), int)\n    assert isinstance(m.longlong_cast(), int)\n\n\ndef test_void_caster_2():\n    assert m.test_void_caster()\n\n\ndef test_const_ref_caster():\n    \"\"\"Verifies that const-ref is propagated through type_caster cast_op.\n    The returned ConstRefCasted type is a minimal type that is constructed to\n    reference the casting mode used.\n    \"\"\"\n    x = False\n    assert m.takes(x) == 1\n    assert m.takes_move(x) == 1\n\n    assert m.takes_ptr(x) == 3\n    assert m.takes_ref(x) == 2\n    assert m.takes_ref_wrap(x) == 2\n\n    assert m.takes_const_ptr(x) == 5\n    assert m.takes_const_ref(x) == 4\n    assert m.takes_const_ref_wrap(x) == 4\n"
  },
  {
    "path": "tests/test_call_policies.cpp",
    "content": "/*\n    tests/test_call_policies.cpp -- keep_alive and call_guard\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nstruct CustomGuard {\n    static bool enabled;\n\n    CustomGuard() { enabled = true; }\n    ~CustomGuard() { enabled = false; }\n\n    static const char *report_status() { return enabled ? \"guarded\" : \"unguarded\"; }\n};\nbool CustomGuard::enabled = false;\n\nstruct DependentGuard {\n    static bool enabled;\n\n    DependentGuard() { enabled = CustomGuard::enabled; }\n    ~DependentGuard() { enabled = false; }\n\n    static const char *report_status() { return enabled ? \"guarded\" : \"unguarded\"; }\n};\nbool DependentGuard::enabled = false;\n\nTEST_SUBMODULE(call_policies, m) {\n    // Parent/Child are used in:\n    // test_keep_alive_argument, test_keep_alive_return_value, test_alive_gc_derived,\n    // test_alive_gc_multi_derived, test_return_none, test_keep_alive_constructor\n    class Child {\n    public:\n        Child() { py::print(\"Allocating child.\"); }\n        Child(const Child &) = default;\n        Child(Child &&) = default;\n        ~Child() { py::print(\"Releasing child.\"); }\n    };\n    py::class_<Child>(m, \"Child\").def(py::init<>());\n\n    class Parent {\n    public:\n        Parent() { py::print(\"Allocating parent.\"); }\n        Parent(const Parent &parent) = default;\n        ~Parent() { py::print(\"Releasing parent.\"); }\n        void addChild(Child *) {}\n        Child *returnChild() { return new Child(); }\n        Child *returnNullChild() { return nullptr; }\n        static Child *staticFunction(Parent *) { return new Child(); }\n    };\n    py::class_<Parent>(m, \"Parent\")\n        .def(py::init<>())\n        .def(py::init([](Child *) { return new Parent(); }), py::keep_alive<1, 2>())\n        .def(\"addChild\", &Parent::addChild)\n        .def(\"addChildKeepAlive\", &Parent::addChild, py::keep_alive<1, 2>())\n        .def(\"returnChild\", &Parent::returnChild)\n        .def(\"returnChildKeepAlive\", &Parent::returnChild, py::keep_alive<1, 0>())\n        .def(\"returnNullChildKeepAliveChild\", &Parent::returnNullChild, py::keep_alive<1, 0>())\n        .def(\"returnNullChildKeepAliveParent\", &Parent::returnNullChild, py::keep_alive<0, 1>())\n        .def_static(\"staticFunction\", &Parent::staticFunction, py::keep_alive<1, 0>());\n\n    m.def(\"free_function\", [](Parent *, Child *) {}, py::keep_alive<1, 2>());\n    m.def(\"invalid_arg_index\", [] {}, py::keep_alive<0, 1>());\n\n#if !defined(PYPY_VERSION)\n    // test_alive_gc\n    class ParentGC : public Parent {\n    public:\n        using Parent::Parent;\n    };\n    py::class_<ParentGC, Parent>(m, \"ParentGC\", py::dynamic_attr()).def(py::init<>());\n#endif\n\n    // test_call_guard\n    m.def(\"unguarded_call\", &CustomGuard::report_status);\n    m.def(\"guarded_call\", &CustomGuard::report_status, py::call_guard<CustomGuard>());\n\n    m.def(\n        \"multiple_guards_correct_order\",\n        []() {\n            return CustomGuard::report_status() + std::string(\" & \")\n                   + DependentGuard::report_status();\n        },\n        py::call_guard<CustomGuard, DependentGuard>());\n\n    m.def(\n        \"multiple_guards_wrong_order\",\n        []() {\n            return DependentGuard::report_status() + std::string(\" & \")\n                   + CustomGuard::report_status();\n        },\n        py::call_guard<DependentGuard, CustomGuard>());\n\n#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)\n    // `py::call_guard<py::gil_scoped_release>()` should work in PyPy/GraalPy as well,\n    // but it's unclear how to test it without `PyGILState_GetThisThreadState`.\n    auto report_gil_status = []() {\n        auto is_gil_held = false;\n        if (auto *tstate = py::detail::get_thread_state_unchecked()) {\n            is_gil_held = (tstate == PyGILState_GetThisThreadState());\n        }\n\n        return is_gil_held ? \"GIL held\" : \"GIL released\";\n    };\n\n    m.def(\"with_gil\", report_gil_status);\n    m.def(\"without_gil\", report_gil_status, py::call_guard<py::gil_scoped_release>());\n#endif\n}\n"
  },
  {
    "path": "tests/test_call_policies.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import call_policies as m\n\n\n@pytest.mark.xfail(\"env.PYPY\", reason=\"sometimes comes out 1 off on PyPy\", strict=False)\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_keep_alive_argument(capture):\n    n_inst = ConstructorStats.detail_reg_inst()\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.addChild(m.Child())\n        assert ConstructorStats.detail_reg_inst() == n_inst + 1\n    assert (\n        capture\n        == \"\"\"\n        Allocating child.\n        Releasing child.\n    \"\"\"\n    )\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert capture == \"Releasing parent.\"\n\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.addChildKeepAlive(m.Child())\n        assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    assert capture == \"Allocating child.\"\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n    p = m.Parent()\n    c = m.Child()\n    assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    m.free_function(p, c)\n    del c\n    assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    del p\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.invalid_arg_index()\n    assert str(excinfo.value) == \"Could not activate keep_alive!\"\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_keep_alive_return_value(capture):\n    n_inst = ConstructorStats.detail_reg_inst()\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.returnChild()\n        assert ConstructorStats.detail_reg_inst() == n_inst + 1\n    assert (\n        capture\n        == \"\"\"\n        Allocating child.\n        Releasing child.\n    \"\"\"\n    )\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert capture == \"Releasing parent.\"\n\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.returnChildKeepAlive()\n        assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    assert capture == \"Allocating child.\"\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n    p = m.Parent()\n    assert ConstructorStats.detail_reg_inst() == n_inst + 1\n    with capture:\n        m.Parent.staticFunction(p)\n        assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    assert capture == \"Allocating child.\"\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2447\n@pytest.mark.xfail(\"env.PYPY\", reason=\"_PyObject_GetDictPtr is unimplemented\")\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_alive_gc(capture):\n    n_inst = ConstructorStats.detail_reg_inst()\n    p = m.ParentGC()\n    p.addChildKeepAlive(m.Child())\n    assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    lst = [p]\n    lst.append(lst)  # creates a circular reference\n    with capture:\n        del p, lst\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_alive_gc_derived(capture):\n    class Derived(m.Parent):\n        pass\n\n    n_inst = ConstructorStats.detail_reg_inst()\n    p = Derived()\n    p.addChildKeepAlive(m.Child())\n    assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    lst = [p]\n    lst.append(lst)  # creates a circular reference\n    with capture:\n        del p, lst\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_alive_gc_multi_derived(capture):\n    class Derived(m.Parent, m.Child):\n        def __init__(self):\n            m.Parent.__init__(self)\n            m.Child.__init__(self)\n\n    n_inst = ConstructorStats.detail_reg_inst()\n    p = Derived()\n    p.addChildKeepAlive(m.Child())\n    # +3 rather than +2 because Derived corresponds to two registered instances\n    assert ConstructorStats.detail_reg_inst() == n_inst + 3\n    lst = [p]\n    lst.append(lst)  # creates a circular reference\n    with capture:\n        del p, lst\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n        Releasing child.\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_return_none(capture):\n    n_inst = ConstructorStats.detail_reg_inst()\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.returnNullChildKeepAliveChild()\n        assert ConstructorStats.detail_reg_inst() == n_inst + 1\n    assert capture == \"\"\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert capture == \"Releasing parent.\"\n\n    with capture:\n        p = m.Parent()\n    assert capture == \"Allocating parent.\"\n    with capture:\n        p.returnNullChildKeepAliveParent()\n        assert ConstructorStats.detail_reg_inst() == n_inst + 1\n    assert capture == \"\"\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert capture == \"Releasing parent.\"\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_keep_alive_constructor(capture):\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    with capture:\n        p = m.Parent(m.Child())\n        assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    assert (\n        capture\n        == \"\"\"\n        Allocating child.\n        Allocating parent.\n    \"\"\"\n    )\n    with capture:\n        del p\n        assert ConstructorStats.detail_reg_inst() == n_inst\n    assert (\n        capture\n        == \"\"\"\n        Releasing parent.\n        Releasing child.\n    \"\"\"\n    )\n\n\ndef test_call_guard():\n    assert m.unguarded_call() == \"unguarded\"\n    assert m.guarded_call() == \"guarded\"\n\n    assert m.multiple_guards_correct_order() == \"guarded & guarded\"\n    assert m.multiple_guards_wrong_order() == \"unguarded & guarded\"\n\n    if hasattr(m, \"with_gil\"):\n        assert m.with_gil() == \"GIL held\"\n        assert m.without_gil() == \"GIL released\"\n"
  },
  {
    "path": "tests/test_callbacks.cpp",
    "content": "/*\n    tests/test_callbacks.cpp -- callbacks\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/functional.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <thread>\n\nnamespace test_callbacks {\nnamespace boost_histogram { // See PR #5580\n\ndouble custom_transform_double(double value) { return value * 3; }\nint custom_transform_int(int value) { return value; }\n\n// Originally derived from\n// https://github.com/scikit-hep/boost-histogram/blob/460ef90905d6a8a9e6dd3beddfe7b4b49b364579/include/bh_python/transform.hpp#L68-L85\ndouble apply_custom_transform(const py::object &src, double value) {\n    using raw_t = double(double);\n\n    py::detail::make_caster<std::function<raw_t>> func_caster;\n    if (!func_caster.load(src, /*convert*/ false)) {\n        return -100;\n    }\n    auto func = static_cast<std::function<raw_t> &>(func_caster);\n    auto *cfunc = func.target<raw_t *>();\n    if (cfunc == nullptr) {\n        return -200;\n    }\n    return (*cfunc)(value);\n}\n\n} // namespace boost_histogram\n} // namespace test_callbacks\n\nint dummy_function(int i) { return i + 1; }\n\nTEST_SUBMODULE(callbacks, m) {\n    // test_callbacks, test_function_signatures\n    m.def(\"test_callback1\", [](const py::object &func) { return func(); });\n    m.def(\"test_callback2\", [](const py::object &func) { return func(\"Hello\", 'x', true, 5); });\n    m.def(\"test_callback3\", [](const std::function<int(int)> &func) {\n        return \"func(43) = \" + std::to_string(func(43));\n    });\n    m.def(\"test_callback4\",\n          []() -> std::function<int(int)> { return [](int i) { return i + 1; }; });\n    m.def(\"test_callback5\",\n          []() { return py::cpp_function([](int i) { return i + 1; }, py::arg(\"number\")); });\n\n    // test_keyword_args_and_generalized_unpacking\n    m.def(\"test_tuple_unpacking\", [](const py::function &f) {\n        auto t1 = py::make_tuple(2, 3);\n        auto t2 = py::make_tuple(5, 6);\n        return f(\"positional\", 1, *t1, 4, *t2);\n    });\n\n    m.def(\"test_dict_unpacking\", [](const py::function &f) {\n        auto d1 = py::dict(\"key\"_a = \"value\", \"a\"_a = 1);\n        auto d2 = py::dict();\n        auto d3 = py::dict(\"b\"_a = 2);\n        return f(\"positional\", 1, **d1, **d2, **d3);\n    });\n\n    m.def(\"test_keyword_args\", [](const py::function &f) { return f(\"x\"_a = 10, \"y\"_a = 20); });\n\n    m.def(\"test_unpacking_and_keywords1\", [](const py::function &f) {\n        auto args = py::make_tuple(2);\n        auto kwargs = py::dict(\"d\"_a = 4);\n        return f(1, *args, \"c\"_a = 3, **kwargs);\n    });\n\n    m.def(\"test_unpacking_and_keywords2\", [](const py::function &f) {\n        auto kwargs1 = py::dict(\"a\"_a = 1);\n        auto kwargs2 = py::dict(\"c\"_a = 3, \"d\"_a = 4);\n        return f(\"positional\",\n                 *py::make_tuple(1),\n                 2,\n                 *py::make_tuple(3, 4),\n                 5,\n                 \"key\"_a = \"value\",\n                 **kwargs1,\n                 \"b\"_a = 2,\n                 **kwargs2,\n                 \"e\"_a = 5);\n    });\n\n    m.def(\"test_unpacking_error1\", [](const py::function &f) {\n        auto kwargs = py::dict(\"x\"_a = 3);\n        return f(\"x\"_a = 1, \"y\"_a = 2, **kwargs); // duplicate ** after keyword\n    });\n\n    m.def(\"test_unpacking_error2\", [](const py::function &f) {\n        auto kwargs = py::dict(\"x\"_a = 3);\n        return f(**kwargs, \"x\"_a = 1); // duplicate keyword after **\n    });\n\n    m.def(\"test_arg_conversion_error1\",\n          [](const py::function &f) { f(234, UnregisteredType(), \"kw\"_a = 567); });\n\n    m.def(\"test_arg_conversion_error2\", [](const py::function &f) {\n        f(234, \"expected_name\"_a = UnregisteredType(), \"kw\"_a = 567);\n    });\n\n    // test_lambda_closure_cleanup\n    struct Payload {\n        Payload() { print_default_created(this); }\n        ~Payload() { print_destroyed(this); }\n        Payload(const Payload &) { print_copy_created(this); }\n        Payload(Payload &&) noexcept { print_move_created(this); }\n    };\n    // Export the payload constructor statistics for testing purposes:\n    m.def(\"payload_cstats\", &ConstructorStats::get<Payload>);\n    m.def(\"test_lambda_closure_cleanup\", []() -> std::function<void()> {\n        Payload p;\n\n        // In this situation, `Func` in the implementation of\n        // `cpp_function::initialize` is NOT trivially destructible.\n        return [p]() {\n            /* p should be cleaned up when the returned function is garbage collected */\n            (void) p;\n        };\n    });\n\n    class CppCallable {\n    public:\n        CppCallable() { track_default_created(this); }\n        ~CppCallable() { track_destroyed(this); }\n        CppCallable(const CppCallable &) { track_copy_created(this); }\n        CppCallable(CppCallable &&) noexcept { track_move_created(this); }\n        void operator()() {}\n    };\n\n    m.def(\"test_cpp_callable_cleanup\", []() {\n        // Related issue: https://github.com/pybind/pybind11/issues/3228\n        // Related PR: https://github.com/pybind/pybind11/pull/3229\n        py::list alive_counts;\n        ConstructorStats &stat = ConstructorStats::get<CppCallable>();\n        alive_counts.append(stat.alive());\n        {\n            CppCallable cpp_callable;\n            alive_counts.append(stat.alive());\n            {\n                // In this situation, `Func` in the implementation of\n                // `cpp_function::initialize` IS trivially destructible,\n                // only `capture` is not.\n                py::cpp_function py_func(cpp_callable);\n                py::detail::silence_unused_warnings(py_func);\n                alive_counts.append(stat.alive());\n            }\n            alive_counts.append(stat.alive());\n            {\n                py::cpp_function py_func(std::move(cpp_callable));\n                py::detail::silence_unused_warnings(py_func);\n                alive_counts.append(stat.alive());\n            }\n            alive_counts.append(stat.alive());\n        }\n        alive_counts.append(stat.alive());\n        return alive_counts;\n    });\n\n    // test_cpp_function_roundtrip\n    /* Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer */\n    m.def(\"dummy_function\", &dummy_function);\n    m.def(\"dummy_function_overloaded\", [](int i, int j) { return i + j; });\n    m.def(\"dummy_function_overloaded\", &dummy_function);\n    m.def(\"dummy_function2\", [](int i, int j) { return i + j; });\n    m.def(\n        \"roundtrip\",\n        [](std::function<int(int)> f, bool expect_none) {\n            if (expect_none && f) {\n                throw std::runtime_error(\"Expected None to be converted to empty std::function\");\n            }\n            return f;\n        },\n        py::arg(\"f\"),\n        py::arg(\"expect_none\") = false);\n    m.def(\"test_dummy_function\", [](const std::function<int(int)> &f) -> std::string {\n        using fn_type = int (*)(int);\n        const auto *result = f.target<fn_type>();\n        if (!result) {\n            auto r = f(1);\n            return \"can't convert to function pointer: eval(1) = \" + std::to_string(r);\n        }\n        if (*result == dummy_function) {\n            auto r = (*result)(1);\n            return \"matches dummy_function: eval(1) = \" + std::to_string(r);\n        }\n        return \"argument does NOT match dummy_function. This should never happen!\";\n    });\n\n    class AbstractBase {\n    public:\n        // [workaround(intel)] = default does not work here\n        // Defaulting this destructor results in linking errors with the Intel compiler\n        // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)\n        virtual ~AbstractBase() {} // NOLINT(modernize-use-equals-default)\n        virtual unsigned int func() = 0;\n    };\n    m.def(\"func_accepting_func_accepting_base\",\n          [](const std::function<double(AbstractBase &)> &) {});\n\n    struct MovableObject {\n        bool valid = true;\n\n        MovableObject() = default;\n        MovableObject(const MovableObject &) = default;\n        MovableObject &operator=(const MovableObject &) = default;\n        MovableObject(MovableObject &&o) noexcept : valid(o.valid) { o.valid = false; }\n        MovableObject &operator=(MovableObject &&o) noexcept {\n            valid = o.valid;\n            o.valid = false;\n            return *this;\n        }\n    };\n    py::class_<MovableObject>(m, \"MovableObject\");\n\n    // test_movable_object\n    m.def(\"callback_with_movable\", [](const std::function<void(MovableObject &)> &f) {\n        auto x = MovableObject();\n        f(x);           // lvalue reference shouldn't move out object\n        return x.valid; // must still return `true`\n    });\n\n    // test_bound_method_callback\n    struct CppBoundMethodTest {};\n    py::class_<CppBoundMethodTest>(m, \"CppBoundMethodTest\")\n        .def(py::init<>())\n        .def(\"triple\", [](CppBoundMethodTest &, int val) { return 3 * val; });\n\n    // This checks that builtin functions can be passed as callbacks\n    // rather than throwing RuntimeError due to trying to extract as capsule\n    m.def(\"test_sum_builtin\",\n          [](const std::function<double(py::iterable)> &sum_builtin, const py::iterable &i) {\n              return sum_builtin(i);\n          });\n\n    // test async Python callbacks\n    using callback_f = std::function<void(int)>;\n    m.def(\"test_async_callback\", [](const callback_f &f, const py::list &work) {\n        // make detached thread that calls `f` with piece of work after a little delay\n        auto start_f = [f](int j) {\n            auto invoke_f = [f, j] {\n                std::this_thread::sleep_for(std::chrono::milliseconds(50));\n                f(j);\n            };\n            auto t = std::thread(std::move(invoke_f));\n            t.detach();\n        };\n\n        // spawn worker threads\n        for (auto i : work) {\n            start_f(py::cast<int>(i));\n        }\n    });\n\n    m.def(\"callback_num_times\", [](const py::function &f, std::size_t num) {\n        for (std::size_t i = 0; i < num; i++) {\n            f();\n        }\n    });\n\n    auto *custom_def = []() {\n        static PyMethodDef def;\n        def.ml_name = \"example_name\";\n        def.ml_doc = \"Example doc\";\n        def.ml_meth = [](PyObject *, PyObject *args) -> PyObject * {\n            if (PyTuple_Size(args) != 1) {\n                throw std::runtime_error(\"Invalid number of arguments for example_name\");\n            }\n            PyObject *first = PyTuple_GetItem(args, 0);\n            if (!PyLong_Check(first)) {\n                throw std::runtime_error(\"Invalid argument to example_name\");\n            }\n            auto result = py::cast(PyLong_AsLong(first) * 9);\n            return result.release().ptr();\n        };\n        def.ml_flags = METH_VARARGS;\n        return &def;\n    }();\n\n    py::capsule rec_capsule(std::malloc(1), [](void *data) { std::free(data); });\n    m.add_object(\"custom_function\", PyCFunction_New(custom_def, rec_capsule.ptr()));\n\n    // rec_capsule with nullptr name\n    py::capsule rec_capsule2(std::malloc(1), [](void *data) { std::free(data); });\n    m.add_object(\"custom_function2\", PyCFunction_New(custom_def, rec_capsule2.ptr()));\n\n    m.def(\"boost_histogram_custom_transform_double\",\n          test_callbacks::boost_histogram::custom_transform_double);\n    m.def(\"boost_histogram_custom_transform_int\",\n          test_callbacks::boost_histogram::custom_transform_int);\n    m.def(\"boost_histogram_apply_custom_transform\",\n          test_callbacks::boost_histogram::apply_custom_transform);\n}\n"
  },
  {
    "path": "tests/test_callbacks.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport time\nfrom threading import Thread\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import callbacks as m\nfrom pybind11_tests import detailed_error_messages_enabled\n\n\ndef test_callbacks():\n    from functools import partial\n\n    def func1():\n        return \"func1\"\n\n    def func2(a, b, c, d):\n        return \"func2\", a, b, c, d\n\n    def func3(a):\n        return f\"func3({a})\"\n\n    assert m.test_callback1(func1) == \"func1\"\n    assert m.test_callback2(func2) == (\"func2\", \"Hello\", \"x\", True, 5)\n    assert m.test_callback1(partial(func2, 1, 2, 3, 4)) == (\"func2\", 1, 2, 3, 4)\n    assert m.test_callback1(partial(func3, \"partial\")) == \"func3(partial)\"\n    assert m.test_callback3(lambda i: i + 1) == \"func(43) = 44\"\n\n    f = m.test_callback4()\n    assert f(43) == 44\n    f = m.test_callback5()\n    assert f(number=43) == 44\n\n\ndef test_bound_method_callback():\n    # Bound Python method:\n    class MyClass:\n        def double(self, val):\n            return 2 * val\n\n    z = MyClass()\n    assert m.test_callback3(z.double) == \"func(43) = 86\"\n\n    z = m.CppBoundMethodTest()\n    assert m.test_callback3(z.triple) == \"func(43) = 129\"\n\n\ndef test_keyword_args_and_generalized_unpacking():\n    def f(*args, **kwargs):\n        return args, kwargs\n\n    assert m.test_tuple_unpacking(f) == ((\"positional\", 1, 2, 3, 4, 5, 6), {})\n    assert m.test_dict_unpacking(f) == (\n        (\"positional\", 1),\n        {\"key\": \"value\", \"a\": 1, \"b\": 2},\n    )\n    assert m.test_keyword_args(f) == ((), {\"x\": 10, \"y\": 20})\n    assert m.test_unpacking_and_keywords1(f) == ((1, 2), {\"c\": 3, \"d\": 4})\n    assert m.test_unpacking_and_keywords2(f) == (\n        (\"positional\", 1, 2, 3, 4, 5),\n        {\"key\": \"value\", \"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5},\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        m.test_unpacking_error1(f)\n    assert \"Got multiple values for keyword argument\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.test_unpacking_error2(f)\n    assert \"Got multiple values for keyword argument\" in str(excinfo.value)\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.test_arg_conversion_error1(f)\n    assert str(excinfo.value) == \"Unable to convert call argument \" + (\n        \"'1' of type 'UnregisteredType' to Python object\"\n        if detailed_error_messages_enabled\n        else \"'1' to Python object (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\"\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.test_arg_conversion_error2(f)\n    assert str(excinfo.value) == \"Unable to convert call argument \" + (\n        \"'expected_name' of type 'UnregisteredType' to Python object\"\n        if detailed_error_messages_enabled\n        else \"'expected_name' to Python object \"\n        \"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_lambda_closure_cleanup():\n    m.test_lambda_closure_cleanup()\n    cstats = m.payload_cstats()\n    assert cstats.alive() == 0\n    assert cstats.copy_constructions == 1\n    assert cstats.move_constructions >= 1\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_cpp_callable_cleanup():\n    alive_counts = m.test_cpp_callable_cleanup()\n    assert alive_counts == [0, 1, 2, 1, 2, 1, 0]\n\n\ndef test_cpp_function_roundtrip():\n    \"\"\"Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer\"\"\"\n\n    assert (\n        m.test_dummy_function(m.dummy_function) == \"matches dummy_function: eval(1) = 2\"\n    )\n    assert (\n        m.test_dummy_function(m.roundtrip(m.dummy_function))\n        == \"matches dummy_function: eval(1) = 2\"\n    )\n    assert (\n        m.test_dummy_function(m.dummy_function_overloaded)\n        == \"matches dummy_function: eval(1) = 2\"\n    )\n    assert m.roundtrip(None, expect_none=True) is None\n    assert (\n        m.test_dummy_function(lambda x: x + 2)\n        == \"can't convert to function pointer: eval(1) = 3\"\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        m.test_dummy_function(m.dummy_function2)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.test_dummy_function(lambda x, y: x + y)\n    assert any(\n        s in str(excinfo.value)\n        for s in (\"missing 1 required positional argument\", \"takes exactly 2 arguments\")\n    )\n\n\ndef test_function_signatures(doc):\n    assert (\n        doc(m.test_callback3)\n        == \"test_callback3(arg0: collections.abc.Callable[[typing.SupportsInt | typing.SupportsIndex], int]) -> str\"\n    )\n    assert (\n        doc(m.test_callback4)\n        == \"test_callback4() -> collections.abc.Callable[[typing.SupportsInt | typing.SupportsIndex], int]\"\n    )\n\n\ndef test_movable_object():\n    assert m.callback_with_movable(lambda _: None) is True\n\n\n@pytest.mark.skipif(\n    \"env.PYPY\",\n    reason=\"PyPy segfaults on here. See discussion on #1413.\",\n)\ndef test_python_builtins():\n    \"\"\"Test if python builtins like sum() can be used as callbacks\"\"\"\n    assert m.test_sum_builtin(sum, [1, 2, 3]) == 6\n    assert m.test_sum_builtin(sum, []) == 0\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_async_callbacks():\n    # serves as state for async callback\n    class Item:\n        def __init__(self, value):\n            self.value = value\n\n    res = []\n\n    # generate stateful lambda that will store result in `res`\n    def gen_f():\n        s = Item(3)\n        return lambda j: res.append(s.value + j)\n\n    # do some work async\n    work = [1, 2, 3, 4]\n    m.test_async_callback(gen_f(), work)\n    # Wait for all detached worker threads to finish.\n    deadline = time.monotonic() + 5.0\n    while len(res) < len(work) and time.monotonic() < deadline:\n        time.sleep(0.01)\n    assert len(res) == len(work), f\"Timed out waiting for callbacks: res={res!r}\"\n    assert sum(res) == sum(x + 3 for x in work)\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_async_async_callbacks():\n    t = Thread(target=test_async_callbacks)\n    t.start()\n    t.join()\n\n\ndef test_callback_num_times():\n    # Super-simple micro-benchmarking related to PR #2919.\n    # Example runtimes (Intel Xeon 2.2GHz, fully optimized):\n    #   num_millions  1, repeats  2:  0.1 secs\n    #   num_millions 20, repeats 10: 11.5 secs\n    one_million = 1000000\n    num_millions = 1  # Try 20 for actual micro-benchmarking.\n    repeats = 2  # Try 10.\n    rates = []\n    for rep in range(repeats):\n        t0 = time.time()\n        m.callback_num_times(lambda: None, num_millions * one_million)\n        td = time.time() - t0\n        rate = num_millions / td if td else 0\n        rates.append(rate)\n        if not rep:\n            print()\n        print(\n            f\"callback_num_times: {num_millions:d} million / {td:.3f} seconds = {rate:.3f} million / second\"\n        )\n    if len(rates) > 1:\n        print(\"Min    Mean   Max\")\n        print(f\"{min(rates):6.3f} {sum(rates) / len(rates):6.3f} {max(rates):6.3f}\")\n\n\ndef test_custom_func():\n    assert m.custom_function(4) == 36\n    assert m.roundtrip(m.custom_function)(4) == 36\n\n\ndef test_custom_func2():\n    assert m.custom_function2(3) == 27\n    assert m.roundtrip(m.custom_function2)(3) == 27\n\n\ndef test_callback_docstring():\n    assert (\n        m.test_tuple_unpacking.__doc__.strip()\n        == \"test_tuple_unpacking(arg0: collections.abc.Callable) -> object\"\n    )\n\n\ndef test_boost_histogram_apply_custom_transform():\n    ctd = m.boost_histogram_custom_transform_double\n    cti = m.boost_histogram_custom_transform_int\n    apply = m.boost_histogram_apply_custom_transform\n    assert apply(ctd, 5) == 15\n    assert apply(cti, 0) == -200\n    assert apply(None, 0) == -100\n    assert apply(lambda value: value, 9) == -200\n    assert apply({}, 0) == -100\n    assert apply(\"\", 0) == -100\n"
  },
  {
    "path": "tests/test_chrono.cpp",
    "content": "/*\n    tests/test_chrono.cpp -- test conversions to/from std::chrono types\n\n    Copyright (c) 2016 Trent Houliston <trent@houliston.me> and\n                       Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/chrono.h>\n\n#include \"pybind11_tests.h\"\n\n#include <chrono>\n\nstruct different_resolutions {\n    using time_point_h = std::chrono::time_point<std::chrono::system_clock, std::chrono::hours>;\n    using time_point_m = std::chrono::time_point<std::chrono::system_clock, std::chrono::minutes>;\n    using time_point_s = std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>;\n    using time_point_ms\n        = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>;\n    using time_point_us\n        = std::chrono::time_point<std::chrono::system_clock, std::chrono::microseconds>;\n    time_point_h timestamp_h;\n    time_point_m timestamp_m;\n    time_point_s timestamp_s;\n    time_point_ms timestamp_ms;\n    time_point_us timestamp_us;\n};\n\nTEST_SUBMODULE(chrono, m) {\n    using system_time = std::chrono::system_clock::time_point;\n    using steady_time = std::chrono::steady_clock::time_point;\n\n    using timespan = std::chrono::duration<int64_t, std::nano>;\n    using timestamp = std::chrono::time_point<std::chrono::system_clock, timespan>;\n\n    // test_chrono_system_clock\n    // Return the current time off the wall clock\n    m.def(\"test_chrono1\", []() { return std::chrono::system_clock::now(); });\n\n    // test_chrono_system_clock_roundtrip\n    // Round trip the passed in system clock time\n    m.def(\"test_chrono2\", [](system_time t) { return t; });\n\n    // test_chrono_duration_roundtrip\n    // Round trip the passed in duration\n    m.def(\"test_chrono3\", [](std::chrono::system_clock::duration d) { return d; });\n\n    // test_chrono_duration_subtraction_equivalence\n    // Difference between two passed in time_points\n    m.def(\"test_chrono4\", [](system_time a, system_time b) { return a - b; });\n\n    // test_chrono_steady_clock\n    // Return the current time off the steady_clock\n    m.def(\"test_chrono5\", []() { return std::chrono::steady_clock::now(); });\n\n    // test_chrono_steady_clock_roundtrip\n    // Round trip a steady clock timepoint\n    m.def(\"test_chrono6\", [](steady_time t) { return t; });\n\n    // test_floating_point_duration\n    // Roundtrip a duration in microseconds from a float argument\n    m.def(\"test_chrono7\", [](std::chrono::microseconds t) { return t; });\n    // Float durations (issue #719)\n    m.def(\"test_chrono_float_diff\",\n          [](std::chrono::duration<float> a, std::chrono::duration<float> b) { return a - b; });\n\n    m.def(\"test_nano_timepoint\",\n          [](timestamp start, timespan delta) -> timestamp { return start + delta; });\n\n    // Test different resolutions\n    py::class_<different_resolutions>(m, \"different_resolutions\")\n        .def(py::init<>())\n        .def_readwrite(\"timestamp_h\", &different_resolutions::timestamp_h)\n        .def_readwrite(\"timestamp_m\", &different_resolutions::timestamp_m)\n        .def_readwrite(\"timestamp_s\", &different_resolutions::timestamp_s)\n        .def_readwrite(\"timestamp_ms\", &different_resolutions::timestamp_ms)\n        .def_readwrite(\"timestamp_us\", &different_resolutions::timestamp_us);\n}\n"
  },
  {
    "path": "tests/test_chrono.py",
    "content": "from __future__ import annotations\n\nimport datetime\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import chrono as m\n\n\ndef test_chrono_system_clock():\n    # Get the time from both c++ and datetime\n    date0 = datetime.datetime.today()\n    date1 = m.test_chrono1()\n    date2 = datetime.datetime.today()\n\n    # The returned value should be a datetime\n    assert isinstance(date1, datetime.datetime)\n\n    # The numbers should vary by a very small amount (time it took to execute)\n    diff_python = abs(date2 - date0)\n    diff = abs(date1 - date2)\n\n    # There should never be a days difference\n    assert diff.days == 0\n\n    # Since datetime.datetime.today() calls time.time(), and on some platforms\n    # that has 1 second accuracy, we compare this way\n    assert diff.seconds <= diff_python.seconds\n\n\ndef test_chrono_system_clock_roundtrip():\n    date1 = datetime.datetime.today()\n\n    # Roundtrip the time\n    date2 = m.test_chrono2(date1)\n\n    # The returned value should be a datetime\n    assert isinstance(date2, datetime.datetime)\n\n    # They should be identical (no information lost on roundtrip)\n    diff = abs(date1 - date2)\n    assert diff == datetime.timedelta(0)\n\n\ndef test_chrono_system_clock_roundtrip_date():\n    date1 = datetime.date.today()\n\n    # Roundtrip the time\n    datetime2 = m.test_chrono2(date1)\n    date2 = datetime2.date()\n    time2 = datetime2.time()\n\n    # The returned value should be a datetime\n    assert isinstance(datetime2, datetime.datetime)\n    assert isinstance(date2, datetime.date)\n    assert isinstance(time2, datetime.time)\n\n    # They should be identical (no information lost on roundtrip)\n    diff = abs(date1 - date2)\n    assert diff.days == 0\n    assert diff.seconds == 0\n    assert diff.microseconds == 0\n\n    # Year, Month & Day should be the same after the round trip\n    assert date1 == date2\n\n    # There should be no time information\n    assert time2.hour == 0\n    assert time2.minute == 0\n    assert time2.second == 0\n    assert time2.microsecond == 0\n\n\nSKIP_TZ_ENV_ON_WIN = pytest.mark.skipif(\n    \"env.WIN\", reason=\"TZ environment variable only supported on POSIX\"\n)\n\n\n@pytest.mark.parametrize(\n    \"time1\",\n    [\n        datetime.datetime.today().time(),\n        datetime.time(0, 0, 0),\n        datetime.time(0, 0, 0, 1),\n        datetime.time(0, 28, 45, 109827),\n        datetime.time(0, 59, 59, 999999),\n        datetime.time(1, 0, 0),\n        datetime.time(5, 59, 59, 0),\n        datetime.time(5, 59, 59, 1),\n    ],\n)\n@pytest.mark.parametrize(\n    \"tz\",\n    [\n        None,\n        pytest.param(\"Europe/Brussels\", marks=SKIP_TZ_ENV_ON_WIN),\n        pytest.param(\"Asia/Pyongyang\", marks=SKIP_TZ_ENV_ON_WIN),\n        pytest.param(\"America/New_York\", marks=SKIP_TZ_ENV_ON_WIN),\n    ],\n)\ndef test_chrono_system_clock_roundtrip_time(time1, tz, monkeypatch):\n    if tz is not None:\n        monkeypatch.setenv(\"TZ\", f\"/usr/share/zoneinfo/{tz}\")\n\n    # Roundtrip the time\n    datetime2 = m.test_chrono2(time1)\n    date2 = datetime2.date()\n    time2 = datetime2.time()\n\n    # The returned value should be a datetime\n    assert isinstance(datetime2, datetime.datetime)\n    assert isinstance(date2, datetime.date)\n    assert isinstance(time2, datetime.time)\n\n    # Hour, Minute, Second & Microsecond should be the same after the round trip\n    assert time1 == time2\n\n    # There should be no date information (i.e. date = python base date)\n    assert date2.year == 1970\n    assert date2.month == 1\n    assert date2.day == 1\n\n\ndef test_chrono_duration_roundtrip():\n    # Get the difference between two times (a timedelta)\n    date1 = datetime.datetime.today()\n    date2 = datetime.datetime.today()\n    diff = date2 - date1\n\n    # Make sure this is a timedelta\n    assert isinstance(diff, datetime.timedelta)\n\n    cpp_diff = m.test_chrono3(diff)\n\n    assert cpp_diff == diff\n\n    # Negative timedelta roundtrip\n    diff = datetime.timedelta(microseconds=-1)\n    cpp_diff = m.test_chrono3(diff)\n\n    assert cpp_diff == diff\n\n\ndef test_chrono_duration_subtraction_equivalence():\n    date1 = datetime.datetime.today()\n    date2 = datetime.datetime.today()\n\n    diff = date2 - date1\n    cpp_diff = m.test_chrono4(date2, date1)\n\n    assert cpp_diff == diff\n\n\ndef test_chrono_duration_subtraction_equivalence_date():\n    date1 = datetime.date.today()\n    date2 = datetime.date.today()\n\n    diff = date2 - date1\n    cpp_diff = m.test_chrono4(date2, date1)\n\n    assert cpp_diff == diff\n\n\ndef test_chrono_steady_clock():\n    time1 = m.test_chrono5()\n    assert isinstance(time1, datetime.timedelta)\n\n\ndef test_chrono_steady_clock_roundtrip():\n    time1 = datetime.timedelta(days=10, seconds=10, microseconds=100)\n    time2 = m.test_chrono6(time1)\n\n    assert isinstance(time2, datetime.timedelta)\n\n    # They should be identical (no information lost on roundtrip)\n    assert time1 == time2\n\n\ndef test_floating_point_duration():\n    # Test using a floating point number in seconds\n    time = m.test_chrono7(35.525123)\n\n    assert isinstance(time, datetime.timedelta)\n\n    assert time.seconds == 35\n    assert 525122 <= time.microseconds <= 525123\n\n    diff = m.test_chrono_float_diff(43.789012, 1.123456)\n    assert diff.seconds == 42\n    assert 665556 <= diff.microseconds <= 665557\n\n\ndef test_nano_timepoint():\n    time = datetime.datetime.now()\n    time1 = m.test_nano_timepoint(time, datetime.timedelta(seconds=60))\n    assert time1 == time + datetime.timedelta(seconds=60)\n\n\ndef test_chrono_different_resolutions():\n    resolutions = m.different_resolutions()\n    time = datetime.datetime.now()\n    resolutions.timestamp_h = time\n    resolutions.timestamp_m = time\n    resolutions.timestamp_s = time\n    resolutions.timestamp_ms = time\n    resolutions.timestamp_us = time\n"
  },
  {
    "path": "tests/test_class.cpp",
    "content": "/*\n    tests/test_class.cpp -- test py::class_ definitions and basic functionality\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#if defined(__INTEL_COMPILER) && __cplusplus >= 201703L\n// Intel compiler requires a separate header file to support aligned new operators\n// and does not set the __cpp_aligned_new feature macro.\n// This header needs to be included before pybind11.\n#    include <aligned_new>\n#endif\n\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"local_bindings.h\"\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\nPYBIND11_WARNING_DISABLE_MSVC(4324)\n//     warning C4324: structure was padded due to alignment specifier\n\n// test_brace_initialization\nstruct NoBraceInitialization {\n    explicit NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}\n    template <typename T>\n    NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}\n\n    std::vector<int> vec;\n};\n\nnamespace test_class {\nnamespace pr4220_tripped_over_this { // PR #4227\n\ntemplate <int>\nstruct SoEmpty {};\n\ntemplate <typename T>\nstd::string get_msg(const T &) {\n    return \"This is really only meant to exercise successful compilation.\";\n}\n\nusing Empty0 = SoEmpty<0x0>;\n\nvoid bind_empty0(py::module_ &m) {\n    py::class_<Empty0>(m, \"Empty0\").def(py::init<>()).def(\"get_msg\", get_msg<Empty0>);\n}\n\n} // namespace pr4220_tripped_over_this\n\nnamespace pr5396_forward_declared_class {\nclass ForwardClass;\nclass Args : public py::args {};\n} // namespace pr5396_forward_declared_class\n\nstruct ConvertibleFromAnything {\n    ConvertibleFromAnything() = default;\n    template <class T>\n    // NOLINTNEXTLINE(bugprone-forwarding-reference-overload,google-explicit-constructor)\n    ConvertibleFromAnything(T &&) {}\n};\n\n} // namespace test_class\n\nstatic_assert(py::detail::is_same_or_base_of<py::args, py::args>::value, \"\");\nstatic_assert(\n    py::detail::is_same_or_base_of<py::args,\n                                   test_class::pr5396_forward_declared_class::Args>::value,\n    \"\");\nstatic_assert(!py::detail::is_same_or_base_of<\n                  py::args,\n                  test_class::pr5396_forward_declared_class::ForwardClass>::value,\n              \"\");\n\nTEST_SUBMODULE(class_, m) {\n    m.def(\"obj_class_name\", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });\n\n    // test_instance\n    struct NoConstructor {\n        NoConstructor() = default;\n        NoConstructor(const NoConstructor &) = default;\n        NoConstructor(NoConstructor &&) = default;\n        static NoConstructor *new_instance() {\n            auto *ptr = new NoConstructor();\n            print_created(ptr, \"via new_instance\");\n            return ptr;\n        }\n        ~NoConstructor() { print_destroyed(this); }\n    };\n    struct NoConstructorNew {\n        NoConstructorNew() = default;\n        NoConstructorNew(const NoConstructorNew &) = default;\n        NoConstructorNew(NoConstructorNew &&) = default;\n        static NoConstructorNew *new_instance() {\n            auto *ptr = new NoConstructorNew();\n            print_created(ptr, \"via new_instance\");\n            return ptr;\n        }\n        ~NoConstructorNew() { print_destroyed(this); }\n    };\n\n    py::class_<NoConstructor>(m, \"NoConstructor\")\n        .def_static(\"new_instance\", &NoConstructor::new_instance, \"Return an instance\");\n\n    py::class_<NoConstructorNew>(m, \"NoConstructorNew\")\n        .def(py::init([]() { return nullptr; })) // Need a NOOP __init__\n        .def_static(\"__new__\",\n                    [](const py::object &) { return NoConstructorNew::new_instance(); });\n\n    // test_pass_unique_ptr\n    struct ToBeHeldByUniquePtr {};\n    py::class_<ToBeHeldByUniquePtr, std::unique_ptr<ToBeHeldByUniquePtr>>(m, \"ToBeHeldByUniquePtr\")\n        .def(py::init<>());\n    m.def(\"pass_unique_ptr\", [](std::unique_ptr<ToBeHeldByUniquePtr> &&) {});\n\n    // test_inheritance\n    class Pet {\n    public:\n        Pet(const std::string &name, const std::string &species)\n            : m_name(name), m_species(species) {}\n        std::string name() const { return m_name; }\n        std::string species() const { return m_species; }\n\n    private:\n        std::string m_name;\n        std::string m_species;\n    };\n\n    class Dog : public Pet {\n    public:\n        explicit Dog(const std::string &name) : Pet(name, \"dog\") {}\n        std::string bark() const { return \"Woof!\"; }\n    };\n\n    class Rabbit : public Pet {\n    public:\n        explicit Rabbit(const std::string &name) : Pet(name, \"parrot\") {}\n    };\n\n    class Hamster : public Pet {\n    public:\n        explicit Hamster(const std::string &name) : Pet(name, \"rodent\") {}\n    };\n\n    class Chimera : public Pet {\n        Chimera() : Pet(\"Kimmy\", \"chimera\") {}\n    };\n\n    py::class_<Pet> pet_class(m, \"Pet\");\n    pet_class.def(py::init<std::string, std::string>())\n        .def(\"name\", &Pet::name)\n        .def(\"species\", &Pet::species);\n\n    /* One way of declaring a subclass relationship: reference parent's class_ object */\n    py::class_<Dog>(m, \"Dog\", pet_class).def(py::init<std::string>());\n\n    /* Another way of declaring a subclass relationship: reference parent's C++ type */\n    py::class_<Rabbit, Pet>(m, \"Rabbit\").def(py::init<std::string>());\n\n    /* And another: list parent in class template arguments */\n    py::class_<Hamster, Pet>(m, \"Hamster\").def(py::init<std::string>());\n\n    /* Constructors are not inherited by default */\n    py::class_<Chimera, Pet>(m, \"Chimera\");\n\n    m.def(\"pet_name_species\",\n          [](const Pet &pet) { return pet.name() + \" is a \" + pet.species(); });\n    m.def(\"dog_bark\", [](const Dog &dog) { return dog.bark(); });\n\n    // test_automatic_upcasting\n    struct BaseClass {\n        BaseClass() = default;\n        BaseClass(const BaseClass &) = default;\n        BaseClass(BaseClass &&) = default;\n        virtual ~BaseClass() = default;\n    };\n    struct DerivedClass1 : BaseClass {};\n    struct DerivedClass2 : BaseClass {};\n\n    py::class_<BaseClass>(m, \"BaseClass\").def(py::init<>());\n    py::class_<DerivedClass1>(m, \"DerivedClass1\").def(py::init<>());\n    py::class_<DerivedClass2>(m, \"DerivedClass2\").def(py::init<>());\n\n    m.def(\"return_class_1\", []() -> BaseClass * { return new DerivedClass1(); });\n    m.def(\"return_class_2\", []() -> BaseClass * { return new DerivedClass2(); });\n    m.def(\"return_class_n\", [](int n) -> BaseClass * {\n        if (n == 1) {\n            return new DerivedClass1();\n        }\n        if (n == 2) {\n            return new DerivedClass2();\n        }\n        return new BaseClass();\n    });\n    m.def(\"return_none\", []() -> BaseClass * { return nullptr; });\n\n    // test_isinstance\n    m.def(\"check_instances\", [](const py::list &l) {\n        return py::make_tuple(py::isinstance<py::tuple>(l[0]),\n                              py::isinstance<py::dict>(l[1]),\n                              py::isinstance<Pet>(l[2]),\n                              py::isinstance<Pet>(l[3]),\n                              py::isinstance<Dog>(l[4]),\n                              py::isinstance<Rabbit>(l[5]),\n                              py::isinstance<UnregisteredType>(l[6]));\n    });\n\n    struct Invalid {};\n\n    // test_type\n    m.def(\"check_type\", [](int category) {\n        // Currently not supported (via a fail at compile time)\n        // See https://github.com/pybind/pybind11/issues/2486\n        // if (category == 2)\n        //     return py::type::of<int>();\n        if (category == 1) {\n            return py::type::of<DerivedClass1>();\n        }\n        return py::type::of<Invalid>();\n    });\n\n    m.def(\"get_type_of\", [](py::object ob) { return py::type::of(std::move(ob)); });\n\n    m.def(\"get_type_classic\", [](py::handle h) { return py::type::handle_of(h); });\n\n    m.def(\"as_type\", [](const py::object &ob) { return py::type(ob); });\n\n    // test_mismatched_holder\n    struct MismatchBase1 {};\n    struct MismatchDerived1 : MismatchBase1 {};\n\n    struct MismatchBase2 {};\n    struct MismatchDerived2 : MismatchBase2 {};\n\n    m.def(\"mismatched_holder_1\", []() {\n        auto mod = py::module_::import(\"__main__\");\n        py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, \"MismatchBase1\");\n        py::class_<MismatchDerived1, std::unique_ptr<MismatchDerived1>, MismatchBase1>(\n            mod, \"MismatchDerived1\");\n    });\n    m.def(\"mismatched_holder_2\", []() {\n        auto mod = py::module_::import(\"__main__\");\n        py::class_<MismatchBase2, std::unique_ptr<MismatchBase2>>(mod, \"MismatchBase2\");\n        py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>, MismatchBase2>(\n            mod, \"MismatchDerived2\");\n    });\n\n    // test_override_static\n    // #511: problem with inheritance + overwritten def_static\n    struct MyBase {\n        static std::unique_ptr<MyBase> make() { return std::unique_ptr<MyBase>(new MyBase()); }\n    };\n\n    struct MyDerived : MyBase {\n        static std::unique_ptr<MyDerived> make() {\n            return std::unique_ptr<MyDerived>(new MyDerived());\n        }\n    };\n\n    py::class_<MyBase>(m, \"MyBase\").def_static(\"make\", &MyBase::make);\n\n    py::class_<MyDerived, MyBase>(m, \"MyDerived\")\n        .def_static(\"make\", &MyDerived::make)\n        .def_static(\"make2\", &MyDerived::make);\n\n    // test_implicit_conversion_life_support\n    struct ConvertibleFromUserType {\n        int i;\n\n        explicit ConvertibleFromUserType(UserType u) : i(u.value()) {}\n    };\n\n    py::class_<ConvertibleFromUserType>(m, \"AcceptsUserType\").def(py::init<UserType>());\n    py::implicitly_convertible<UserType, ConvertibleFromUserType>();\n\n    m.def(\"implicitly_convert_argument\", [](const ConvertibleFromUserType &r) { return r.i; });\n    m.def(\"implicitly_convert_variable\", [](const py::object &o) {\n        // `o` is `UserType` and `r` is a reference to a temporary created by implicit\n        // conversion. This is valid when called inside a bound function because the temp\n        // object is attached to the same life support system as the arguments.\n        const auto &r = o.cast<const ConvertibleFromUserType &>();\n        return r.i;\n    });\n    m.add_object(\"implicitly_convert_variable_fail\", [&] {\n        auto f = [](PyObject *, PyObject *args) -> PyObject * {\n            auto o = py::reinterpret_borrow<py::tuple>(args)[0];\n            try { // It should fail here because there is no life support.\n                o.cast<const ConvertibleFromUserType &>();\n            } catch (const py::cast_error &e) {\n                return py::str(e.what()).release().ptr();\n            }\n            return py::str().release().ptr();\n        };\n\n        auto *def = new PyMethodDef{\"f\", f, METH_VARARGS, nullptr};\n        py::capsule def_capsule(def,\n                                [](void *ptr) { delete reinterpret_cast<PyMethodDef *>(ptr); });\n        return py::reinterpret_steal<py::object>(\n            PyCFunction_NewEx(def, def_capsule.ptr(), m.ptr()));\n    }());\n\n    // test_operator_new_delete\n    struct HasOpNewDel {\n        std::uint64_t i;\n        static void *operator new(size_t s) {\n            py::print(\"A new\", s);\n            return ::operator new(s);\n        }\n        static void *operator new(size_t s, void *ptr) {\n            py::print(\"A placement-new\", s);\n            return ptr;\n        }\n        static void operator delete(void *p) {\n            py::print(\"A delete\");\n            return ::operator delete(p);\n        }\n    };\n    struct HasOpNewDelSize {\n        std::uint32_t i;\n        static void *operator new(size_t s) {\n            py::print(\"B new\", s);\n            return ::operator new(s);\n        }\n        static void *operator new(size_t s, void *ptr) {\n            py::print(\"B placement-new\", s);\n            return ptr;\n        }\n        static void operator delete(void *p, size_t s) {\n            py::print(\"B delete\", s);\n            return ::operator delete(p);\n        }\n    };\n    struct AliasedHasOpNewDelSize {\n        std::uint64_t i;\n        static void *operator new(size_t s) {\n            py::print(\"C new\", s);\n            return ::operator new(s);\n        }\n        static void *operator new(size_t s, void *ptr) {\n            py::print(\"C placement-new\", s);\n            return ptr;\n        }\n        static void operator delete(void *p, size_t s) {\n            py::print(\"C delete\", s);\n            return ::operator delete(p);\n        }\n        virtual ~AliasedHasOpNewDelSize() = default;\n        AliasedHasOpNewDelSize() = default;\n        AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize &) = delete;\n    };\n    struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {\n        PyAliasedHasOpNewDelSize() = default;\n        explicit PyAliasedHasOpNewDelSize(int) {}\n        std::uint64_t j;\n    };\n    struct HasOpNewDelBoth {\n        std::uint32_t i[8];\n        static void *operator new(size_t s) {\n            py::print(\"D new\", s);\n            return ::operator new(s);\n        }\n        static void *operator new(size_t s, void *ptr) {\n            py::print(\"D placement-new\", s);\n            return ptr;\n        }\n        static void operator delete(void *p) {\n            py::print(\"D delete\");\n            return ::operator delete(p);\n        }\n        static void operator delete(void *p, size_t s) {\n            py::print(\"D wrong delete\", s);\n            return ::operator delete(p);\n        }\n    };\n    py::class_<HasOpNewDel>(m, \"HasOpNewDel\").def(py::init<>());\n    py::class_<HasOpNewDelSize>(m, \"HasOpNewDelSize\").def(py::init<>());\n    py::class_<HasOpNewDelBoth>(m, \"HasOpNewDelBoth\").def(py::init<>());\n    py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m,\n                                                                         \"AliasedHasOpNewDelSize\");\n    aliased.def(py::init<>());\n    aliased.attr(\"size_noalias\") = py::int_(sizeof(AliasedHasOpNewDelSize));\n    aliased.attr(\"size_alias\") = py::int_(sizeof(PyAliasedHasOpNewDelSize));\n\n    // This test is actually part of test_local_bindings (test_duplicate_local), but we need a\n    // definition in a different compilation unit within the same module:\n    bind_local<LocalExternal, 17>(m, \"LocalExternal\", py::module_local());\n\n    // test_bind_protected_functions\n    class ProtectedA {\n    protected:\n        int foo() const { return value; }\n\n    private:\n        int value = 42;\n    };\n\n    class PublicistA : public ProtectedA {\n    public:\n        using ProtectedA::foo;\n    };\n\n    py::class_<ProtectedA>(m, \"ProtectedA\").def(py::init<>()).def(\"foo\", &PublicistA::foo);\n\n    class ProtectedB {\n    public:\n        virtual ~ProtectedB() = default;\n        ProtectedB() = default;\n        ProtectedB(const ProtectedB &) = delete;\n\n    protected:\n        virtual int foo() const { return value; }\n        virtual void *void_foo() { return static_cast<void *>(&value); }\n        virtual void *get_self() { return static_cast<void *>(this); }\n\n    private:\n        int value = 42;\n    };\n\n    class TrampolineB : public ProtectedB {\n    public:\n        int foo() const override { PYBIND11_OVERRIDE(int, ProtectedB, foo, ); }\n        void *void_foo() override { PYBIND11_OVERRIDE(void *, ProtectedB, void_foo, ); }\n        void *get_self() override { PYBIND11_OVERRIDE(void *, ProtectedB, get_self, ); }\n    };\n\n    class PublicistB : public ProtectedB {\n    public:\n        // [workaround(intel)] = default does not work here\n        // Removing or defaulting this destructor results in linking errors with the Intel compiler\n        // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)\n        ~PublicistB() override {}; // NOLINT(modernize-use-equals-default)\n        using ProtectedB::foo;\n        using ProtectedB::get_self;\n        using ProtectedB::void_foo;\n    };\n\n    m.def(\"read_foo\", [](const void *original) {\n        const int *ptr = reinterpret_cast<const int *>(original);\n        return *ptr;\n    });\n\n    m.def(\"pointers_equal\",\n          [](const void *original, const void *comparison) { return original == comparison; });\n\n    py::class_<ProtectedB, TrampolineB>(m, \"ProtectedB\")\n        .def(py::init<>())\n        .def(\"foo\", &PublicistB::foo)\n        .def(\"void_foo\", &PublicistB::void_foo)\n        .def(\"get_self\", &PublicistB::get_self);\n\n    // test_brace_initialization\n    struct BraceInitialization {\n        int field1;\n        std::string field2;\n    };\n\n    py::class_<BraceInitialization>(m, \"BraceInitialization\")\n        .def(py::init<int, const std::string &>())\n        .def_readwrite(\"field1\", &BraceInitialization::field1)\n        .def_readwrite(\"field2\", &BraceInitialization::field2);\n    // We *don't* want to construct using braces when the given constructor argument maps to a\n    // constructor, because brace initialization could go to the wrong place (in particular when\n    // there is also an `initializer_list<T>`-accept constructor):\n    py::class_<NoBraceInitialization>(m, \"NoBraceInitialization\")\n        .def(py::init<std::vector<int>>())\n        .def_readonly(\"vec\", &NoBraceInitialization::vec);\n\n    // test_reentrant_implicit_conversion_failure\n    // #1035: issue with runaway reentrant implicit conversion\n    struct BogusImplicitConversion {\n        BogusImplicitConversion(const BogusImplicitConversion &) = default;\n    };\n\n    py::class_<BogusImplicitConversion>(m, \"BogusImplicitConversion\")\n        .def(py::init<const BogusImplicitConversion &>());\n\n    py::implicitly_convertible<int, BogusImplicitConversion>();\n\n    // test_qualname\n    // #1166: nested class docstring doesn't show nested name\n    // Also related: tests that __qualname__ is set properly\n    struct NestBase {};\n    struct Nested {};\n    py::class_<NestBase> base(m, \"NestBase\");\n    base.def(py::init<>());\n    py::class_<Nested>(base, \"Nested\")\n        .def(py::init<>())\n        .def(\"fn\", [](Nested &, int, NestBase &, Nested &) {})\n        .def(\"fa\", [](Nested &, int, NestBase &, Nested &) {}, \"a\"_a, \"b\"_a, \"c\"_a);\n    base.def(\"g\", [](NestBase &, Nested &) {});\n    base.def(\"h\", []() { return NestBase(); });\n\n    // test_error_after_conversion\n    // The second-pass path through dispatcher() previously didn't\n    // remember which overload was used, and would crash trying to\n    // generate a useful error message\n\n    struct NotRegistered {};\n    struct StringWrapper {\n        std::string str;\n    };\n    m.def(\"test_error_after_conversions\", [](int) {});\n    m.def(\"test_error_after_conversions\",\n          [](const StringWrapper &) -> NotRegistered { return {}; });\n    py::class_<StringWrapper>(m, \"StringWrapper\").def(py::init<std::string>());\n    py::implicitly_convertible<std::string, StringWrapper>();\n\n#if defined(PYBIND11_CPP17)\n    struct alignas(1024) Aligned {\n        std::uintptr_t ptr() const { return (uintptr_t) this; }\n    };\n    py::class_<Aligned>(m, \"Aligned\").def(py::init<>()).def(\"ptr\", &Aligned::ptr);\n#endif\n\n    // test_final\n    struct IsFinal final {};\n    py::class_<IsFinal>(m, \"IsFinal\", py::is_final());\n\n    // test_non_final_final\n    struct IsNonFinalFinal {};\n    py::class_<IsNonFinalFinal>(m, \"IsNonFinalFinal\", py::is_final());\n\n    // test_exception_rvalue_abort\n    struct PyPrintDestructor {\n        PyPrintDestructor() = default;\n        PyPrintDestructor(const PyPrintDestructor &) = default;\n        ~PyPrintDestructor() { py::print(\"Print from destructor\"); }\n        void throw_something() { throw std::runtime_error(\"error\"); }\n    };\n    py::class_<PyPrintDestructor>(m, \"PyPrintDestructor\")\n        .def(py::init<>())\n        .def(\"throw_something\", &PyPrintDestructor::throw_something);\n\n    // test_multiple_instances_with_same_pointer\n    struct SamePointer {};\n    static SamePointer samePointer;\n    py::class_<SamePointer, std::unique_ptr<SamePointer, py::nodelete>>(m, \"SamePointer\")\n        .def(py::init([]() { return &samePointer; }));\n\n    struct Empty {};\n    py::class_<Empty>(m, \"Empty\").def(py::init<>());\n\n    // test_base_and_derived_nested_scope\n    struct BaseWithNested {\n        struct Nested {};\n    };\n\n    struct DerivedWithNested : BaseWithNested {\n        struct Nested {};\n    };\n\n    py::class_<BaseWithNested> baseWithNested_class(m, \"BaseWithNested\");\n    py::class_<DerivedWithNested, BaseWithNested> derivedWithNested_class(m, \"DerivedWithNested\");\n    py::class_<BaseWithNested::Nested>(baseWithNested_class, \"Nested\")\n        .def_static(\"get_name\", []() { return \"BaseWithNested::Nested\"; });\n    py::class_<DerivedWithNested::Nested>(derivedWithNested_class, \"Nested\")\n        .def_static(\"get_name\", []() { return \"DerivedWithNested::Nested\"; });\n\n    // test_register_duplicate_class\n    struct Duplicate {};\n    struct OtherDuplicate {};\n    struct DuplicateNested {};\n    struct OtherDuplicateNested {};\n\n    m.def(\"register_duplicate_class_name\", [](const py::module_ &m) {\n        py::class_<Duplicate>(m, \"Duplicate\");\n        py::class_<OtherDuplicate>(m, \"Duplicate\");\n    });\n    m.def(\"register_duplicate_class_type\", [](const py::module_ &m) {\n        py::class_<OtherDuplicate>(m, \"OtherDuplicate\");\n        py::class_<OtherDuplicate>(m, \"YetAnotherDuplicate\");\n    });\n    m.def(\"register_duplicate_nested_class_name\", [](const py::object &gt) {\n        py::class_<DuplicateNested>(gt, \"DuplicateNested\");\n        py::class_<OtherDuplicateNested>(gt, \"DuplicateNested\");\n    });\n    m.def(\"register_duplicate_nested_class_type\", [](const py::object &gt) {\n        py::class_<OtherDuplicateNested>(gt, \"OtherDuplicateNested\");\n        py::class_<OtherDuplicateNested>(gt, \"YetAnotherDuplicateNested\");\n    });\n\n    test_class::pr4220_tripped_over_this::bind_empty0(m);\n\n    // Regression test for compiler error that showed up in #5866\n    m.def(\"return_universal_recipient\", []() -> test_class::ConvertibleFromAnything {\n        return test_class::ConvertibleFromAnything{};\n    });\n}\n\ntemplate <int N>\nclass BreaksBase {\npublic:\n    virtual ~BreaksBase() = default;\n    BreaksBase() = default;\n    BreaksBase(const BreaksBase &) = delete;\n};\ntemplate <int N>\nclass BreaksTramp : public BreaksBase<N> {};\n// These should all compile just fine:\nusing DoesntBreak1 = py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>>;\nusing DoesntBreak2 = py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>>;\nusing DoesntBreak3 = py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>>;\nusing DoesntBreak4 = py::class_<BreaksBase<4>, BreaksTramp<4>>;\nusing DoesntBreak5 = py::class_<BreaksBase<5>>;\nusing DoesntBreak6 = py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>>;\nusing DoesntBreak7 = py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>>;\nusing DoesntBreak8 = py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>>;\n#define CHECK_BASE(N)                                                                             \\\n    static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<(N)>>::value,            \\\n                  \"DoesntBreak\" #N \" has wrong type!\")\nCHECK_BASE(1);\nCHECK_BASE(2);\nCHECK_BASE(3);\nCHECK_BASE(4);\nCHECK_BASE(5);\nCHECK_BASE(6);\nCHECK_BASE(7);\nCHECK_BASE(8);\n#define CHECK_ALIAS(N)                                                                            \\\n    static_assert(                                                                                \\\n        DoesntBreak##N::has_alias                                                                 \\\n            && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<(N)>>::value,        \\\n        \"DoesntBreak\" #N \" has wrong type_alias!\")\n#define CHECK_NOALIAS(N)                                                                          \\\n    static_assert(!DoesntBreak##N::has_alias                                                      \\\n                      && std::is_void<typename DoesntBreak##N::type_alias>::value,                \\\n                  \"DoesntBreak\" #N \" has type alias, but shouldn't!\")\nCHECK_ALIAS(1);\nCHECK_ALIAS(2);\nCHECK_NOALIAS(3);\nCHECK_ALIAS(4);\nCHECK_NOALIAS(5);\nCHECK_ALIAS(6);\nCHECK_ALIAS(7);\nCHECK_NOALIAS(8);\n#define CHECK_HOLDER(N, TYPE)                                                                     \\\n    static_assert(std::is_same<typename DoesntBreak##N::holder_type,                              \\\n                               std::TYPE##_ptr<BreaksBase<(N)>>>::value,                          \\\n                  \"DoesntBreak\" #N \" has wrong holder_type!\")\nCHECK_HOLDER(1, unique);\nCHECK_HOLDER(2, unique);\nCHECK_HOLDER(3, unique);\n#ifndef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE\nCHECK_HOLDER(4, unique);\nCHECK_HOLDER(5, unique);\n#endif\nCHECK_HOLDER(6, shared);\nCHECK_HOLDER(7, shared);\nCHECK_HOLDER(8, shared);\n\n// There's no nice way to test that these fail because they fail to compile; leave them here,\n// though, so that they can be manually tested by uncommenting them (and seeing that compilation\n// failures occurs).\n\n// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:\n#define CHECK_BROKEN(N)                                                                           \\\n    static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-(N)>>::value,                \\\n                  \"Breaks1 has wrong type!\");\n\n#ifdef PYBIND11_NEVER_DEFINED_EVER\n// Two holder classes:\ntypedef py::\n    class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>>\n        Breaks1;\nCHECK_BROKEN(1);\n// Two aliases:\ntypedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;\nCHECK_BROKEN(2);\n// Holder + 2 aliases\ntypedef py::\n    class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>>\n        Breaks3;\nCHECK_BROKEN(3);\n// Alias + 2 holders\ntypedef py::class_<BreaksBase<-4>,\n                   std::unique_ptr<BreaksBase<-4>>,\n                   BreaksTramp<-4>,\n                   std::shared_ptr<BreaksBase<-4>>>\n    Breaks4;\nCHECK_BROKEN(4);\n// Invalid option (not a subclass or holder)\ntypedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;\nCHECK_BROKEN(5);\n// Invalid option: multiple inheritance not supported:\ntemplate <>\nstruct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};\ntypedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;\nCHECK_BROKEN(8);\n#endif\n"
  },
  {
    "path": "tests/test_class.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom unittest import mock\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats, UserType\nfrom pybind11_tests import class_ as m\n\nUINT32MAX = 2**32 - 1\n\n\ndef refcount_immortal(ob: object) -> int:\n    if _is_immortal := getattr(sys, \"_is_immortal\", None):\n        return UINT32MAX if _is_immortal(ob) else sys.getrefcount(ob)\n    return sys.getrefcount(ob)\n\n\ndef test_obj_class_name():\n    expected_name = \"UserType\" if env.PYPY else \"pybind11_tests.UserType\"\n    assert m.obj_class_name(UserType(1)) == expected_name\n    assert m.obj_class_name(UserType) == expected_name\n\n\ndef test_repr():\n    assert \"pybind11_type\" in repr(type(UserType))\n    assert \"UserType\" in repr(UserType)\n\n\ndef test_instance(msg):\n    with pytest.raises(TypeError) as excinfo:\n        m.NoConstructor()\n    assert msg(excinfo.value) == \"m.class_.NoConstructor: No constructor defined!\"\n\n    instance = m.NoConstructor.new_instance()\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    cstats = ConstructorStats.get(m.NoConstructor)\n    assert cstats.alive() == 1\n    del instance\n    assert cstats.alive() == 0\n\n\ndef test_instance_new():\n    instance = m.NoConstructorNew()  # .__new__(m.NoConstructor.__class__)\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    cstats = ConstructorStats.get(m.NoConstructorNew)\n    assert cstats.alive() == 1\n    del instance\n    assert cstats.alive() == 0\n\n\ndef test_pass_unique_ptr():\n    obj = m.ToBeHeldByUniquePtr()\n    with pytest.raises(RuntimeError) as execinfo:\n        m.pass_unique_ptr(obj)\n    assert str(execinfo.value).startswith(\n        \"Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, py::smart_holder>` (with T = \"\n    )\n    assert \"ToBeHeldByUniquePtr\" in str(execinfo.value)\n\n\ndef test_type():\n    assert m.check_type(1) == m.DerivedClass1\n    with pytest.raises(RuntimeError) as execinfo:\n        m.check_type(0)\n\n    assert \"pybind11::detail::get_type_info: unable to find type info\" in str(\n        execinfo.value\n    )\n    assert \"Invalid\" in str(execinfo.value)\n\n    # Currently not supported\n    # See https://github.com/pybind/pybind11/issues/2486\n    # assert m.check_type(2) == int\n\n\ndef test_type_of_py():\n    assert m.get_type_of(1) == int\n    assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1\n    assert m.get_type_of(int) == type\n\n\ndef test_type_of_classic():\n    assert m.get_type_classic(1) == int\n    assert m.get_type_classic(m.DerivedClass1()) == m.DerivedClass1\n    assert m.get_type_classic(int) == type\n\n\ndef test_type_of_py_nodelete():\n    # If the above test deleted the class, this will segfault\n    assert m.get_type_of(m.DerivedClass1()) == m.DerivedClass1\n\n\ndef test_as_type_py():\n    assert m.as_type(int) == int\n\n    with pytest.raises(TypeError):\n        assert m.as_type(1) == int\n\n    with pytest.raises(TypeError):\n        assert m.as_type(m.DerivedClass1()) == m.DerivedClass1\n\n\ndef test_docstrings(doc):\n    assert doc(UserType) == \"A `py::class_` type for testing\"\n    assert UserType.__name__ == \"UserType\"\n    assert UserType.__module__ == \"pybind11_tests\"\n    assert UserType.get_value.__name__ == \"get_value\"\n    assert UserType.get_value.__module__ == \"pybind11_tests\"\n\n    assert (\n        doc(UserType.get_value)\n        == \"\"\"\n        get_value(self: m.UserType) -> int\n\n        Get value using a method\n    \"\"\"\n    )\n    assert doc(UserType.value) == \"Get/set value using a property\"\n\n    assert (\n        doc(m.NoConstructor.new_instance)\n        == \"\"\"\n        new_instance() -> m.class_.NoConstructor\n\n        Return an instance\n    \"\"\"\n    )\n\n\ndef test_qualname(doc):\n    \"\"\"Tests that a properly qualified name is set in __qualname__ and that\n    generated docstrings properly use it and the module name\"\"\"\n    assert m.NestBase.__qualname__ == \"NestBase\"\n    assert m.NestBase.Nested.__qualname__ == \"NestBase.Nested\"\n\n    assert (\n        doc(m.NestBase.__init__)\n        == \"\"\"\n        __init__(self: m.class_.NestBase) -> None\n    \"\"\"\n    )\n    assert (\n        doc(m.NestBase.g)\n        == \"\"\"\n        g(self: m.class_.NestBase, arg0: m.class_.NestBase.Nested) -> None\n    \"\"\"\n    )\n    assert (\n        doc(m.NestBase.Nested.__init__)\n        == \"\"\"\n        __init__(self: m.class_.NestBase.Nested) -> None\n    \"\"\"\n    )\n    assert (\n        doc(m.NestBase.Nested.fn)\n        == \"\"\"\n        fn(self: m.class_.NestBase.Nested, arg0: typing.SupportsInt | typing.SupportsIndex, arg1: m.class_.NestBase, arg2: m.class_.NestBase.Nested) -> None\n    \"\"\"\n    )\n    assert (\n        doc(m.NestBase.Nested.fa)\n        == \"\"\"\n        fa(self: m.class_.NestBase.Nested, a: typing.SupportsInt | typing.SupportsIndex, b: m.class_.NestBase, c: m.class_.NestBase.Nested) -> None\n    \"\"\"\n    )\n    assert m.NestBase.__module__ == \"pybind11_tests.class_\"\n    assert m.NestBase.Nested.__module__ == \"pybind11_tests.class_\"\n\n\ndef test_inheritance(msg):\n    roger = m.Rabbit(\"Rabbit\")\n    assert roger.name() + \" is a \" + roger.species() == \"Rabbit is a parrot\"\n    assert m.pet_name_species(roger) == \"Rabbit is a parrot\"\n\n    polly = m.Pet(\"Polly\", \"parrot\")\n    assert polly.name() + \" is a \" + polly.species() == \"Polly is a parrot\"\n    assert m.pet_name_species(polly) == \"Polly is a parrot\"\n\n    molly = m.Dog(\"Molly\")\n    assert molly.name() + \" is a \" + molly.species() == \"Molly is a dog\"\n    assert m.pet_name_species(molly) == \"Molly is a dog\"\n\n    fred = m.Hamster(\"Fred\")\n    assert fred.name() + \" is a \" + fred.species() == \"Fred is a rodent\"\n\n    assert m.dog_bark(molly) == \"Woof!\"\n\n    with pytest.raises(TypeError) as excinfo:\n        m.dog_bark(polly)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        dog_bark(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: m.class_.Dog) -> str\n\n        Invoked with: <m.class_.Pet object at 0>\n    \"\"\"\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        m.Chimera(\"lion\", \"goat\")\n    assert \"No constructor defined!\" in str(excinfo.value)\n\n\ndef test_inheritance_init(msg):\n    # Single base\n    class Python(m.Pet):\n        def __init__(self):\n            pass\n\n    with pytest.raises(TypeError) as exc_info:\n        Python()\n    expected = \"m.class_.Pet.__init__() must be called when overriding __init__\"\n    assert msg(exc_info.value) == expected\n\n    # Multiple bases\n    class RabbitHamster(m.Rabbit, m.Hamster):\n        def __init__(self):\n            m.Rabbit.__init__(self, \"RabbitHamster\")\n\n    with pytest.raises(TypeError) as exc_info:\n        RabbitHamster()\n    expected = \"m.class_.Hamster.__init__() must be called when overriding __init__\"\n    assert msg(exc_info.value) == expected\n\n\n@pytest.mark.parametrize(\n    \"mock_return_value\", [None, (1, 2, 3), m.Pet(\"Polly\", \"parrot\"), m.Dog(\"Molly\")]\n)\ndef test_mock_new(mock_return_value):\n    with mock.patch.object(\n        m.Pet, \"__new__\", return_value=mock_return_value\n    ) as mock_new:\n        obj = m.Pet(\"Noname\", \"Nospecies\")\n    assert obj is mock_return_value\n    mock_new.assert_called_once_with(m.Pet, \"Noname\", \"Nospecies\")\n\n\ndef test_automatic_upcasting():\n    assert type(m.return_class_1()).__name__ == \"DerivedClass1\"\n    assert type(m.return_class_2()).__name__ == \"DerivedClass2\"\n    assert type(m.return_none()).__name__ == \"NoneType\"\n    # Repeat these a few times in a random order to ensure no invalid caching is applied\n    assert type(m.return_class_n(1)).__name__ == \"DerivedClass1\"\n    assert type(m.return_class_n(2)).__name__ == \"DerivedClass2\"\n    assert type(m.return_class_n(0)).__name__ == \"BaseClass\"\n    assert type(m.return_class_n(2)).__name__ == \"DerivedClass2\"\n    assert type(m.return_class_n(2)).__name__ == \"DerivedClass2\"\n    assert type(m.return_class_n(0)).__name__ == \"BaseClass\"\n    assert type(m.return_class_n(1)).__name__ == \"DerivedClass1\"\n\n\ndef test_isinstance():\n    objects = [(), {}, m.Pet(\"Polly\", \"parrot\")] + [m.Dog(\"Molly\")] * 4\n    expected = (True, True, True, True, True, False, False)\n    assert m.check_instances(objects) == expected\n\n\ndef test_mismatched_holder():\n    import re\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.mismatched_holder_1()\n    assert re.match(\n        'generic_type: type \".*MismatchDerived1\" does not have a non-default '\n        'holder type while its base \".*MismatchBase1\" does',\n        str(excinfo.value),\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.mismatched_holder_2()\n    assert re.match(\n        'generic_type: type \".*MismatchDerived2\" has a non-default holder type '\n        'while its base \".*MismatchBase2\" does not',\n        str(excinfo.value),\n    )\n\n\ndef test_override_static():\n    \"\"\"#511: problem with inheritance + overwritten def_static\"\"\"\n    b = m.MyBase.make()\n    d1 = m.MyDerived.make2()\n    d2 = m.MyDerived.make()\n\n    assert isinstance(b, m.MyBase)\n    assert isinstance(d1, m.MyDerived)\n    assert isinstance(d2, m.MyDerived)\n\n\ndef test_implicit_conversion_life_support():\n    \"\"\"Ensure the lifetime of temporary objects created for implicit conversions\"\"\"\n    assert m.implicitly_convert_argument(UserType(5)) == 5\n    assert m.implicitly_convert_variable(UserType(5)) == 5\n\n    assert \"outside a bound function\" in m.implicitly_convert_variable_fail(UserType(5))\n\n\ndef test_operator_new_delete(capture):\n    \"\"\"Tests that class-specific operator new/delete functions are invoked\"\"\"\n\n    class SubAliased(m.AliasedHasOpNewDelSize):\n        pass\n\n    with capture:\n        a = m.HasOpNewDel()\n        b = m.HasOpNewDelSize()\n        d = m.HasOpNewDelBoth()\n    assert (\n        capture\n        == \"\"\"\n        A new 8\n        B new 4\n        D new 32\n    \"\"\"\n    )\n    sz_alias = str(m.AliasedHasOpNewDelSize.size_alias)\n    sz_noalias = str(m.AliasedHasOpNewDelSize.size_noalias)\n    with capture:\n        c = m.AliasedHasOpNewDelSize()\n        c2 = SubAliased()\n    assert capture == (\"C new \" + sz_noalias + \"\\n\" + \"C new \" + sz_alias + \"\\n\")\n\n    with capture:\n        del a\n        pytest.gc_collect()\n        del b\n        pytest.gc_collect()\n        del d\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        A delete\n        B delete 4\n        D delete\n    \"\"\"\n    )\n\n    with capture:\n        del c\n        pytest.gc_collect()\n        del c2\n        pytest.gc_collect()\n    assert capture == (\"C delete \" + sz_noalias + \"\\n\" + \"C delete \" + sz_alias + \"\\n\")\n\n\ndef test_bind_protected_functions():\n    \"\"\"Expose protected member functions to Python using a helper class\"\"\"\n    a = m.ProtectedA()\n    assert a.foo() == 42\n\n    b = m.ProtectedB()\n    assert b.foo() == 42\n    assert m.read_foo(b.void_foo()) == 42\n    assert m.pointers_equal(b.get_self(), b)\n\n    class C(m.ProtectedB):\n        def __init__(self):\n            m.ProtectedB.__init__(self)\n\n        def foo(self):\n            return 0\n\n    c = C()\n    assert c.foo() == 0\n\n\ndef test_brace_initialization():\n    \"\"\"Tests that simple POD classes can be constructed using C++11 brace initialization\"\"\"\n    a = m.BraceInitialization(123, \"test\")\n    assert a.field1 == 123\n    assert a.field2 == \"test\"\n\n    # Tests that a non-simple class doesn't get brace initialization (if the\n    # class defines an initializer_list constructor, in particular, it would\n    # win over the expected constructor).\n    b = m.NoBraceInitialization([123, 456])\n    assert b.vec == [123, 456]\n\n\n@pytest.mark.xfail(\"env.PYPY or env.GRAALPY\")\ndef test_class_refcount():\n    \"\"\"Instances must correctly increase/decrease the reference count of their types (#1029)\"\"\"\n\n    class PyDog(m.Dog):\n        pass\n\n    for cls in m.Dog, PyDog:\n        refcount_1 = refcount_immortal(cls)\n        molly = [cls(\"Molly\") for _ in range(10)]\n        refcount_2 = refcount_immortal(cls)\n\n        del molly\n        pytest.gc_collect()\n        refcount_3 = refcount_immortal(cls)\n\n        # Python may report a large value here (above 30 bits), that's also fine\n        assert refcount_1 == refcount_3\n        assert (refcount_2 > refcount_1) or (\n            refcount_2 == refcount_1 and refcount_1 >= 2**29\n        )\n\n\ndef test_reentrant_implicit_conversion_failure(msg):\n    # ensure that there is no runaway reentrant implicit conversion (#1035)\n    with pytest.raises(TypeError) as excinfo:\n        m.BogusImplicitConversion(0)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        __init__(): incompatible constructor arguments. The following argument types are supported:\n            1. m.class_.BogusImplicitConversion(arg0: m.class_.BogusImplicitConversion)\n\n        Invoked with: 0\n    \"\"\"\n    )\n\n\ndef test_error_after_conversions():\n    with pytest.raises(TypeError) as exc_info:\n        m.test_error_after_conversions(\"hello\")\n    assert str(exc_info.value).startswith(\n        \"Unable to convert function return value to a Python type!\"\n    )\n\n\ndef test_aligned():\n    if hasattr(m, \"Aligned\"):\n        p = m.Aligned().ptr()\n        assert p % 1024 == 0\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2742\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_final():\n    with pytest.raises(TypeError) as exc_info:\n\n        class PyFinalChild(m.IsFinal):\n            pass\n\n    assert str(exc_info.value).endswith(\"is not an acceptable base type\")\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2742\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_non_final_final():\n    with pytest.raises(TypeError) as exc_info:\n\n        class PyNonFinalFinalChild(m.IsNonFinalFinal):\n            pass\n\n    assert str(exc_info.value).endswith(\"is not an acceptable base type\")\n\n\n# https://github.com/pybind/pybind11/issues/1878\ndef test_exception_rvalue_abort():\n    with pytest.raises(RuntimeError):\n        m.PyPrintDestructor().throw_something()\n\n\n# https://github.com/pybind/pybind11/issues/1568\ndef test_multiple_instances_with_same_pointer():\n    n = 100\n    instances = [m.SamePointer() for _ in range(n)]\n    for i in range(n):\n        # We need to reuse the same allocated memory for with a different type,\n        # to ensure the bug in `deregister_instance_impl` is detected. Otherwise\n        # `Py_TYPE(self) == Py_TYPE(it->second)` will still succeed, even though\n        # the `instance` is already deleted.\n        instances[i] = m.Empty()\n    # No assert: if this does not trigger the error\n    #   pybind11_fail(\"pybind11_object_dealloc(): Tried to deallocate unregistered instance!\");\n    # and just completes without crashing, we're good.\n\n\n# https://github.com/pybind/pybind11/issues/1624\ndef test_base_and_derived_nested_scope():\n    assert issubclass(m.DerivedWithNested, m.BaseWithNested)\n    assert m.BaseWithNested.Nested != m.DerivedWithNested.Nested\n    assert m.BaseWithNested.Nested.get_name() == \"BaseWithNested::Nested\"\n    assert m.DerivedWithNested.Nested.get_name() == \"DerivedWithNested::Nested\"\n\n\ndef test_register_duplicate_class():\n    import types\n\n    module_scope = types.ModuleType(\"module_scope\")\n    with pytest.raises(RuntimeError) as exc_info:\n        m.register_duplicate_class_name(module_scope)\n    expected = (\n        'generic_type: cannot initialize type \"Duplicate\": '\n        \"an object with that name is already defined\"\n    )\n    assert str(exc_info.value) == expected\n    with pytest.raises(RuntimeError) as exc_info:\n        m.register_duplicate_class_type(module_scope)\n    expected = 'generic_type: type \"YetAnotherDuplicate\" is already registered!'\n    assert str(exc_info.value) == expected\n\n    class ClassScope:\n        pass\n\n    with pytest.raises(RuntimeError) as exc_info:\n        m.register_duplicate_nested_class_name(ClassScope)\n    expected = (\n        'generic_type: cannot initialize type \"DuplicateNested\": '\n        \"an object with that name is already defined\"\n    )\n    assert str(exc_info.value) == expected\n    with pytest.raises(RuntimeError) as exc_info:\n        m.register_duplicate_nested_class_type(ClassScope)\n    expected = 'generic_type: type \"YetAnotherDuplicateNested\" is already registered!'\n    assert str(exc_info.value) == expected\n\n\ndef test_pr4220_tripped_over_this():\n    assert (\n        m.Empty0().get_msg()\n        == \"This is really only meant to exercise successful compilation.\"\n    )\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_all_type_info_multithreaded():\n    # See PR #5419 for background.\n    import threading\n\n    from pybind11_tests import TestContext\n\n    class Context(TestContext):\n        pass\n\n    num_runs = 10\n    num_threads = 4\n    barrier = threading.Barrier(num_threads)\n\n    def func():\n        barrier.wait()\n        with Context():\n            pass\n\n    for _ in range(num_runs):\n        threads = [threading.Thread(target=func) for _ in range(num_threads)]\n        for thread in threads:\n            thread.start()\n\n        for thread in threads:\n            thread.join()\n"
  },
  {
    "path": "tests/test_class_cross_module_use_after_one_module_dealloc.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <iostream>\n\nclass CrossDSOClass {\npublic:\n    CrossDSOClass() = default;\n    virtual ~CrossDSOClass();\n    CrossDSOClass(const CrossDSOClass &) = default;\n};\n\nCrossDSOClass::~CrossDSOClass() = default;\n\nstruct UnrelatedClass {};\n\nTEST_SUBMODULE(class_cross_module_use_after_one_module_dealloc, m) {\n    m.def(\"register_and_instantiate_cross_dso_class\", [](const py::module_ &m) {\n        py::class_<CrossDSOClass>(m, \"CrossDSOClass\").def(py::init<>());\n        return CrossDSOClass();\n    });\n    m.def(\"register_unrelated_class\",\n          [](const py::module_ &m) { py::class_<UnrelatedClass>(m, \"UnrelatedClass\"); });\n}\n"
  },
  {
    "path": "tests/test_class_cross_module_use_after_one_module_dealloc.py",
    "content": "from __future__ import annotations\n\nimport types\n\nimport pytest\n\nimport env\nfrom pybind11_tests import class_cross_module_use_after_one_module_dealloc as m\n\n\n@pytest.mark.skipif(\n    env.TYPES_ARE_IMMORTAL, reason=\"can't GC type objects on this platform\"\n)\ndef test_cross_module_use_after_one_module_dealloc():\n    # This is a regression test for a bug that occurred during development of\n    # internals::registered_types_cpp_fast (see #5842). registered_types_cpp_fast maps\n    # &typeid(T) to a raw non-owning pointer to a Python type object. If two DSOs both\n    # look up the same global type, they will create two separate entries in\n    # registered_types_cpp_fast, which will look like:\n    # +=========================================+\n    # |&typeid(T) from DSO 1|type object pointer|\n    # |&typeid(T) from DSO 2|type object pointer|\n    # +=========================================+\n    #\n    # Then, if the type object is destroyed and we don't take extra steps to clean up\n    # the table thoroughly, the first row of the table will be cleaned up but the second\n    # one will contain a dangling pointer to the old type object. Further lookups from\n    # DSO 2 will then return that dangling pointer, which will cause use-after-frees.\n\n    import pybind11_cross_module_tests as cm\n\n    module_scope = types.ModuleType(\"module_scope\")\n    instance = m.register_and_instantiate_cross_dso_class(module_scope)\n    cm.consume_cross_dso_class(instance)\n\n    del instance\n    pytest.delattr_and_ensure_destroyed((module_scope, \"CrossDSOClass\"))\n\n    # Make sure that CrossDSOClass gets allocated at a different address.\n    m.register_unrelated_class(module_scope)\n\n    instance = m.register_and_instantiate_cross_dso_class(module_scope)\n    cm.consume_cross_dso_class(instance)\n"
  },
  {
    "path": "tests/test_class_release_gil_before_calling_cpp_dtor.cpp",
    "content": "#include <pybind11/pybind11.h>\n\n#include \"pybind11_tests.h\"\n\n#include <string>\n#include <unordered_map>\n\nnamespace pybind11_tests {\nnamespace class_release_gil_before_calling_cpp_dtor {\n\nusing RegistryType = std::unordered_map<std::string, int>;\n\nstatic RegistryType &PyGILState_Check_Results() {\n    static RegistryType singleton; // Local static variables have thread-safe initialization.\n    return singleton;\n}\n\ntemplate <int> // Using int as a trick to easily generate a series of types.\nstruct ProbeType {\nprivate:\n    std::string unique_key;\n\npublic:\n    explicit ProbeType(const std::string &unique_key) : unique_key{unique_key} {}\n    ProbeType(const ProbeType &) = default;\n\n    ~ProbeType() {\n        RegistryType &reg = PyGILState_Check_Results();\n        assert(reg.count(unique_key) == 0);\n        reg[unique_key] = PyGILState_Check();\n    }\n};\n\n} // namespace class_release_gil_before_calling_cpp_dtor\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(class_release_gil_before_calling_cpp_dtor, m) {\n    using namespace pybind11_tests::class_release_gil_before_calling_cpp_dtor;\n\n    py::class_<ProbeType<0>>(m, \"ProbeType0\").def(py::init<std::string>());\n\n    py::class_<ProbeType<1>>(m, \"ProbeType1\", py::release_gil_before_calling_cpp_dtor())\n        .def(py::init<std::string>());\n\n    m.def(\"PopPyGILState_Check_Result\", [](const std::string &unique_key) -> std::string {\n        RegistryType &reg = PyGILState_Check_Results();\n        if (reg.count(unique_key) == 0) {\n            return \"MISSING\";\n        }\n        int res = reg[unique_key];\n        reg.erase(unique_key);\n        return std::to_string(res);\n    });\n}\n"
  },
  {
    "path": "tests/test_class_release_gil_before_calling_cpp_dtor.py",
    "content": "from __future__ import annotations\n\nimport gc\n\nimport pytest\n\nfrom pybind11_tests import class_release_gil_before_calling_cpp_dtor as m\n\n\n@pytest.mark.parametrize(\n    (\"probe_type\", \"unique_key\", \"expected_result\"),\n    [\n        (m.ProbeType0, \"without_manipulating_gil\", \"1\"),\n        (m.ProbeType1, \"release_gil_before_calling_cpp_dtor\", \"0\"),\n    ],\n)\ndef test_gil_state_check_results(probe_type, unique_key, expected_result):\n    probe_type(unique_key)\n    gc.collect()\n    result = m.PopPyGILState_Check_Result(unique_key)\n    assert result == expected_result\n"
  },
  {
    "path": "tests/test_class_sh_basic.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace pybind11_tests {\nnamespace class_sh_basic {\n\nstruct atyp { // Short for \"any type\".\n    std::string mtxt;\n    atyp() : mtxt(\"DefaultConstructor\") {}\n    explicit atyp(const std::string &mtxt_) : mtxt(mtxt_) {}\n    atyp(const atyp &other) { mtxt = other.mtxt + \"_CpCtor\"; }\n    atyp(atyp &&other) noexcept { mtxt = other.mtxt + \"_MvCtor\"; }\n};\n\nstruct uconsumer { // unique_ptr consumer\n    std::unique_ptr<atyp> held;\n    bool valid() const { return static_cast<bool>(held); }\n\n    void pass_valu(std::unique_ptr<atyp> obj) { held = std::move(obj); }\n    void pass_rref(std::unique_ptr<atyp> &&obj) { held = std::move(obj); }\n    std::unique_ptr<atyp> rtrn_valu() { return std::move(held); }\n    std::unique_ptr<atyp> &rtrn_lref() { return held; }\n    const std::unique_ptr<atyp> &rtrn_cref() const { return held; }\n};\n\n/// Custom deleter that is default constructible.\nstruct custom_deleter {\n    std::string trace_txt;\n\n    custom_deleter() = default;\n    explicit custom_deleter(const std::string &trace_txt_) : trace_txt(trace_txt_) {}\n\n    custom_deleter(const custom_deleter &other) { trace_txt = other.trace_txt + \"_CpCtor\"; }\n\n    custom_deleter &operator=(const custom_deleter &rhs) {\n        trace_txt = rhs.trace_txt + \"_CpLhs\";\n        return *this;\n    }\n\n    custom_deleter(custom_deleter &&other) noexcept {\n        trace_txt = other.trace_txt + \"_MvCtorTo\";\n        other.trace_txt += \"_MvCtorFrom\";\n    }\n\n    custom_deleter &operator=(custom_deleter &&rhs) noexcept {\n        trace_txt = rhs.trace_txt + \"_MvLhs\";\n        rhs.trace_txt += \"_MvRhs\";\n        return *this;\n    }\n\n    void operator()(atyp *p) const { std::default_delete<atyp>()(p); }\n    void operator()(const atyp *p) const { std::default_delete<const atyp>()(p); }\n};\nstatic_assert(std::is_default_constructible<custom_deleter>::value, \"\");\n\n/// Custom deleter that is not default constructible.\nstruct custom_deleter_nd : custom_deleter {\n    custom_deleter_nd() = delete;\n    explicit custom_deleter_nd(const std::string &trace_txt_) : custom_deleter(trace_txt_) {}\n};\nstatic_assert(!std::is_default_constructible<custom_deleter_nd>::value, \"\");\n\n// clang-format off\n\natyp        rtrn_valu() { atyp obj{\"rtrn_valu\"}; return obj; }\natyp&&      rtrn_rref() { static atyp obj; obj.mtxt = \"rtrn_rref\"; return std::move(obj); }\natyp const& rtrn_cref() { static atyp obj; obj.mtxt = \"rtrn_cref\"; return obj; }\natyp&       rtrn_mref() { static atyp obj; obj.mtxt = \"rtrn_mref\"; return obj; }\natyp const* rtrn_cptr() { return new atyp{\"rtrn_cptr\"}; }\natyp*       rtrn_mptr() { return new atyp{\"rtrn_mptr\"}; }\n\nstd::string pass_valu(atyp obj)        { return \"pass_valu:\" + obj.mtxt; } // NOLINT\nstd::string pass_cref(atyp const& obj) { return \"pass_cref:\" + obj.mtxt; }\nstd::string pass_mref(atyp& obj)       { return \"pass_mref:\" + obj.mtxt; }\nstd::string pass_cptr(atyp const* obj) { return \"pass_cptr:\" + obj->mtxt; }\nstd::string pass_mptr(atyp* obj)       { return \"pass_mptr:\" + obj->mtxt; }\n\nstd::shared_ptr<atyp>       rtrn_shmp() { return std::make_shared<atyp>(\"rtrn_shmp\"); }\nstd::shared_ptr<atyp const> rtrn_shcp() { return std::shared_ptr<atyp const>(new atyp{\"rtrn_shcp\"}); }\n\nstd::string pass_shmp(std::shared_ptr<atyp>       obj) { return \"pass_shmp:\" + obj->mtxt; } // NOLINT\nstd::string pass_shcp(std::shared_ptr<atyp const> obj) { return \"pass_shcp:\" + obj->mtxt; } // NOLINT\n\nstd::unique_ptr<atyp>       rtrn_uqmp() { return std::unique_ptr<atyp      >(new atyp{\"rtrn_uqmp\"}); }\nstd::unique_ptr<atyp const> rtrn_uqcp() { return std::unique_ptr<atyp const>(new atyp{\"rtrn_uqcp\"}); }\n\nstd::string pass_uqmp(std::unique_ptr<atyp      > obj) { return \"pass_uqmp:\" + obj->mtxt; }\nstd::string pass_uqcp(std::unique_ptr<atyp const> obj) { return \"pass_uqcp:\" + obj->mtxt; }\n\nstruct sddm : std::default_delete<atyp      > {};\nstruct sddc : std::default_delete<atyp const> {};\n\nstd::unique_ptr<atyp,       sddm> rtrn_udmp() { return std::unique_ptr<atyp,       sddm>(new atyp{\"rtrn_udmp\"}); }\nstd::unique_ptr<atyp const, sddc> rtrn_udcp() { return std::unique_ptr<atyp const, sddc>(new atyp{\"rtrn_udcp\"}); }\n\nstd::string pass_udmp(std::unique_ptr<atyp,       sddm> obj) { return \"pass_udmp:\" + obj->mtxt; }\nstd::string pass_udcp(std::unique_ptr<atyp const, sddc> obj) { return \"pass_udcp:\" + obj->mtxt; }\n\nstd::unique_ptr<atyp,       custom_deleter> rtrn_udmp_del() { return std::unique_ptr<atyp,       custom_deleter>(new atyp{\"rtrn_udmp_del\"}, custom_deleter{\"udmp_deleter\"}); }\nstd::unique_ptr<atyp const, custom_deleter> rtrn_udcp_del() { return std::unique_ptr<atyp const, custom_deleter>(new atyp{\"rtrn_udcp_del\"}, custom_deleter{\"udcp_deleter\"}); }\n\nstd::string pass_udmp_del(std::unique_ptr<atyp,       custom_deleter> obj) { return \"pass_udmp_del:\" + obj->mtxt + \",\" + obj.get_deleter().trace_txt; }\nstd::string pass_udcp_del(std::unique_ptr<atyp const, custom_deleter> obj) { return \"pass_udcp_del:\" + obj->mtxt + \",\" + obj.get_deleter().trace_txt; }\n\nstd::unique_ptr<atyp,       custom_deleter_nd> rtrn_udmp_del_nd() { return std::unique_ptr<atyp,       custom_deleter_nd>(new atyp{\"rtrn_udmp_del_nd\"}, custom_deleter_nd{\"udmp_deleter_nd\"}); }\nstd::unique_ptr<atyp const, custom_deleter_nd> rtrn_udcp_del_nd() { return std::unique_ptr<atyp const, custom_deleter_nd>(new atyp{\"rtrn_udcp_del_nd\"}, custom_deleter_nd{\"udcp_deleter_nd\"}); }\n\nstd::string pass_udmp_del_nd(std::unique_ptr<atyp,       custom_deleter_nd> obj) { return \"pass_udmp_del_nd:\" + obj->mtxt + \",\" + obj.get_deleter().trace_txt; }\nstd::string pass_udcp_del_nd(std::unique_ptr<atyp const, custom_deleter_nd> obj) { return \"pass_udcp_del_nd:\" + obj->mtxt + \",\" + obj.get_deleter().trace_txt; }\n\n// clang-format on\n\n// Helpers for testing.\nstd::string get_mtxt(atyp const &obj) { return obj.mtxt; }\nstd::ptrdiff_t get_ptr(atyp const &obj) { return reinterpret_cast<std::ptrdiff_t>(&obj); }\n\nstd::unique_ptr<atyp> unique_ptr_roundtrip(std::unique_ptr<atyp> obj) { return obj; }\n\nstd::string pass_unique_ptr_cref(const std::unique_ptr<atyp> &obj) { return obj->mtxt; }\n\nconst std::unique_ptr<atyp> &rtrn_unique_ptr_cref(const std::string &mtxt) {\n    static std::unique_ptr<atyp> obj{new atyp{\"static_ctor_arg\"}};\n    if (!mtxt.empty()) {\n        obj->mtxt = mtxt;\n    }\n    return obj;\n}\n\nconst std::unique_ptr<atyp> &unique_ptr_cref_roundtrip(const std::unique_ptr<atyp> &obj) {\n    // This is passed in, so it can't be given a temporary\n    return obj; // NOLINT(bugprone-return-const-ref-from-parameter)\n}\n\nstruct SharedPtrStash {\n    std::vector<std::shared_ptr<const atyp>> stash;\n    void Add(const std::shared_ptr<const atyp> &obj) { stash.push_back(obj); }\n};\n\nclass LocalUnusualOpRef : UnusualOpRef {}; // To avoid clashing with `py::class_<UnusualOpRef>`.\npy::object CastUnusualOpRefConstRef(const LocalUnusualOpRef &cref) { return py::cast(cref); }\npy::object CastUnusualOpRefMovable(LocalUnusualOpRef &&mvbl) { return py::cast(std::move(mvbl)); }\n\nTEST_SUBMODULE(class_sh_basic, m) {\n    namespace py = pybind11;\n\n    py::classh<atyp>(m, \"atyp\").def(py::init<>()).def(py::init([](const std::string &mtxt) {\n        atyp obj;\n        obj.mtxt = mtxt;\n        return obj;\n    }));\n\n    m.def(\"rtrn_valu\", rtrn_valu);\n    m.def(\"rtrn_rref\", rtrn_rref);\n    m.def(\"rtrn_cref\", rtrn_cref);\n    m.def(\"rtrn_mref\", rtrn_mref);\n    m.def(\"rtrn_cptr\", rtrn_cptr);\n    m.def(\"rtrn_mptr\", rtrn_mptr);\n\n    m.def(\"pass_valu\", pass_valu);\n    m.def(\"pass_cref\", pass_cref);\n    m.def(\"pass_mref\", pass_mref);\n    m.def(\"pass_cptr\", pass_cptr);\n    m.def(\"pass_mptr\", pass_mptr);\n\n    m.def(\"rtrn_shmp\", rtrn_shmp);\n    m.def(\"rtrn_shcp\", rtrn_shcp);\n\n    m.def(\"pass_shmp\", pass_shmp);\n    m.def(\"pass_shcp\", pass_shcp);\n\n    m.def(\"rtrn_uqmp\", rtrn_uqmp);\n    m.def(\"rtrn_uqcp\", rtrn_uqcp);\n\n    m.def(\"pass_uqmp\", pass_uqmp);\n    m.def(\"pass_uqcp\", pass_uqcp);\n\n    m.def(\"rtrn_udmp\", rtrn_udmp);\n    m.def(\"rtrn_udcp\", rtrn_udcp);\n\n    m.def(\"pass_udmp\", pass_udmp);\n    m.def(\"pass_udcp\", pass_udcp);\n\n    m.def(\"rtrn_udmp_del\", rtrn_udmp_del);\n    m.def(\"rtrn_udcp_del\", rtrn_udcp_del);\n\n    m.def(\"pass_udmp_del\", pass_udmp_del);\n    m.def(\"pass_udcp_del\", pass_udcp_del);\n\n    m.def(\"rtrn_udmp_del_nd\", rtrn_udmp_del_nd);\n    m.def(\"rtrn_udcp_del_nd\", rtrn_udcp_del_nd);\n\n    m.def(\"pass_udmp_del_nd\", pass_udmp_del_nd);\n    m.def(\"pass_udcp_del_nd\", pass_udcp_del_nd);\n\n    py::classh<uconsumer>(m, \"uconsumer\")\n        .def(py::init<>())\n        .def(\"valid\", &uconsumer::valid)\n        .def(\"pass_valu\", &uconsumer::pass_valu)\n        .def(\"pass_rref\", &uconsumer::pass_rref)\n        .def(\"rtrn_valu\", &uconsumer::rtrn_valu)\n        .def(\"rtrn_lref\", &uconsumer::rtrn_lref)\n        .def(\"rtrn_cref\", &uconsumer::rtrn_cref);\n\n    // Helpers for testing.\n    // These require selected functions above to work first, as indicated:\n    m.def(\"get_mtxt\", get_mtxt); // pass_cref\n    m.def(\"get_ptr\", get_ptr);   // pass_cref\n\n    m.def(\"unique_ptr_roundtrip\", unique_ptr_roundtrip); // pass_uqmp, rtrn_uqmp\n\n    m.def(\"pass_unique_ptr_cref\", pass_unique_ptr_cref);\n    m.def(\"rtrn_unique_ptr_cref\", rtrn_unique_ptr_cref);\n    m.def(\"unique_ptr_cref_roundtrip\", unique_ptr_cref_roundtrip);\n\n    py::classh<SharedPtrStash>(m, \"SharedPtrStash\")\n        .def(py::init<>())\n        .def(\"Add\", &SharedPtrStash::Add, py::arg(\"obj\"));\n\n    m.def(\"py_type_handle_of_atyp\", []() {\n        return py::type::handle_of<atyp>(); // Exercises static_cast in this function.\n    });\n\n    // Checks for type names used as arguments\n    m.def(\"args_shared_ptr\", [](std::shared_ptr<atyp> p) { return p; });\n    m.def(\"args_shared_ptr_const\", [](std::shared_ptr<atyp const> p) { return p; });\n    m.def(\"args_unique_ptr\", [](std::unique_ptr<atyp> p) { return p; });\n    m.def(\"args_unique_ptr_const\", [](std::unique_ptr<atyp const> p) { return p; });\n\n    // Make sure unique_ptr type caster accept automatic_reference return value policy.\n    m.def(\n        \"rtrn_uq_automatic_reference\",\n        []() { return std::unique_ptr<atyp>(new atyp(\"rtrn_uq_automatic_reference\")); },\n        pybind11::return_value_policy::automatic_reference);\n\n    m.def(\"pass_shared_ptr_ptr\", [](std::shared_ptr<atyp> *) {});\n\n    py::classh<LocalUnusualOpRef>(m, \"LocalUnusualOpRef\");\n    m.def(\"CallCastUnusualOpRefConstRef\",\n          []() { return CastUnusualOpRefConstRef(LocalUnusualOpRef()); });\n    m.def(\"CallCastUnusualOpRefMovable\",\n          []() { return CastUnusualOpRefMovable(LocalUnusualOpRef()); });\n}\n\n} // namespace class_sh_basic\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_class_sh_basic.py",
    "content": "# Importing re before pytest after observing a PyPy CI flake when importing pytest first.\nfrom __future__ import annotations\n\nimport re\n\nimport pytest\n\nfrom pybind11_tests import class_sh_basic as m\n\n\ndef test_atyp_constructors():\n    obj = m.atyp()\n    assert obj.__class__.__name__ == \"atyp\"\n    obj = m.atyp(\"\")\n    assert obj.__class__.__name__ == \"atyp\"\n    obj = m.atyp(\"txtm\")\n    assert obj.__class__.__name__ == \"atyp\"\n\n\n@pytest.mark.parametrize(\n    (\"rtrn_f\", \"expected\"),\n    [\n        (m.rtrn_valu, \"rtrn_valu(_MvCtor)*_MvCtor\"),\n        (m.rtrn_rref, \"rtrn_rref(_MvCtor)*_MvCtor\"),\n        (m.rtrn_cref, \"rtrn_cref(_MvCtor)*_CpCtor\"),\n        (m.rtrn_mref, \"rtrn_mref(_MvCtor)*_CpCtor\"),\n        (m.rtrn_cptr, \"rtrn_cptr\"),\n        (m.rtrn_mptr, \"rtrn_mptr\"),\n        (m.rtrn_shmp, \"rtrn_shmp\"),\n        (m.rtrn_shcp, \"rtrn_shcp\"),\n        (m.rtrn_uqmp, \"rtrn_uqmp\"),\n        (m.rtrn_uqcp, \"rtrn_uqcp\"),\n        (m.rtrn_udmp, \"rtrn_udmp\"),\n        (m.rtrn_udcp, \"rtrn_udcp\"),\n    ],\n)\ndef test_cast(rtrn_f, expected):\n    assert re.match(expected, m.get_mtxt(rtrn_f()))\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"mtxt\", \"expected\"),\n    [\n        (m.pass_valu, \"Valu\", \"pass_valu:Valu(_MvCtor)*_CpCtor\"),\n        (m.pass_cref, \"Cref\", \"pass_cref:Cref(_MvCtor)*_MvCtor\"),\n        (m.pass_mref, \"Mref\", \"pass_mref:Mref(_MvCtor)*_MvCtor\"),\n        (m.pass_cptr, \"Cptr\", \"pass_cptr:Cptr(_MvCtor)*_MvCtor\"),\n        (m.pass_mptr, \"Mptr\", \"pass_mptr:Mptr(_MvCtor)*_MvCtor\"),\n        (m.pass_shmp, \"Shmp\", \"pass_shmp:Shmp(_MvCtor)*_MvCtor\"),\n        (m.pass_shcp, \"Shcp\", \"pass_shcp:Shcp(_MvCtor)*_MvCtor\"),\n        (m.pass_uqmp, \"Uqmp\", \"pass_uqmp:Uqmp(_MvCtor)*_MvCtor\"),\n        (m.pass_uqcp, \"Uqcp\", \"pass_uqcp:Uqcp(_MvCtor)*_MvCtor\"),\n    ],\n)\ndef test_load_with_mtxt(pass_f, mtxt, expected):\n    assert re.match(expected, pass_f(m.atyp(mtxt)))\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"rtrn_f\", \"expected\"),\n    [\n        (m.pass_udmp, m.rtrn_udmp, \"pass_udmp:rtrn_udmp\"),\n        (m.pass_udcp, m.rtrn_udcp, \"pass_udcp:rtrn_udcp\"),\n    ],\n)\ndef test_load_with_rtrn_f(pass_f, rtrn_f, expected):\n    assert pass_f(rtrn_f()) == expected\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"rtrn_f\", \"regex_expected\"),\n    [\n        (\n            m.pass_udmp_del,\n            m.rtrn_udmp_del,\n            \"pass_udmp_del:rtrn_udmp_del,udmp_deleter(_MvCtorTo)*_MvCtorTo\",\n        ),\n        (\n            m.pass_udcp_del,\n            m.rtrn_udcp_del,\n            \"pass_udcp_del:rtrn_udcp_del,udcp_deleter(_MvCtorTo)*_MvCtorTo\",\n        ),\n        (\n            m.pass_udmp_del_nd,\n            m.rtrn_udmp_del_nd,\n            \"pass_udmp_del_nd:rtrn_udmp_del_nd,udmp_deleter_nd(_MvCtorTo)*_MvCtorTo\",\n        ),\n        (\n            m.pass_udcp_del_nd,\n            m.rtrn_udcp_del_nd,\n            \"pass_udcp_del_nd:rtrn_udcp_del_nd,udcp_deleter_nd(_MvCtorTo)*_MvCtorTo\",\n        ),\n    ],\n)\ndef test_deleter_roundtrip(pass_f, rtrn_f, regex_expected):\n    assert re.match(regex_expected, pass_f(rtrn_f()))\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"rtrn_f\", \"expected\"),\n    [\n        (m.pass_uqmp, m.rtrn_uqmp, \"pass_uqmp:rtrn_uqmp\"),\n        (m.pass_uqcp, m.rtrn_uqcp, \"pass_uqcp:rtrn_uqcp\"),\n        (m.pass_udmp, m.rtrn_udmp, \"pass_udmp:rtrn_udmp\"),\n        (m.pass_udcp, m.rtrn_udcp, \"pass_udcp:rtrn_udcp\"),\n    ],\n)\ndef test_pass_unique_ptr_disowns(pass_f, rtrn_f, expected):\n    obj = rtrn_f()\n    assert pass_f(obj) == expected\n    with pytest.raises(ValueError) as exc_info:\n        pass_f(obj)\n    assert str(exc_info.value) == (\n        \"Missing value for wrapped C++ type\"\n        \" `pybind11_tests::class_sh_basic::atyp`:\"\n        \" Python instance was disowned.\"\n    )\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"rtrn_f\"),\n    [\n        (m.pass_uqmp, m.rtrn_uqmp),\n        (m.pass_uqcp, m.rtrn_uqcp),\n        (m.pass_udmp, m.rtrn_udmp),\n        (m.pass_udcp, m.rtrn_udcp),\n    ],\n)\ndef test_cannot_disown_use_count_ne_1(pass_f, rtrn_f):\n    obj = rtrn_f()\n    stash = m.SharedPtrStash()\n    stash.Add(obj)\n    with pytest.raises(ValueError) as exc_info:\n        pass_f(obj)\n    assert str(exc_info.value) == (\"Cannot disown use_count != 1 (load_as_unique_ptr).\")\n\n\ndef test_unique_ptr_roundtrip():\n    # Multiple roundtrips to stress-test instance registration/deregistration.\n    num_round_trips = 1000\n    recycled = m.atyp(\"passenger\")\n    for _ in range(num_round_trips):\n        id_orig = id(recycled)\n        recycled = m.unique_ptr_roundtrip(recycled)\n        assert re.match(\"passenger(_MvCtor)*_MvCtor\", m.get_mtxt(recycled))\n        id_rtrn = id(recycled)\n        # Ensure the returned object is a different Python instance.\n        assert id_rtrn != id_orig\n        id_orig = id_rtrn\n\n\ndef test_pass_unique_ptr_cref():\n    obj = m.atyp(\"ctor_arg\")\n    assert re.match(\"ctor_arg(_MvCtor)*_MvCtor\", m.get_mtxt(obj))\n    assert re.match(\"ctor_arg(_MvCtor)*_MvCtor\", m.pass_unique_ptr_cref(obj))\n    assert re.match(\"ctor_arg(_MvCtor)*_MvCtor\", m.get_mtxt(obj))\n\n\ndef test_rtrn_unique_ptr_cref():\n    obj0 = m.rtrn_unique_ptr_cref(\"\")\n    assert m.get_mtxt(obj0) == \"static_ctor_arg\"\n    obj1 = m.rtrn_unique_ptr_cref(\"passed_mtxt_1\")\n    assert m.get_mtxt(obj1) == \"passed_mtxt_1\"\n    assert m.get_mtxt(obj0) == \"passed_mtxt_1\"\n    assert obj0 is obj1\n\n\ndef test_unique_ptr_cref_roundtrip():\n    # Multiple roundtrips to stress-test implementation.\n    num_round_trips = 1000\n    orig = m.atyp(\"passenger\")\n    mtxt_orig = m.get_mtxt(orig)\n    recycled = orig\n    for _ in range(num_round_trips):\n        recycled = m.unique_ptr_cref_roundtrip(recycled)\n        assert recycled is orig\n        assert m.get_mtxt(recycled) == mtxt_orig\n\n\n@pytest.mark.parametrize(\n    (\"pass_f\", \"rtrn_f\", \"moved_out\", \"moved_in\"),\n    [\n        (m.uconsumer.pass_valu, m.uconsumer.rtrn_valu, True, True),\n        (m.uconsumer.pass_rref, m.uconsumer.rtrn_valu, True, True),\n        (m.uconsumer.pass_valu, m.uconsumer.rtrn_lref, True, False),\n        (m.uconsumer.pass_valu, m.uconsumer.rtrn_cref, True, False),\n    ],\n)\ndef test_unique_ptr_consumer_roundtrip(pass_f, rtrn_f, moved_out, moved_in):\n    c = m.uconsumer()\n    assert not c.valid()\n    recycled = m.atyp(\"passenger\")\n    mtxt_orig = m.get_mtxt(recycled)\n    assert re.match(\"passenger_(MvCtor){1,2}\", mtxt_orig)\n\n    pass_f(c, recycled)\n    if moved_out:\n        with pytest.raises(ValueError) as excinfo:\n            m.get_mtxt(recycled)\n        assert \"Python instance was disowned\" in str(excinfo.value)\n\n    recycled = rtrn_f(c)\n    assert c.valid() != moved_in\n    assert m.get_mtxt(recycled) == mtxt_orig\n\n\ndef test_py_type_handle_of_atyp():\n    obj = m.py_type_handle_of_atyp()\n    assert obj.__class__.__name__ == \"pybind11_type\"\n\n\ndef test_function_signatures(doc):\n    assert (\n        doc(m.args_shared_ptr)\n        == \"args_shared_ptr(arg0: m.class_sh_basic.atyp) -> m.class_sh_basic.atyp\"\n    )\n    assert (\n        doc(m.args_shared_ptr_const)\n        == \"args_shared_ptr_const(arg0: m.class_sh_basic.atyp) -> m.class_sh_basic.atyp\"\n    )\n    assert (\n        doc(m.args_unique_ptr)\n        == \"args_unique_ptr(arg0: m.class_sh_basic.atyp) -> m.class_sh_basic.atyp\"\n    )\n    assert (\n        doc(m.args_unique_ptr_const)\n        == \"args_unique_ptr_const(arg0: m.class_sh_basic.atyp) -> m.class_sh_basic.atyp\"\n    )\n\n\ndef test_unique_ptr_return_value_policy_automatic_reference():\n    assert m.get_mtxt(m.rtrn_uq_automatic_reference()) == \"rtrn_uq_automatic_reference\"\n\n\ndef test_pass_shared_ptr_ptr():\n    obj = m.atyp()\n    with pytest.raises(RuntimeError) as excinfo:\n        m.pass_shared_ptr_ptr(obj)\n    assert str(excinfo.value) == (\n        \"Passing `std::shared_ptr<T> *` from Python to C++ is not supported\"\n        \" (inherently unsafe).\"\n    )\n\n\ndef test_unusual_op_ref():\n    # Merely to test that this still exists and built successfully.\n    assert m.CallCastUnusualOpRefConstRef().__class__.__name__ == \"LocalUnusualOpRef\"\n    assert m.CallCastUnusualOpRefMovable().__class__.__name__ == \"LocalUnusualOpRef\"\n"
  },
  {
    "path": "tests/test_class_sh_disowning.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_disowning {\n\ntemplate <int SerNo> // Using int as a trick to easily generate a series of types.\nstruct Atype {\n    int val = 0;\n    explicit Atype(int val_) : val{val_} {}\n    int get() const { return val * 10 + SerNo; }\n};\n\nint same_twice(std::unique_ptr<Atype<1>> at1a, std::unique_ptr<Atype<1>> at1b) {\n    return at1a->get() * 100 + at1b->get() * 10;\n}\n\nint mixed(std::unique_ptr<Atype<1>> at1, std::unique_ptr<Atype<2>> at2) {\n    return at1->get() * 200 + at2->get() * 20;\n}\n\nint overloaded(std::unique_ptr<Atype<1>> at1, int i) { return at1->get() * 30 + i; }\nint overloaded(std::unique_ptr<Atype<2>> at2, int i) { return at2->get() * 40 + i; }\n\n} // namespace class_sh_disowning\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(class_sh_disowning, m) {\n    using namespace pybind11_tests::class_sh_disowning;\n\n    py::classh<Atype<1>>(m, \"Atype1\").def(py::init<int>()).def(\"get\", &Atype<1>::get);\n    py::classh<Atype<2>>(m, \"Atype2\").def(py::init<int>()).def(\"get\", &Atype<2>::get);\n\n    m.def(\"same_twice\", same_twice);\n\n    m.def(\"mixed\", mixed);\n\n    m.def(\"overloaded\", (int (*)(std::unique_ptr<Atype<1>>, int)) &overloaded);\n    m.def(\"overloaded\", (int (*)(std::unique_ptr<Atype<2>>, int)) &overloaded);\n}\n"
  },
  {
    "path": "tests/test_class_sh_disowning.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_disowning as m\n\n\ndef is_disowned(obj):\n    try:\n        obj.get()\n    except ValueError:\n        return True\n    return False\n\n\ndef test_same_twice():\n    while True:\n        obj1a = m.Atype1(57)\n        obj1b = m.Atype1(62)\n        assert m.same_twice(obj1a, obj1b) == (57 * 10 + 1) * 100 + (62 * 10 + 1) * 10\n        assert is_disowned(obj1a)\n        assert is_disowned(obj1b)\n        obj1c = m.Atype1(0)\n        with pytest.raises(ValueError):\n            # Disowning works for one argument, but not both.\n            m.same_twice(obj1c, obj1c)\n        assert is_disowned(obj1c)\n        return  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_mixed():\n    first_pass = True\n    while True:\n        obj1a = m.Atype1(90)\n        obj2a = m.Atype2(25)\n        assert m.mixed(obj1a, obj2a) == (90 * 10 + 1) * 200 + (25 * 10 + 2) * 20\n        assert is_disowned(obj1a)\n        assert is_disowned(obj2a)\n\n        # The C++ order of evaluation of function arguments is (unfortunately) unspecified:\n        # https://en.cppreference.com/w/cpp/language/eval_order\n        # Read on.\n        obj1b = m.Atype1(0)\n        with pytest.raises(ValueError):\n            # If the 1st argument is evaluated first, obj1b is disowned before the conversion for\n            # the already disowned obj2a fails as expected.\n            m.mixed(obj1b, obj2a)\n        obj2b = m.Atype2(0)\n        with pytest.raises(ValueError):\n            # If the 2nd argument is evaluated first, obj2b is disowned before the conversion for\n            # the already disowned obj1a fails as expected.\n            m.mixed(obj1a, obj2b)\n\n        # Either obj1b or obj2b was disowned in the expected failed m.mixed() calls above, but not\n        # both.\n        is_disowned_results = (is_disowned(obj1b), is_disowned(obj2b))\n        assert is_disowned_results.count(True) == 1\n        if first_pass:\n            first_pass = False\n            ix = is_disowned_results.index(True) + 1\n            print(f\"\\nC++ function argument {ix} is evaluated first.\")\n\n        return  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_overloaded():\n    while True:\n        obj1 = m.Atype1(81)\n        obj2 = m.Atype2(60)\n        with pytest.raises(TypeError):\n            m.overloaded(obj1, \"NotInt\")\n        assert obj1.get() == 81 * 10 + 1  # Not disowned.\n        assert m.overloaded(obj1, 3) == (81 * 10 + 1) * 30 + 3\n        with pytest.raises(TypeError):\n            m.overloaded(obj2, \"NotInt\")\n        assert obj2.get() == 60 * 10 + 2  # Not disowned.\n        assert m.overloaded(obj2, 2) == (60 * 10 + 2) * 40 + 2\n        return  # Comment out for manual leak checking (use `top` command).\n"
  },
  {
    "path": "tests/test_class_sh_disowning_mi.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_disowning_mi {\n\n// Diamond inheritance (copied from test_multiple_inheritance.cpp).\nstruct B {\n    int val_b = 10;\n    B() = default;\n    B(const B &) = default;\n    virtual ~B() = default;\n};\n\nstruct C0 : public virtual B {\n    int val_c0 = 20;\n};\n\nstruct C1 : public virtual B {\n    int val_c1 = 21;\n};\n\nstruct D : public C0, public C1 {\n    int val_d = 30;\n};\n\nvoid disown_b(std::unique_ptr<B>) {}\n\n// test_multiple_inheritance_python\nstruct Base1 {\n    explicit Base1(int i) : i(i) {}\n    int foo() const { return i; }\n    int i;\n};\n\nstruct Base2 {\n    explicit Base2(int j) : j(j) {}\n    int bar() const { return j; }\n    int j;\n};\n\nint disown_base1(std::unique_ptr<Base1> b1) { return b1->i * 2000 + 1; }\nint disown_base2(std::unique_ptr<Base2> b2) { return b2->j * 2000 + 2; }\n\n} // namespace class_sh_disowning_mi\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(class_sh_disowning_mi, m) {\n    using namespace pybind11_tests::class_sh_disowning_mi;\n\n    py::classh<B>(m, \"B\")\n        .def(py::init<>())\n        .def_readonly(\"val_b\", &D::val_b)\n        .def(\"b\", [](B *self) { return self; })\n        .def(\"get\", [](const B &self) { return self.val_b; });\n\n    py::classh<C0, B>(m, \"C0\")\n        .def(py::init<>())\n        .def_readonly(\"val_c0\", &D::val_c0)\n        .def(\"c0\", [](C0 *self) { return self; })\n        .def(\"get\", [](const C0 &self) { return self.val_b * 100 + self.val_c0; });\n\n    py::classh<C1, B>(m, \"C1\")\n        .def(py::init<>())\n        .def_readonly(\"val_c1\", &D::val_c1)\n        .def(\"c1\", [](C1 *self) { return self; })\n        .def(\"get\", [](const C1 &self) { return self.val_b * 100 + self.val_c1; });\n\n    py::classh<D, C0, C1>(m, \"D\")\n        .def(py::init<>())\n        .def_readonly(\"val_d\", &D::val_d)\n        .def(\"d\", [](D *self) { return self; })\n        .def(\"get\", [](const D &self) {\n            return self.val_b * 1000000 + self.val_c0 * 10000 + self.val_c1 * 100 + self.val_d;\n        });\n\n    m.def(\"disown_b\", disown_b);\n\n    // test_multiple_inheritance_python\n    py::classh<Base1>(m, \"Base1\").def(py::init<int>()).def(\"foo\", &Base1::foo);\n    py::classh<Base2>(m, \"Base2\").def(py::init<int>()).def(\"bar\", &Base2::bar);\n    m.def(\"disown_base1\", disown_base1);\n    m.def(\"disown_base2\", disown_base2);\n}\n"
  },
  {
    "path": "tests/test_class_sh_disowning_mi.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import class_sh_disowning_mi as m\n\n\ndef test_diamond_inheritance():\n    # Very similar to test_multiple_inheritance.py:test_diamond_inheritance.\n    d = m.D()\n    assert d is d.d()\n    assert d is d.c0()\n    assert d is d.c1()\n    assert d is d.b()\n    assert d is d.c0().b()\n    assert d is d.c1().b()\n    assert d is d.c0().c1().b().c0().b()\n\n\ndef is_disowned(callable_method):\n    try:\n        callable_method()\n    except ValueError as e:\n        assert \"Python instance was disowned\" in str(e)  # noqa: PT017\n        return True\n    return False\n\n\ndef test_disown_b():\n    b = m.B()\n    assert b.get() == 10\n    m.disown_b(b)\n    assert is_disowned(b.get)\n\n\n@pytest.mark.parametrize(\"var_to_disown\", [\"c0\", \"b\"])\ndef test_disown_c0(var_to_disown):\n    c0 = m.C0()\n    assert c0.get() == 1020\n    b = c0.b()\n    m.disown_b(locals()[var_to_disown])\n    assert is_disowned(c0.get)\n    assert is_disowned(b.get)\n\n\n@pytest.mark.parametrize(\"var_to_disown\", [\"c1\", \"b\"])\ndef test_disown_c1(var_to_disown):\n    c1 = m.C1()\n    assert c1.get() == 1021\n    b = c1.b()\n    m.disown_b(locals()[var_to_disown])\n    assert is_disowned(c1.get)\n    assert is_disowned(b.get)\n\n\n@pytest.mark.parametrize(\"var_to_disown\", [\"d\", \"c1\", \"c0\", \"b\"])\ndef test_disown_d(var_to_disown):\n    d = m.D()\n    assert d.get() == 10202130\n    b = d.b()\n    c0 = d.c0()\n    c1 = d.c1()\n    m.disown_b(locals()[var_to_disown])\n    assert is_disowned(d.get)\n    assert is_disowned(c1.get)\n    assert is_disowned(c0.get)\n    assert is_disowned(b.get)\n\n\n# Based on test_multiple_inheritance.py:test_multiple_inheritance_python.\nclass MI1(m.Base1, m.Base2):\n    def __init__(self, i, j):\n        m.Base1.__init__(self, i)\n        m.Base2.__init__(self, j)\n\n\nclass B1:\n    def v(self):\n        return 1\n\n\nclass MI2(B1, m.Base1, m.Base2):\n    def __init__(self, i, j):\n        B1.__init__(self)\n        m.Base1.__init__(self, i)\n        m.Base2.__init__(self, j)\n\n\nclass MI3(MI2):\n    def __init__(self, i, j):\n        MI2.__init__(self, i, j)\n\n\nclass MI4(MI3, m.Base2):\n    def __init__(self, i, j):\n        MI3.__init__(self, i, j)\n        # This should be ignored (Base2 is already initialized via MI2):\n        m.Base2.__init__(self, i + 100)\n\n\nclass MI5(m.Base2, B1, m.Base1):\n    def __init__(self, i, j):\n        B1.__init__(self)\n        m.Base1.__init__(self, i)\n        m.Base2.__init__(self, j)\n\n\nclass MI6(m.Base2, B1):\n    def __init__(self, i):\n        m.Base2.__init__(self, i)\n        B1.__init__(self)\n\n\nclass B2(B1):\n    def v(self):\n        return 2\n\n\nclass B3:\n    def v(self):\n        return 3\n\n\nclass B4(B3, B2):\n    def v(self):\n        return 4\n\n\nclass MI7(B4, MI6):\n    def __init__(self, i):\n        B4.__init__(self)\n        MI6.__init__(self, i)\n\n\nclass MI8(MI6, B3):\n    def __init__(self, i):\n        MI6.__init__(self, i)\n        B3.__init__(self)\n\n\nclass MI8b(B3, MI6):\n    def __init__(self, i):\n        B3.__init__(self)\n        MI6.__init__(self, i)\n\n\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_multiple_inheritance_python():\n    # Based on test_multiple_inheritance.py:test_multiple_inheritance_python.\n    # Exercises values_and_holders with 2 value_and_holder instances.\n\n    mi1 = MI1(1, 2)\n    assert mi1.foo() == 1\n    assert mi1.bar() == 2\n\n    mi2 = MI2(3, 4)\n    assert mi2.v() == 1\n    assert mi2.foo() == 3\n    assert mi2.bar() == 4\n\n    mi3 = MI3(5, 6)\n    assert mi3.v() == 1\n    assert mi3.foo() == 5\n    assert mi3.bar() == 6\n\n    mi4 = MI4(7, 8)\n    assert mi4.v() == 1\n    assert mi4.foo() == 7\n    assert mi4.bar() == 8\n\n    mi5 = MI5(10, 11)\n    assert mi5.v() == 1\n    assert mi5.foo() == 10\n    assert mi5.bar() == 11\n\n    mi6 = MI6(12)\n    assert mi6.v() == 1\n    assert mi6.bar() == 12\n\n    mi7 = MI7(13)\n    assert mi7.v() == 4\n    assert mi7.bar() == 13\n\n    mi8 = MI8(14)\n    assert mi8.v() == 1\n    assert mi8.bar() == 14\n\n    mi8b = MI8b(15)\n    assert mi8b.v() == 3\n    assert mi8b.bar() == 15\n\n\nDISOWN_CLS_I_J_V_LIST = [\n    (MI1, 1, 2, None),\n    (MI2, 3, 4, 1),\n    (MI3, 5, 6, 1),\n    (MI4, 7, 8, 1),\n    (MI5, 10, 11, 1),\n]\n\n\n@pytest.mark.xfail(\"env.PYPY\", strict=False)\n@pytest.mark.parametrize((\"cls\", \"i\", \"j\", \"v\"), DISOWN_CLS_I_J_V_LIST)\ndef test_disown_base1_first(cls, i, j, v):\n    obj = cls(i, j)\n    assert obj.foo() == i\n    assert m.disown_base1(obj) == 2000 * i + 1\n    assert is_disowned(obj.foo)\n    assert obj.bar() == j\n    assert m.disown_base2(obj) == 2000 * j + 2\n    assert is_disowned(obj.bar)\n    if v is not None:\n        assert obj.v() == v\n\n\n@pytest.mark.xfail(\"env.PYPY\", strict=False)\n@pytest.mark.parametrize((\"cls\", \"i\", \"j\", \"v\"), DISOWN_CLS_I_J_V_LIST)\ndef test_disown_base2_first(cls, i, j, v):\n    obj = cls(i, j)\n    assert obj.bar() == j\n    assert m.disown_base2(obj) == 2000 * j + 2\n    assert is_disowned(obj.bar)\n    assert obj.foo() == i\n    assert m.disown_base1(obj) == 2000 * i + 1\n    assert is_disowned(obj.foo)\n    if v is not None:\n        assert obj.v() == v\n\n\n@pytest.mark.xfail(\"env.PYPY\", strict=False)\n@pytest.mark.parametrize(\n    (\"cls\", \"j\", \"v\"),\n    [\n        (MI6, 12, 1),\n        (MI7, 13, 4),\n        (MI8, 14, 1),\n        (MI8b, 15, 3),\n    ],\n)\ndef test_disown_base2(cls, j, v):\n    obj = cls(j)\n    assert obj.bar() == j\n    assert m.disown_base2(obj) == 2000 * j + 2\n    assert is_disowned(obj.bar)\n    assert obj.v() == v\n"
  },
  {
    "path": "tests/test_class_sh_factory_constructors.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <string>\n\nnamespace pybind11_tests {\nnamespace class_sh_factory_constructors {\n\ntemplate <int> // Using int as a trick to easily generate a series of types.\nstruct atyp {  // Short for \"any type\".\n    std::string mtxt;\n};\n\ntemplate <typename T>\nstd::string get_mtxt(const T &obj) {\n    return obj.mtxt;\n}\n\nusing atyp_valu = atyp<0x0>;\nusing atyp_rref = atyp<0x1>;\nusing atyp_cref = atyp<0x2>;\nusing atyp_mref = atyp<0x3>;\nusing atyp_cptr = atyp<0x4>;\nusing atyp_mptr = atyp<0x5>;\nusing atyp_shmp = atyp<0x6>;\nusing atyp_shcp = atyp<0x7>;\nusing atyp_uqmp = atyp<0x8>;\nusing atyp_uqcp = atyp<0x9>;\nusing atyp_udmp = atyp<0xA>;\nusing atyp_udcp = atyp<0xB>;\n\n// clang-format off\n\natyp_valu        rtrn_valu() { atyp_valu obj{\"Valu\"}; return obj; }\natyp_rref&&      rtrn_rref() { static atyp_rref obj; obj.mtxt = \"Rref\"; return std::move(obj); }\natyp_cref const& rtrn_cref() { static atyp_cref obj; obj.mtxt = \"Cref\"; return obj; }\natyp_mref&       rtrn_mref() { static atyp_mref obj; obj.mtxt = \"Mref\"; return obj; }\natyp_cptr const* rtrn_cptr() { return new atyp_cptr{\"Cptr\"}; }\natyp_mptr*       rtrn_mptr() { return new atyp_mptr{\"Mptr\"}; }\n\nstd::shared_ptr<atyp_shmp>       rtrn_shmp() { return std::make_shared<atyp_shmp>(atyp_shmp{\"Shmp\"}); }\nstd::shared_ptr<atyp_shcp const> rtrn_shcp() { return std::shared_ptr<atyp_shcp const>(new atyp_shcp{\"Shcp\"}); }\n\nstd::unique_ptr<atyp_uqmp>       rtrn_uqmp() { return std::unique_ptr<atyp_uqmp      >(new atyp_uqmp{\"Uqmp\"}); }\nstd::unique_ptr<atyp_uqcp const> rtrn_uqcp() { return std::unique_ptr<atyp_uqcp const>(new atyp_uqcp{\"Uqcp\"}); }\n\nstruct sddm : std::default_delete<atyp_udmp      > {};\nstruct sddc : std::default_delete<atyp_udcp const> {};\n\nstd::unique_ptr<atyp_udmp,       sddm> rtrn_udmp() { return std::unique_ptr<atyp_udmp,       sddm>(new atyp_udmp{\"Udmp\"}); }\nstd::unique_ptr<atyp_udcp const, sddc> rtrn_udcp() { return std::unique_ptr<atyp_udcp const, sddc>(new atyp_udcp{\"Udcp\"}); }\n\n// clang-format on\n\n// Minimalistic approach to achieve full coverage of construct() overloads for constructing\n// smart_holder from unique_ptr and shared_ptr returns.\nstruct with_alias {\n    int val = 0;\n    virtual ~with_alias() = default;\n    // Some compilers complain about implicitly defined versions of some of the following:\n    with_alias() = default;\n    with_alias(const with_alias &) = default;\n    with_alias(with_alias &&) = default;\n    with_alias &operator=(const with_alias &) = default;\n    with_alias &operator=(with_alias &&) = default;\n};\nstruct with_alias_alias : with_alias, py::trampoline_self_life_support {};\nstruct sddwaa : std::default_delete<with_alias_alias> {};\n\n} // namespace class_sh_factory_constructors\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(class_sh_factory_constructors, m) {\n    using namespace pybind11_tests::class_sh_factory_constructors;\n\n    py::classh<atyp_valu>(m, \"atyp_valu\")\n        .def(py::init(&rtrn_valu))\n        .def(\"get_mtxt\", get_mtxt<atyp_valu>);\n\n    py::classh<atyp_rref>(m, \"atyp_rref\")\n        .def(py::init(&rtrn_rref))\n        .def(\"get_mtxt\", get_mtxt<atyp_rref>);\n\n    py::classh<atyp_cref>(m, \"atyp_cref\")\n        // class_: ... must return a compatible ...\n        // classh: ... cannot pass object of non-trivial type ...\n        // .def(py::init(&rtrn_cref))\n        .def(\"get_mtxt\", get_mtxt<atyp_cref>);\n\n    py::classh<atyp_mref>(m, \"atyp_mref\")\n        // class_: ... must return a compatible ...\n        // classh: ... cannot pass object of non-trivial type ...\n        // .def(py::init(&rtrn_mref))\n        .def(\"get_mtxt\", get_mtxt<atyp_mref>);\n\n    py::classh<atyp_cptr>(m, \"atyp_cptr\")\n        // class_: ... must return a compatible ...\n        // classh: ... must return a compatible ...\n        // .def(py::init(&rtrn_cptr))\n        .def(\"get_mtxt\", get_mtxt<atyp_cptr>);\n\n    py::classh<atyp_mptr>(m, \"atyp_mptr\")\n        .def(py::init(&rtrn_mptr))\n        .def(\"get_mtxt\", get_mtxt<atyp_mptr>);\n\n    py::classh<atyp_shmp>(m, \"atyp_shmp\")\n        .def(py::init(&rtrn_shmp))\n        .def(\"get_mtxt\", get_mtxt<atyp_shmp>);\n\n    py::classh<atyp_shcp>(m, \"atyp_shcp\")\n        .def(py::init(&rtrn_shcp))\n        .def(\"get_mtxt\", get_mtxt<atyp_shcp>);\n\n    py::classh<atyp_uqmp>(m, \"atyp_uqmp\")\n        .def(py::init(&rtrn_uqmp))\n        .def(\"get_mtxt\", get_mtxt<atyp_uqmp>);\n\n    py::classh<atyp_uqcp>(m, \"atyp_uqcp\")\n        .def(py::init(&rtrn_uqcp))\n        .def(\"get_mtxt\", get_mtxt<atyp_uqcp>);\n\n    py::classh<atyp_udmp>(m, \"atyp_udmp\")\n        .def(py::init(&rtrn_udmp))\n        .def(\"get_mtxt\", get_mtxt<atyp_udmp>);\n\n    py::classh<atyp_udcp>(m, \"atyp_udcp\")\n        .def(py::init(&rtrn_udcp))\n        .def(\"get_mtxt\", get_mtxt<atyp_udcp>);\n\n    py::classh<with_alias, with_alias_alias>(m, \"with_alias\")\n        .def_readonly(\"val\", &with_alias::val)\n        .def(py::init([](int i) {\n            auto p = std::unique_ptr<with_alias_alias, sddwaa>(new with_alias_alias);\n            p->val = i * 100;\n            return p;\n        }))\n        .def(py::init([](int i, int j) {\n            auto p = std::unique_ptr<with_alias_alias>(new with_alias_alias);\n            p->val = i * 100 + j * 10;\n            return p;\n        }))\n        .def(py::init([](int i, int j, int k) {\n            auto p = std::make_shared<with_alias_alias>();\n            p->val = i * 100 + j * 10 + k;\n            return p;\n        }))\n        .def(py::init(\n            [](int, int, int, int) { return std::unique_ptr<with_alias>(new with_alias); },\n            [](int, int, int, int) {\n                return std::unique_ptr<with_alias>(new with_alias); // Invalid alias factory.\n            }))\n        .def(py::init([](int, int, int, int, int) { return std::make_shared<with_alias>(); },\n                      [](int, int, int, int, int) {\n                          return std::make_shared<with_alias>(); // Invalid alias factory.\n                      }));\n}\n"
  },
  {
    "path": "tests/test_class_sh_factory_constructors.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_factory_constructors as m\n\n\ndef test_atyp_factories():\n    assert m.atyp_valu().get_mtxt() == \"Valu\"\n    assert m.atyp_rref().get_mtxt() == \"Rref\"\n    # sert m.atyp_cref().get_mtxt() == \"Cref\"\n    # sert m.atyp_mref().get_mtxt() == \"Mref\"\n    # sert m.atyp_cptr().get_mtxt() == \"Cptr\"\n    assert m.atyp_mptr().get_mtxt() == \"Mptr\"\n    assert m.atyp_shmp().get_mtxt() == \"Shmp\"\n    assert m.atyp_shcp().get_mtxt() == \"Shcp\"\n    assert m.atyp_uqmp().get_mtxt() == \"Uqmp\"\n    assert m.atyp_uqcp().get_mtxt() == \"Uqcp\"\n    assert m.atyp_udmp().get_mtxt() == \"Udmp\"\n    assert m.atyp_udcp().get_mtxt() == \"Udcp\"\n\n\n@pytest.mark.parametrize(\n    (\"init_args\", \"expected\"),\n    [\n        ((3,), 300),\n        ((5, 7), 570),\n        ((9, 11, 13), 1023),\n    ],\n)\ndef test_with_alias_success(init_args, expected):\n    assert m.with_alias(*init_args).val == expected\n\n\n@pytest.mark.parametrize(\n    (\"num_init_args\", \"smart_ptr\"),\n    [\n        (4, \"std::unique_ptr\"),\n        (5, \"std::shared_ptr\"),\n    ],\n)\ndef test_with_alias_invalid(num_init_args, smart_ptr):\n    class PyDrvdWithAlias(m.with_alias):\n        pass\n\n    with pytest.raises(TypeError) as excinfo:\n        PyDrvdWithAlias(*((0,) * num_init_args))\n    assert (\n        str(excinfo.value)\n        == \"pybind11::init(): construction failed: returned \"\n        + smart_ptr\n        + \" pointee is not an alias instance\"\n    )\n"
  },
  {
    "path": "tests/test_class_sh_inheritance.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_inheritance {\n\ntemplate <int Id>\nstruct base_template {\n    base_template() : base_id(Id) {}\n    virtual ~base_template() = default;\n    virtual int id() const { return base_id; }\n    int base_id;\n\n    // Some compilers complain about implicitly defined versions of some of the following:\n    base_template(const base_template &) = default;\n    base_template(base_template &&) noexcept = default;\n    base_template &operator=(const base_template &) = default;\n    base_template &operator=(base_template &&) noexcept = default;\n};\n\nusing base = base_template<100>;\n\nstruct drvd : base {\n    int id() const override { return 2 * base_id; }\n};\n\n// clang-format off\ninline drvd *rtrn_mptr_drvd()         { return new drvd; }\ninline base *rtrn_mptr_drvd_up_cast() { return new drvd; }\n\ninline int pass_cptr_base(base const *b) { return b->id() + 11; }\ninline int pass_cptr_drvd(drvd const *d) { return d->id() + 12; }\n\ninline std::shared_ptr<drvd> rtrn_shmp_drvd()         { return std::make_shared<drvd>(); }\ninline std::shared_ptr<base> rtrn_shmp_drvd_up_cast() { return std::make_shared<drvd>(); }\n\ninline int pass_shcp_base(const std::shared_ptr<base const>& b) { return b->id() + 21; }\ninline int pass_shcp_drvd(const std::shared_ptr<drvd const>& d) { return d->id() + 22; }\n// clang-format on\n\nusing base1 = base_template<110>;\nusing base2 = base_template<120>;\n\n// Not reusing base here because it would interfere with the single-inheritance test.\nstruct drvd2 : base1, base2 {\n    int id() const override { return 3 * base1::base_id + 4 * base2::base_id; }\n};\n\n// clang-format off\ninline drvd2 *rtrn_mptr_drvd2()          { return new drvd2; }\ninline base1 *rtrn_mptr_drvd2_up_cast1() { return new drvd2; }\ninline base2 *rtrn_mptr_drvd2_up_cast2() { return new drvd2; }\n\ninline int pass_cptr_base1(base1 const *b) { return b->id() + 21; }\ninline int pass_cptr_base2(base2 const *b) { return b->id() + 22; }\ninline int pass_cptr_drvd2(drvd2 const *d) { return d->id() + 23; }\n// clang-format on\n\nTEST_SUBMODULE(class_sh_inheritance, m) {\n    py::classh<base>(m, \"base\");\n    py::classh<drvd, base>(m, \"drvd\");\n\n    auto rvto = py::return_value_policy::take_ownership;\n\n    m.def(\"rtrn_mptr_drvd\", rtrn_mptr_drvd, rvto);\n    m.def(\"rtrn_mptr_drvd_up_cast\", rtrn_mptr_drvd_up_cast, rvto);\n    m.def(\"pass_cptr_base\", pass_cptr_base);\n    m.def(\"pass_cptr_drvd\", pass_cptr_drvd);\n\n    m.def(\"rtrn_shmp_drvd\", rtrn_shmp_drvd);\n    m.def(\"rtrn_shmp_drvd_up_cast\", rtrn_shmp_drvd_up_cast);\n    m.def(\"pass_shcp_base\", pass_shcp_base);\n    m.def(\"pass_shcp_drvd\", pass_shcp_drvd);\n\n    // __init__ needed for Python inheritance.\n    py::classh<base1>(m, \"base1\").def(py::init<>());\n    py::classh<base2>(m, \"base2\").def(py::init<>());\n    py::classh<drvd2, base1, base2>(m, \"drvd2\");\n\n    m.def(\"rtrn_mptr_drvd2\", rtrn_mptr_drvd2, rvto);\n    m.def(\"rtrn_mptr_drvd2_up_cast1\", rtrn_mptr_drvd2_up_cast1, rvto);\n    m.def(\"rtrn_mptr_drvd2_up_cast2\", rtrn_mptr_drvd2_up_cast2, rvto);\n    m.def(\"pass_cptr_base1\", pass_cptr_base1);\n    m.def(\"pass_cptr_base2\", pass_cptr_base2);\n    m.def(\"pass_cptr_drvd2\", pass_cptr_drvd2);\n}\n\n} // namespace class_sh_inheritance\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_class_sh_inheritance.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import class_sh_inheritance as m\n\n\ndef test_rtrn_mptr_drvd_pass_cptr_base():\n    d = m.rtrn_mptr_drvd()\n    i = m.pass_cptr_base(d)  # load_impl Case 2a\n    assert i == 2 * 100 + 11\n\n\ndef test_rtrn_shmp_drvd_pass_shcp_base():\n    d = m.rtrn_shmp_drvd()\n    i = m.pass_shcp_base(d)  # load_impl Case 2a\n    assert i == 2 * 100 + 21\n\n\ndef test_rtrn_mptr_drvd_up_cast_pass_cptr_drvd():\n    b = m.rtrn_mptr_drvd_up_cast()\n    # the base return is down-cast immediately.\n    assert b.__class__.__name__ == \"drvd\"\n    i = m.pass_cptr_drvd(b)\n    assert i == 2 * 100 + 12\n\n\ndef test_rtrn_shmp_drvd_up_cast_pass_shcp_drvd():\n    b = m.rtrn_shmp_drvd_up_cast()\n    # the base return is down-cast immediately.\n    assert b.__class__.__name__ == \"drvd\"\n    i = m.pass_shcp_drvd(b)\n    assert i == 2 * 100 + 22\n\n\ndef test_rtrn_mptr_drvd2_pass_cptr_bases():\n    d = m.rtrn_mptr_drvd2()\n    i1 = m.pass_cptr_base1(d)  # load_impl Case 2c\n    assert i1 == 3 * 110 + 4 * 120 + 21\n    i2 = m.pass_cptr_base2(d)\n    assert i2 == 3 * 110 + 4 * 120 + 22\n\n\ndef test_rtrn_mptr_drvd2_up_casts_pass_cptr_drvd2():\n    b1 = m.rtrn_mptr_drvd2_up_cast1()\n    assert b1.__class__.__name__ == \"drvd2\"\n    i1 = m.pass_cptr_drvd2(b1)\n    assert i1 == 3 * 110 + 4 * 120 + 23\n    b2 = m.rtrn_mptr_drvd2_up_cast2()\n    assert b2.__class__.__name__ == \"drvd2\"\n    i2 = m.pass_cptr_drvd2(b2)\n    assert i2 == 3 * 110 + 4 * 120 + 23\n\n\ndef test_python_drvd2():\n    class Drvd2(m.base1, m.base2):\n        def __init__(self):\n            m.base1.__init__(self)\n            m.base2.__init__(self)\n\n    d = Drvd2()\n    i1 = m.pass_cptr_base1(d)  # load_impl Case 2b\n    assert i1 == 110 + 21\n    i2 = m.pass_cptr_base2(d)\n    assert i2 == 120 + 22\n"
  },
  {
    "path": "tests/test_class_sh_mi_thunks.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\nnamespace test_class_sh_mi_thunks {\n\n// For general background: https://shaharmike.com/cpp/vtable-part2/\n// C++ vtables - Part 2 - Multiple Inheritance\n// ... the compiler creates a 'thunk' method that corrects `this` ...\n\n// This test was added under PR #4380\n\nstruct Base0 {\n    virtual ~Base0() = default;\n    Base0() = default;\n    Base0(const Base0 &) = delete;\n};\n\nstruct Base1 {\n    virtual ~Base1() = default;\n    // Using `vector` here because it is known to make this test very sensitive to bugs.\n    std::vector<int> vec = {1, 2, 3, 4, 5};\n    Base1() = default;\n    Base1(const Base1 &) = delete;\n};\n\nstruct Derived : Base1, Base0 {\n    ~Derived() override = default;\n    Derived() = default;\n    Derived(const Derived &) = delete;\n};\n\n// ChatGPT-generated Diamond added under PR #5836\n\nstruct VBase {\n    VBase() = default;\n    VBase(const VBase &) = default; // silence -Wdeprecated-copy-with-dtor\n    VBase &operator=(const VBase &) = default;\n    VBase(VBase &&) = default;\n    VBase &operator=(VBase &&) = default;\n    virtual ~VBase() = default;\n    virtual int ping() const { return 1; }\n    int vbase_tag = 42; // ensure it's not empty\n};\n\n// Make the virtual bases non-empty and (likely) differently sized.\n// The test does *not* require different sizes; we only want to avoid \"all at offset 0\".\n// If a compiler/ABI still places the virtual base at offset 0, our test logs that via\n// test_virtual_base_at_offset_0() and continues.\nstruct Left : virtual VBase {\n    char pad_l[4]; // small, typically 4 + padding\n    ~Left() override = default;\n};\nstruct Right : virtual VBase {\n    char pad_r[24]; // larger, to differ from Left\n    ~Right() override = default;\n};\n\nstruct Diamond : Left, Right {\n    Diamond() = default;\n    Diamond(const Diamond &) = default;\n    ~Diamond() override = default;\n    int ping() const override { return 7; }\n    int self_tag = 99;\n};\n\nVBase *make_diamond_as_vbase_raw_ptr() {\n    auto *ptr = new Diamond;\n    return ptr; // upcast\n}\n\nstd::shared_ptr<VBase> make_diamond_as_vbase_shared_ptr() {\n    auto shptr = std::make_shared<Diamond>();\n    return shptr; // upcast\n}\n\nstd::unique_ptr<VBase> make_diamond_as_vbase_unique_ptr() {\n    auto uqptr = std::unique_ptr<Diamond>(new Diamond);\n    return uqptr; // upcast\n}\n\n// For diagnostics\nstruct DiamondAddrs {\n    uintptr_t as_self;\n    uintptr_t as_vbase;\n    uintptr_t as_left;\n    uintptr_t as_right;\n};\n\nDiamondAddrs diamond_addrs() {\n    auto sp = std::make_shared<Diamond>();\n    return DiamondAddrs{reinterpret_cast<uintptr_t>(sp.get()),\n                        reinterpret_cast<uintptr_t>(static_cast<VBase *>(sp.get())),\n                        reinterpret_cast<uintptr_t>(static_cast<Left *>(sp.get())),\n                        reinterpret_cast<uintptr_t>(static_cast<Right *>(sp.get()))};\n}\n\n// Animal-Cat-Tiger reproducer copied from PR #5796\n// clone_raw_ptr, clone_unique_ptr added under PR #5836\n\nclass Animal {\npublic:\n    Animal() = default;\n    Animal(const Animal &) = default;\n    Animal &operator=(const Animal &) = default;\n    virtual Animal *clone_raw_ptr() const = 0;\n    virtual std::shared_ptr<Animal> clone_shared_ptr() const = 0;\n    virtual std::unique_ptr<Animal> clone_unique_ptr() const = 0;\n    virtual ~Animal() = default;\n};\n\nclass Cat : virtual public Animal {\npublic:\n    Cat() = default;\n    Cat(const Cat &) = default;\n    Cat &operator=(const Cat &) = default;\n    ~Cat() override = default;\n};\n\nclass Tiger : virtual public Cat {\npublic:\n    Tiger() = default;\n    Tiger(const Tiger &) = default;\n    Tiger &operator=(const Tiger &) = default;\n    ~Tiger() override = default;\n    Animal *clone_raw_ptr() const override {\n        return new Tiger(*this); // upcast\n    }\n    std::shared_ptr<Animal> clone_shared_ptr() const override {\n        return std::make_shared<Tiger>(*this); // upcast\n    }\n    std::unique_ptr<Animal> clone_unique_ptr() const override {\n        return std::unique_ptr<Tiger>(new Tiger(*this)); // upcast\n    }\n};\n\n} // namespace test_class_sh_mi_thunks\n\nTEST_SUBMODULE(class_sh_mi_thunks, m) {\n    using namespace test_class_sh_mi_thunks;\n\n    m.def(\"ptrdiff_drvd_base0\", []() {\n        auto drvd = std::unique_ptr<Derived>(new Derived);\n        auto *base0 = dynamic_cast<Base0 *>(drvd.get());\n        return std::ptrdiff_t(reinterpret_cast<char *>(drvd.get())\n                              - reinterpret_cast<char *>(base0));\n    });\n\n    py::classh<Base0>(m, \"Base0\");\n    py::classh<Base1>(m, \"Base1\");\n    py::classh<Derived, Base1, Base0>(m, \"Derived\");\n\n    m.def(\n        \"get_drvd_as_base0_raw_ptr\",\n        []() {\n            auto *drvd = new Derived;\n            auto *base0 = dynamic_cast<Base0 *>(drvd);\n            return base0;\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\"get_drvd_as_base0_shared_ptr\", []() {\n        auto drvd = std::make_shared<Derived>();\n        auto base0 = std::dynamic_pointer_cast<Base0>(drvd);\n        return base0;\n    });\n\n    m.def(\"get_drvd_as_base0_unique_ptr\", []() {\n        auto drvd = std::unique_ptr<Derived>(new Derived);\n        auto base0 = std::unique_ptr<Base0>(std::move(drvd));\n        return base0;\n    });\n\n    m.def(\"vec_size_base0_raw_ptr\", [](const Base0 *obj) {\n        const auto *obj_der = dynamic_cast<const Derived *>(obj);\n        if (obj_der == nullptr) {\n            return std::size_t(0);\n        }\n        return obj_der->vec.size();\n    });\n\n    m.def(\"vec_size_base0_shared_ptr\", [](const std::shared_ptr<Base0> &obj) -> std::size_t {\n        const auto obj_der = std::dynamic_pointer_cast<Derived>(obj);\n        if (!obj_der) {\n            return std::size_t(0);\n        }\n        return obj_der->vec.size();\n    });\n\n    m.def(\"vec_size_base0_unique_ptr\", [](std::unique_ptr<Base0> obj) -> std::size_t {\n        const auto *obj_der = dynamic_cast<const Derived *>(obj.get());\n        if (obj_der == nullptr) {\n            return std::size_t(0);\n        }\n        return obj_der->vec.size();\n    });\n\n    py::class_<VBase, py::smart_holder>(m, \"VBase\").def(\"ping\", &VBase::ping);\n\n    py::class_<Left, VBase, py::smart_holder>(m, \"Left\");\n    py::class_<Right, VBase, py::smart_holder>(m, \"Right\");\n\n    py::class_<Diamond, Left, Right, py::smart_holder>(m, \"Diamond\", py::multiple_inheritance())\n        .def(py::init<>())\n        .def(\"ping\", &Diamond::ping);\n\n    m.def(\"make_diamond_as_vbase_raw_ptr\",\n          &make_diamond_as_vbase_raw_ptr,\n          py::return_value_policy::take_ownership);\n    m.def(\"make_diamond_as_vbase_shared_ptr\", &make_diamond_as_vbase_shared_ptr);\n    m.def(\"make_diamond_as_vbase_unique_ptr\", &make_diamond_as_vbase_unique_ptr);\n\n    py::class_<DiamondAddrs, py::smart_holder>(m, \"DiamondAddrs\")\n        .def_readonly(\"as_self\", &DiamondAddrs::as_self)\n        .def_readonly(\"as_vbase\", &DiamondAddrs::as_vbase)\n        .def_readonly(\"as_left\", &DiamondAddrs::as_left)\n        .def_readonly(\"as_right\", &DiamondAddrs::as_right);\n\n    m.def(\"diamond_addrs\", &diamond_addrs);\n\n    py::classh<Animal>(m, \"Animal\");\n    py::classh<Cat, Animal>(m, \"Cat\");\n    py::classh<Tiger, Cat>(m, \"Tiger\", py::multiple_inheritance())\n        .def(py::init<>())\n        .def(\"clone_raw_ptr\", &Tiger::clone_raw_ptr)\n        .def(\"clone_shared_ptr\", &Tiger::clone_shared_ptr)\n        .def(\"clone_unique_ptr\", &Tiger::clone_unique_ptr);\n}\n"
  },
  {
    "path": "tests/test_class_sh_mi_thunks.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_mi_thunks as m\n\n\ndef test_ptrdiff_drvd_base0():\n    ptrdiff = m.ptrdiff_drvd_base0()\n    # A failure here does not (necessarily) mean that there is a bug, but that\n    # test_class_sh_mi_thunks is not exercising what it is supposed to.\n    # If this ever fails on some platforms: use pytest.skip()\n    # If this ever fails on all platforms: don't know, seems extremely unlikely.\n    assert ptrdiff != 0\n\n\n@pytest.mark.parametrize(\n    \"vec_size_fn\",\n    [\n        m.vec_size_base0_raw_ptr,\n        m.vec_size_base0_shared_ptr,\n    ],\n)\n@pytest.mark.parametrize(\n    \"get_fn\",\n    [\n        m.get_drvd_as_base0_raw_ptr,\n        m.get_drvd_as_base0_shared_ptr,\n        m.get_drvd_as_base0_unique_ptr,\n    ],\n)\ndef test_get_vec_size_raw_shared(get_fn, vec_size_fn):\n    obj = get_fn()\n    assert vec_size_fn(obj) == 5\n\n\n@pytest.mark.parametrize(\n    \"get_fn\", [m.get_drvd_as_base0_raw_ptr, m.get_drvd_as_base0_unique_ptr]\n)\ndef test_get_vec_size_unique(get_fn):\n    obj = get_fn()\n    assert m.vec_size_base0_unique_ptr(obj) == 5\n    with pytest.raises(ValueError, match=\"Python instance was disowned\"):\n        m.vec_size_base0_unique_ptr(obj)\n\n\ndef test_get_shared_vec_size_unique():\n    obj = m.get_drvd_as_base0_shared_ptr()\n    with pytest.raises(ValueError) as exc_info:\n        m.vec_size_base0_unique_ptr(obj)\n    assert (\n        str(exc_info.value) == \"Cannot disown external shared_ptr (load_as_unique_ptr).\"\n    )\n\n\ndef test_virtual_base_not_at_offset_0():\n    # This test ensures that the Diamond fixture actually exercises a non-zero\n    # virtual-base subobject offset on our supported platforms/ABIs.\n    #\n    # If this assert ever fails on some platform/toolchain, please adjust the\n    # C++ fixture so the virtual base is *not* at offset 0:\n    #   - Keep VBase non-empty.\n    #   - Make Left and Right non-empty and asymmetrically sized and, if\n    #     needed, nudge with a modest alignment.\n    #   - The goal is to achieve a non-zero address delta between `Diamond*`\n    #     and `static_cast<VBase*>(Diamond*)`.\n    #\n    # Rationale: certain smart_holder features are exercised only when the\n    # registered subobject address differs from the most-derived object start,\n    # so this check guards test efficacy across compilers.\n    addrs = m.diamond_addrs()\n    assert addrs.as_vbase - addrs.as_self != 0, (\n        \"Diamond VBase at offset 0 on this platform; to ensure test efficacy, \"\n        \"tweak fixtures (VBase/Left/Right) to ensure non-zero subobject offset.\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"make_fn\",\n    [\n        m.make_diamond_as_vbase_raw_ptr,  # exercises smart_holder::from_raw_ptr_take_ownership\n        m.make_diamond_as_vbase_shared_ptr,  # exercises smart_holder_from_shared_ptr\n        m.make_diamond_as_vbase_unique_ptr,  # exercises smart_holder_from_unique_ptr\n    ],\n)\ndef test_make_diamond_as_vbase(make_fn):\n    # Added under PR #5836\n    vb = make_fn()\n    assert vb.ping() == 7\n\n\n@pytest.mark.parametrize(\n    \"clone_fn\",\n    [\n        m.Tiger.clone_raw_ptr,\n        m.Tiger.clone_shared_ptr,\n        m.Tiger.clone_unique_ptr,\n    ],\n)\ndef test_animal_cat_tiger(clone_fn):\n    # Based on Animal-Cat-Tiger reproducer under PR #5796\n    tiger = m.Tiger()\n    cloned = clone_fn(tiger)\n    assert isinstance(cloned, m.Tiger)\n"
  },
  {
    "path": "tests/test_class_sh_property.cpp",
    "content": "// The compact 4-character naming matches that in test_class_sh_basic.cpp\n// Variable names are intentionally terse, to not distract from the more important C++ type names:\n// valu(e), ref(erence), ptr or p (pointer), r = rvalue, m = mutable, c = const,\n// sh = shared_ptr, uq = unique_ptr.\n\n#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace test_class_sh_property {\n\nstruct ClassicField {\n    int num = -88;\n};\n\nstruct ClassicOuter {\n    ClassicField *m_mptr = nullptr;\n    const ClassicField *m_cptr = nullptr;\n};\n\nstruct Field {\n    int num = -99;\n};\n\nstruct Outer {\n    Field m_valu;\n    Field *m_mptr = nullptr;\n    const Field *m_cptr = nullptr;\n    std::unique_ptr<Field> m_uqmp;\n    std::unique_ptr<const Field> m_uqcp;\n    std::shared_ptr<Field> m_shmp;\n    std::shared_ptr<const Field> m_shcp;\n};\n\ninline void DisownOuter(std::unique_ptr<Outer>) {}\n\nstruct WithCharArrayMember {\n    WithCharArrayMember() { std::memcpy(char6_member, \"Char6\", 6); }\n    char char6_member[6];\n};\n\nstruct WithConstCharPtrMember {\n    const char *const_char_ptr_member = \"ConstChar*\";\n};\n\n} // namespace test_class_sh_property\n\nTEST_SUBMODULE(class_sh_property, m) {\n    using namespace test_class_sh_property;\n\n    py::class_<ClassicField, std::unique_ptr<ClassicField>>(m, \"ClassicField\")\n        .def(py::init<>())\n        .def_readwrite(\"num\", &ClassicField::num);\n\n    py::class_<ClassicOuter, std::unique_ptr<ClassicOuter>>(m, \"ClassicOuter\")\n        .def(py::init<>())\n        .def_readonly(\"m_mptr_readonly\", &ClassicOuter::m_mptr)\n        .def_readwrite(\"m_mptr_readwrite\", &ClassicOuter::m_mptr)\n        .def_readwrite(\"m_cptr_readonly\", &ClassicOuter::m_cptr)\n        .def_readwrite(\"m_cptr_readwrite\", &ClassicOuter::m_cptr);\n\n    py::classh<Field>(m, \"Field\").def(py::init<>()).def_readwrite(\"num\", &Field::num);\n\n    py::classh<Outer>(m, \"Outer\")\n        .def(py::init<>())\n\n        .def_readonly(\"m_valu_readonly\", &Outer::m_valu)\n        .def_readwrite(\"m_valu_readwrite\", &Outer::m_valu)\n\n        .def_readonly(\"m_mptr_readonly\", &Outer::m_mptr)\n        .def_readwrite(\"m_mptr_readwrite\", &Outer::m_mptr)\n        .def_readonly(\"m_cptr_readonly\", &Outer::m_cptr)\n        .def_readwrite(\"m_cptr_readwrite\", &Outer::m_cptr)\n\n        // .def_readonly(\"m_uqmp_readonly\", &Outer::m_uqmp) // Custom compilation Error.\n        .def_readwrite(\"m_uqmp_readwrite\", &Outer::m_uqmp)\n        // .def_readonly(\"m_uqcp_readonly\", &Outer::m_uqcp) // Custom compilation Error.\n        .def_readwrite(\"m_uqcp_readwrite\", &Outer::m_uqcp)\n\n        .def_readwrite(\"m_shmp_readonly\", &Outer::m_shmp)\n        .def_readwrite(\"m_shmp_readwrite\", &Outer::m_shmp)\n        .def_readwrite(\"m_shcp_readonly\", &Outer::m_shcp)\n        .def_readwrite(\"m_shcp_readwrite\", &Outer::m_shcp);\n\n    m.def(\"DisownOuter\", DisownOuter);\n\n    py::classh<WithCharArrayMember>(m, \"WithCharArrayMember\")\n        .def(py::init<>())\n        .def_readonly(\"char6_member\", &WithCharArrayMember::char6_member);\n\n    py::classh<WithConstCharPtrMember>(m, \"WithConstCharPtrMember\")\n        .def(py::init<>())\n        .def_readonly(\"const_char_ptr_member\", &WithConstCharPtrMember::const_char_ptr_member);\n}\n"
  },
  {
    "path": "tests/test_class_sh_property.py",
    "content": "# The compact 4-character naming scheme (e.g. mptr, cptr, shcp) is explained at the top of\n# test_class_sh_property.cpp.\nfrom __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import class_sh_property as m\n\n\n@pytest.mark.skipif(\n    \"env.PYPY or env.GRAALPY\", reason=\"gc after `del field` is apparently deferred\"\n)\n@pytest.mark.parametrize(\"m_attr\", [\"m_valu_readonly\", \"m_valu_readwrite\"])\ndef test_valu_getter(m_attr):\n    # Reduced from PyCLIF test:\n    # https://github.com/google/clif/blob/c371a6d4b28d25d53a16e6d2a6d97305fb1be25a/clif/testing/python/nested_fields_test.py#L56\n    outer = m.Outer()\n    field = getattr(outer, m_attr)\n    assert field.num == -99\n    with pytest.raises(ValueError) as excinfo:\n        m.DisownOuter(outer)\n    assert str(excinfo.value) == \"Cannot disown use_count != 1 (load_as_unique_ptr).\"\n    del field\n    m.DisownOuter(outer)\n    with pytest.raises(ValueError, match=\"Python instance was disowned\") as excinfo:\n        getattr(outer, m_attr)\n\n\ndef test_valu_setter():\n    outer = m.Outer()\n    assert outer.m_valu_readonly.num == -99\n    assert outer.m_valu_readwrite.num == -99\n    field = m.Field()\n    field.num = 35\n    outer.m_valu_readwrite = field\n    assert outer.m_valu_readonly.num == 35\n    assert outer.m_valu_readwrite.num == 35\n\n\n@pytest.mark.parametrize(\"m_attr\", [\"m_shmp\", \"m_shcp\"])\ndef test_shp(m_attr):\n    m_attr_readonly = m_attr + \"_readonly\"\n    m_attr_readwrite = m_attr + \"_readwrite\"\n    outer = m.Outer()\n    assert getattr(outer, m_attr_readonly) is None\n    assert getattr(outer, m_attr_readwrite) is None\n    field = m.Field()\n    field.num = 43\n    setattr(outer, m_attr_readwrite, field)\n    assert getattr(outer, m_attr_readonly).num == 43\n    assert getattr(outer, m_attr_readwrite).num == 43\n    getattr(outer, m_attr_readonly).num = 57\n    getattr(outer, m_attr_readwrite).num = 57\n    assert field.num == 57\n    del field\n    assert getattr(outer, m_attr_readonly).num == 57\n    assert getattr(outer, m_attr_readwrite).num == 57\n\n\n@pytest.mark.parametrize(\n    (\"field_type\", \"num_default\", \"outer_type\"),\n    [\n        (m.ClassicField, -88, m.ClassicOuter),\n        (m.Field, -99, m.Outer),\n    ],\n)\n@pytest.mark.parametrize(\"m_attr\", [\"m_mptr\", \"m_cptr\"])\n@pytest.mark.parametrize(\"r_kind\", [\"_readonly\", \"_readwrite\"])\ndef test_ptr(field_type, num_default, outer_type, m_attr, r_kind):\n    m_attr_r_kind = m_attr + r_kind\n    outer = outer_type()\n    assert getattr(outer, m_attr_r_kind) is None\n    field = field_type()\n    assert field.num == num_default\n    setattr(outer, m_attr + \"_readwrite\", field)\n    assert getattr(outer, m_attr_r_kind).num == num_default\n    field.num = 76\n    assert getattr(outer, m_attr_r_kind).num == 76\n    # Change to -88 or -99 to demonstrate Undefined Behavior (dangling pointer).\n    if num_default == 88 and m_attr == \"m_mptr\":\n        del field\n    assert getattr(outer, m_attr_r_kind).num == 76\n\n\n@pytest.mark.parametrize(\"m_attr_readwrite\", [\"m_uqmp_readwrite\", \"m_uqcp_readwrite\"])\ndef test_uqp(m_attr_readwrite):\n    outer = m.Outer()\n    assert getattr(outer, m_attr_readwrite) is None\n    field_orig = m.Field()\n    field_orig.num = 39\n    setattr(outer, m_attr_readwrite, field_orig)\n    with pytest.raises(ValueError, match=\"Python instance was disowned\"):\n        _ = field_orig.num\n    field_retr1 = getattr(outer, m_attr_readwrite)\n    assert getattr(outer, m_attr_readwrite) is None\n    assert field_retr1.num == 39\n    field_retr1.num = 93\n    setattr(outer, m_attr_readwrite, field_retr1)\n    with pytest.raises(ValueError):\n        _ = field_retr1.num\n    field_retr2 = getattr(outer, m_attr_readwrite)\n    assert field_retr2.num == 93\n\n\n# Proof-of-concept (POC) for safe & intuitive Python access to unique_ptr members.\n# The C++ member unique_ptr is disowned to a temporary Python object for accessing\n# an attribute of the member. After the attribute was accessed, the Python object\n# is disowned back to the C++ member unique_ptr.\n# Productizing this POC is left for a future separate PR, as needed.\nclass unique_ptr_field_proxy_poc:\n    def __init__(self, obj, field_name):\n        object.__setattr__(self, \"__obj\", obj)\n        object.__setattr__(self, \"__field_name\", field_name)\n\n    def __getattr__(self, *args, **kwargs):\n        return _proxy_dereference(self, getattr, *args, **kwargs)\n\n    def __setattr__(self, *args, **kwargs):\n        return _proxy_dereference(self, setattr, *args, **kwargs)\n\n    def __delattr__(self, *args, **kwargs):\n        return _proxy_dereference(self, delattr, *args, **kwargs)\n\n\ndef _proxy_dereference(proxy, xxxattr, *args, **kwargs):\n    obj = object.__getattribute__(proxy, \"__obj\")\n    field_name = object.__getattribute__(proxy, \"__field_name\")\n    field = getattr(obj, field_name)  # Disowns the C++ unique_ptr member.\n    assert field is not None\n    try:\n        return xxxattr(field, *args, **kwargs)\n    finally:\n        setattr(obj, field_name, field)  # Disowns the temporary Python object (field).\n\n\n@pytest.mark.parametrize(\"m_attr\", [\"m_uqmp\", \"m_uqcp\"])\ndef test_unique_ptr_field_proxy_poc(m_attr):\n    m_attr_readwrite = m_attr + \"_readwrite\"\n    outer = m.Outer()\n    field_orig = m.Field()\n    field_orig.num = 45\n    setattr(outer, m_attr_readwrite, field_orig)\n    field_proxy = unique_ptr_field_proxy_poc(outer, m_attr_readwrite)\n    assert field_proxy.num == 45\n    assert field_proxy.num == 45\n    with pytest.raises(AttributeError):\n        _ = field_proxy.xyz\n    assert field_proxy.num == 45\n    field_proxy.num = 82\n    assert field_proxy.num == 82\n    field_proxy = unique_ptr_field_proxy_poc(outer, m_attr_readwrite)\n    assert field_proxy.num == 82\n    with pytest.raises(AttributeError):\n        del field_proxy.num\n    assert field_proxy.num == 82\n\n\ndef test_readonly_char6_member():\n    obj = m.WithCharArrayMember()\n    assert obj.char6_member == \"Char6\"\n\n\ndef test_readonly_const_char_ptr_member():\n    obj = m.WithConstCharPtrMember()\n    assert obj.const_char_ptr_member == \"ConstChar*\"\n"
  },
  {
    "path": "tests/test_class_sh_property_non_owning.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <cstddef>\n#include <vector>\n\nnamespace test_class_sh_property_non_owning {\n\nstruct CoreField {\n    explicit CoreField(int int_value = -99) : int_value{int_value} {}\n    int int_value;\n};\n\nstruct DataField {\n    DataField(int i_value, int i_shared, int i_unique)\n        : core_fld_value{i_value}, core_fld_shared_ptr{new CoreField{i_shared}},\n          core_fld_raw_ptr{core_fld_shared_ptr.get()},\n          core_fld_unique_ptr{new CoreField{i_unique}} {}\n    CoreField core_fld_value;\n    std::shared_ptr<CoreField> core_fld_shared_ptr;\n    CoreField *core_fld_raw_ptr;\n    std::unique_ptr<CoreField> core_fld_unique_ptr;\n};\n\nstruct DataFieldsHolder {\nprivate:\n    std::vector<DataField> vec;\n\npublic:\n    explicit DataFieldsHolder(std::size_t vec_size) {\n        for (std::size_t i = 0; i < vec_size; i++) {\n            int i11 = static_cast<int>(i) * 11;\n            vec.emplace_back(13 + i11, 14 + i11, 15 + i11);\n        }\n    }\n\n    DataFieldsHolder(DataFieldsHolder &&) noexcept = default;\n\n    DataField *vec_at(std::size_t index) {\n        if (index >= vec.size()) {\n            return nullptr;\n        }\n        return &vec[index];\n    }\n};\n\n} // namespace test_class_sh_property_non_owning\n\nusing namespace test_class_sh_property_non_owning;\n\nTEST_SUBMODULE(class_sh_property_non_owning, m) {\n    py::classh<CoreField>(m, \"CoreField\").def_readwrite(\"int_value\", &CoreField::int_value);\n\n    py::classh<DataField>(m, \"DataField\")\n        .def_readonly(\"core_fld_value_ro\", &DataField::core_fld_value)\n        .def_readwrite(\"core_fld_value_rw\", &DataField::core_fld_value)\n        .def_readonly(\"core_fld_shared_ptr_ro\", &DataField::core_fld_shared_ptr)\n        .def_readwrite(\"core_fld_shared_ptr_rw\", &DataField::core_fld_shared_ptr)\n        .def_readonly(\"core_fld_raw_ptr_ro\", &DataField::core_fld_raw_ptr)\n        .def_readwrite(\"core_fld_raw_ptr_rw\", &DataField::core_fld_raw_ptr)\n        .def_readwrite(\"core_fld_unique_ptr_rw\", &DataField::core_fld_unique_ptr);\n\n    py::classh<DataFieldsHolder>(m, \"DataFieldsHolder\")\n        .def(py::init<std::size_t>())\n        .def(\"vec_at\", &DataFieldsHolder::vec_at, py::return_value_policy::reference_internal);\n}\n"
  },
  {
    "path": "tests/test_class_sh_property_non_owning.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_property_non_owning as m\n\n\n@pytest.mark.parametrize(\"persistent_holder\", [True, False])\n@pytest.mark.parametrize(\n    (\"core_fld\", \"expected\"),\n    [\n        (\"core_fld_value_ro\", (13, 24)),\n        (\"core_fld_value_rw\", (13, 24)),\n        (\"core_fld_shared_ptr_ro\", (14, 25)),\n        (\"core_fld_shared_ptr_rw\", (14, 25)),\n        (\"core_fld_raw_ptr_ro\", (14, 25)),\n        (\"core_fld_raw_ptr_rw\", (14, 25)),\n        (\"core_fld_unique_ptr_rw\", (15, 26)),\n    ],\n)\ndef test_core_fld_common(core_fld, expected, persistent_holder):\n    if persistent_holder:\n        h = m.DataFieldsHolder(2)\n        for i, exp in enumerate(expected):\n            c = getattr(h.vec_at(i), core_fld)\n            assert c.int_value == exp\n    else:\n        for i, exp in enumerate(expected):\n            c = getattr(m.DataFieldsHolder(2).vec_at(i), core_fld)\n            assert c.int_value == exp\n"
  },
  {
    "path": "tests/test_class_sh_shared_ptr_copy_move.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace pybind11_tests {\nnamespace {\n\nconst std::string fooNames[] = {\"ShPtr_\", \"SmHld_\"};\n\ntemplate <int SerNo>\nstruct Foo {\n    std::string history;\n    explicit Foo(const std::string &history_) : history(history_) {}\n    Foo(const Foo &other) : history(other.history + \"_CpCtor\") {}\n    Foo(Foo &&other) noexcept : history(other.history + \"_MvCtor\") {}\n    Foo &operator=(const Foo &other) {\n        history = other.history + \"_OpEqLv\";\n        return *this;\n    }\n    Foo &operator=(Foo &&other) noexcept {\n        history = other.history + \"_OpEqRv\";\n        return *this;\n    }\n    std::string get_history() const { return \"Foo\" + fooNames[SerNo] + history; }\n};\n\nusing FooShPtr = Foo<0>;\nusing FooSmHld = Foo<1>;\n\nstruct Outer {\n    std::shared_ptr<FooShPtr> ShPtr;\n    std::shared_ptr<FooSmHld> SmHld;\n    Outer()\n        : ShPtr(std::make_shared<FooShPtr>(\"Outer\")), SmHld(std::make_shared<FooSmHld>(\"Outer\")) {}\n    std::shared_ptr<FooShPtr> getShPtr() const { return ShPtr; }\n    std::shared_ptr<FooSmHld> getSmHld() const { return SmHld; }\n};\n\n} // namespace\n\nTEST_SUBMODULE(class_sh_shared_ptr_copy_move, m) {\n    namespace py = pybind11;\n\n    py::class_<FooShPtr, std::shared_ptr<FooShPtr>>(m, \"FooShPtr\")\n        .def(\"get_history\", &FooShPtr::get_history);\n    py::classh<FooSmHld>(m, \"FooSmHld\").def(\"get_history\", &FooSmHld::get_history);\n\n    auto outer = py::class_<Outer>(m, \"Outer\").def(py::init());\n#define MAKE_PROP(PropTyp)                                                                        \\\n    MAKE_PROP_FOO(ShPtr, PropTyp)                                                                 \\\n    MAKE_PROP_FOO(SmHld, PropTyp)\n\n#define MAKE_PROP_FOO(FooTyp, PropTyp)                                                            \\\n    .def_##PropTyp(#FooTyp \"_\" #PropTyp \"_default\", &Outer::FooTyp)                               \\\n        .def_##PropTyp(                                                                           \\\n            #FooTyp \"_\" #PropTyp \"_copy\", &Outer::FooTyp, py::return_value_policy::copy)          \\\n        .def_##PropTyp(                                                                           \\\n            #FooTyp \"_\" #PropTyp \"_move\", &Outer::FooTyp, py::return_value_policy::move)\n    outer MAKE_PROP(readonly) MAKE_PROP(readwrite);\n#undef MAKE_PROP_FOO\n\n#define MAKE_PROP_FOO(FooTyp, PropTyp)                                                            \\\n    .def_##PropTyp(#FooTyp \"_property_\" #PropTyp \"_default\", &Outer::FooTyp)                      \\\n        .def_property_##PropTyp(#FooTyp \"_property_\" #PropTyp \"_copy\",                            \\\n                                &Outer::get##FooTyp,                                              \\\n                                py::return_value_policy::copy)                                    \\\n        .def_property_##PropTyp(#FooTyp \"_property_\" #PropTyp \"_move\",                            \\\n                                &Outer::get##FooTyp,                                              \\\n                                py::return_value_policy::move)\n    outer MAKE_PROP(readonly);\n#undef MAKE_PROP_FOO\n#undef MAKE_PROP\n\n    m.def(\"test_ShPtr_copy\", []() {\n        auto o = std::make_shared<FooShPtr>(\"copy\");\n        auto l = py::list();\n        l.append(o);\n        return l;\n    });\n    m.def(\"test_SmHld_copy\", []() {\n        auto o = std::make_shared<FooSmHld>(\"copy\");\n        auto l = py::list();\n        l.append(o);\n        return l;\n    });\n\n    m.def(\"test_ShPtr_move\", []() {\n        auto o = std::make_shared<FooShPtr>(\"move\");\n        auto l = py::list();\n        l.append(std::move(o));\n        return l;\n    });\n    m.def(\"test_SmHld_move\", []() {\n        auto o = std::make_shared<FooSmHld>(\"move\");\n        auto l = py::list();\n        l.append(std::move(o));\n        return l;\n    });\n}\n\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_class_sh_shared_ptr_copy_move.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import class_sh_shared_ptr_copy_move as m\n\n\ndef test_shptr_copy():\n    txt = m.test_ShPtr_copy()[0].get_history()\n    assert txt == \"FooShPtr_copy\"\n\n\ndef test_smhld_copy():\n    txt = m.test_SmHld_copy()[0].get_history()\n    assert txt == \"FooSmHld_copy\"\n\n\ndef test_shptr_move():\n    txt = m.test_ShPtr_move()[0].get_history()\n    assert txt == \"FooShPtr_move\"\n\n\ndef test_smhld_move():\n    txt = m.test_SmHld_move()[0].get_history()\n    assert txt == \"FooSmHld_move\"\n\n\ndef _check_property(foo_typ, prop_typ, policy):\n    o = m.Outer()\n    name = f\"{foo_typ}_{prop_typ}_{policy}\"\n    history = f\"Foo{foo_typ}_Outer\"\n    f = getattr(o, name)\n    assert f.get_history() == history\n    # and try again to check that o did not get changed\n    f = getattr(o, name)\n    assert f.get_history() == history\n\n\ndef test_properties():\n    for prop_typ in (\"readonly\", \"readwrite\", \"property_readonly\"):\n        for foo_typ in (\"ShPtr\", \"SmHld\"):\n            for policy in (\"default\", \"copy\", \"move\"):\n                _check_property(foo_typ, prop_typ, policy)\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_basic.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_basic {\n\nstruct Abase {\n    int val = 0;\n    virtual ~Abase() = default;\n    explicit Abase(int val_) : val{val_} {}\n    int Get() const { return val * 10 + 3; }\n    virtual int Add(int other_val) const = 0;\n\n    // Some compilers complain about implicitly defined versions of some of the following:\n    Abase(const Abase &) = default;\n    Abase(Abase &&) noexcept = default;\n    Abase &operator=(const Abase &) = default;\n    Abase &operator=(Abase &&) noexcept = default;\n};\n\nstruct AbaseAlias : Abase, py::trampoline_self_life_support {\n    using Abase::Abase;\n\n    int Add(int other_val) const override {\n        PYBIND11_OVERRIDE_PURE(int,   /* Return type */\n                               Abase, /* Parent class */\n                               Add,   /* Name of function in C++ (must match Python name) */\n                               other_val);\n    }\n};\n\nint AddInCppRawPtr(const Abase *obj, int other_val) { return obj->Add(other_val) * 10 + 7; }\n\nint AddInCppSharedPtr(const std::shared_ptr<Abase> &obj, int other_val) {\n    return obj->Add(other_val) * 100 + 11;\n}\n\nint AddInCppUniquePtr(std::unique_ptr<Abase> obj, int other_val) {\n    return obj->Add(other_val) * 100 + 13;\n}\n\n} // namespace class_sh_trampoline_basic\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::class_sh_trampoline_basic;\n\nTEST_SUBMODULE(class_sh_trampoline_basic, m) {\n    py::classh<Abase, AbaseAlias>(m, \"Abase\")\n        .def(py::init<int>(), py::arg(\"val\"))\n        .def(\"Get\", &Abase::Get)\n        .def(\"Add\", &Abase::Add, py::arg(\"other_val\"));\n\n    m.def(\"AddInCppRawPtr\", AddInCppRawPtr, py::arg(\"obj\"), py::arg(\"other_val\"));\n    m.def(\"AddInCppSharedPtr\", AddInCppSharedPtr, py::arg(\"obj\"), py::arg(\"other_val\"));\n    m.def(\"AddInCppUniquePtr\", AddInCppUniquePtr, py::arg(\"obj\"), py::arg(\"other_val\"));\n}\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_basic.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import class_sh_trampoline_basic as m\n\n\nclass PyDrvd(m.Abase):\n    def __init__(self, val):\n        super().__init__(val)\n\n    def Add(self, other_val):\n        return self.Get() * 100 + other_val\n\n\ndef test_drvd_add():\n    drvd = PyDrvd(74)\n    assert drvd.Add(38) == (74 * 10 + 3) * 100 + 38\n\n\ndef test_drvd_add_in_cpp_raw_ptr():\n    drvd = PyDrvd(52)\n    assert m.AddInCppRawPtr(drvd, 27) == ((52 * 10 + 3) * 100 + 27) * 10 + 7\n\n\ndef test_drvd_add_in_cpp_shared_ptr():\n    while True:\n        drvd = PyDrvd(36)\n        assert m.AddInCppSharedPtr(drvd, 56) == ((36 * 10 + 3) * 100 + 56) * 100 + 11\n        return  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_drvd_add_in_cpp_unique_ptr():\n    while True:\n        drvd = PyDrvd(25)\n        assert m.AddInCppUniquePtr(drvd, 83) == ((25 * 10 + 3) * 100 + 83) * 100 + 13\n        return  # Comment out for manual leak checking (use `top` command).\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_self_life_support.cpp",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11/trampoline_self_life_support.h\"\n#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <string>\n#include <utility>\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_self_life_support {\n\nstruct Big5 { // Also known as \"rule of five\".\n    std::string history;\n\n    explicit Big5(std::string history_start) : history{std::move(history_start)} {}\n\n    Big5(const Big5 &other) { history = other.history + \"_CpCtor\"; }\n\n    Big5(Big5 &&other) noexcept { history = other.history + \"_MvCtor\"; }\n\n    Big5 &operator=(const Big5 &other) {\n        history = other.history + \"_OpEqLv\";\n        return *this;\n    }\n\n    Big5 &operator=(Big5 &&other) noexcept {\n        history = other.history + \"_OpEqRv\";\n        return *this;\n    }\n\n    virtual ~Big5() = default;\n\nprotected:\n    Big5() : history{\"DefaultConstructor\"} {}\n};\n\nstruct Big5Trampoline : Big5, py::trampoline_self_life_support {\n    using Big5::Big5;\n};\n\n} // namespace class_sh_trampoline_self_life_support\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::class_sh_trampoline_self_life_support;\n\nTEST_SUBMODULE(class_sh_trampoline_self_life_support, m) {\n    py::classh<Big5, Big5Trampoline>(m, \"Big5\")\n        .def(py::init<std::string>())\n        .def_readonly(\"history\", &Big5::history);\n\n    m.def(\"action\", [](std::unique_ptr<Big5> obj, int action_id) {\n        py::object o2 = py::none();\n        // This is very unusual, but needed to directly exercise the trampoline_self_life_support\n        // CpCtor, MvCtor, operator= lvalue, operator= rvalue.\n        auto *obj_trampoline = dynamic_cast<Big5Trampoline *>(obj.get());\n        if (obj_trampoline != nullptr) {\n            switch (action_id) {\n                case 0: { // CpCtor\n                    std::unique_ptr<Big5> cp(new Big5Trampoline(*obj_trampoline));\n                    o2 = py::cast(std::move(cp));\n                } break;\n                case 1: { // MvCtor\n                    std::unique_ptr<Big5> mv(new Big5Trampoline(std::move(*obj_trampoline)));\n                    o2 = py::cast(std::move(mv));\n                } break;\n                case 2: { // operator= lvalue\n                    std::unique_ptr<Big5> lv(new Big5Trampoline);\n                    *lv = *obj_trampoline; // NOLINT clang-tidy cppcoreguidelines-slicing\n                    o2 = py::cast(std::move(lv));\n                } break;\n                case 3: { // operator= rvalue\n                    std::unique_ptr<Big5> rv(new Big5Trampoline);\n                    *rv = std::move(*obj_trampoline);\n                    o2 = py::cast(std::move(rv));\n                } break;\n                default:\n                    break;\n            }\n        }\n        py::object o1 = py::cast(std::move(obj));\n        return py::make_tuple(o1, o2);\n    });\n}\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_self_life_support.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport pybind11_tests.class_sh_trampoline_self_life_support as m\n\n\nclass PyBig5(m.Big5):\n    pass\n\n\ndef test_m_big5():\n    obj = m.Big5(\"Seed\")\n    assert obj.history == \"Seed\"\n    o1, o2 = m.action(obj, 0)\n    assert o1 is not obj\n    assert o1.history == \"Seed\"\n    with pytest.raises(ValueError) as excinfo:\n        _ = obj.history\n    assert \"Python instance was disowned\" in str(excinfo.value)\n    assert o2 is None\n\n\n@pytest.mark.parametrize(\n    (\"action_id\", \"expected_history\"),\n    [\n        (0, \"Seed_CpCtor\"),\n        (1, \"Seed_MvCtor\"),\n        (2, \"Seed_OpEqLv\"),\n        (3, \"Seed_OpEqRv\"),\n    ],\n)\ndef test_py_big5(action_id, expected_history):\n    obj = PyBig5(\"Seed\")\n    assert obj.history == \"Seed\"\n    o1, o2 = m.action(obj, action_id)\n    assert o1 is obj\n    assert o2.history == expected_history\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_shared_from_this.cpp",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <string>\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_shared_from_this {\n\nstruct Sft : std::enable_shared_from_this<Sft> {\n    std::string history;\n    explicit Sft(const std::string &history_seed) : history{history_seed} {}\n    virtual ~Sft() = default;\n\n#if defined(__clang__)\n    // \"Group of 4\" begin.\n    // This group is not meant to be used, but will leave a trace in the\n    // history in case something goes wrong.\n    // However, compilers other than clang have a variety of issues. It is not\n    // worth the trouble covering all platforms.\n    Sft(const Sft &other) : enable_shared_from_this(other) { history = other.history + \"_CpCtor\"; }\n\n    Sft(Sft &&other) noexcept { history = other.history + \"_MvCtor\"; }\n\n    Sft &operator=(const Sft &other) {\n        history = other.history + \"_OpEqLv\";\n        return *this;\n    }\n\n    Sft &operator=(Sft &&other) noexcept {\n        history = other.history + \"_OpEqRv\";\n        return *this;\n    }\n    // \"Group of 4\" end.\n#endif\n};\n\nstruct SftSharedPtrStash {\n    int ser_no;\n    std::vector<std::shared_ptr<Sft>> stash;\n    explicit SftSharedPtrStash(int ser_no) : ser_no{ser_no} {}\n    void Clear() { stash.clear(); }\n    void Add(const std::shared_ptr<Sft> &obj) {\n        if (!obj->history.empty()) {\n            obj->history += \"_Stash\" + std::to_string(ser_no) + \"Add\";\n        }\n        stash.push_back(obj);\n    }\n    void AddSharedFromThis(Sft *obj) {\n        auto sft = obj->shared_from_this();\n        if (!sft->history.empty()) {\n            sft->history += \"_Stash\" + std::to_string(ser_no) + \"AddSharedFromThis\";\n        }\n        stash.push_back(sft);\n    }\n    std::string history(unsigned i) {\n        if (i < stash.size()) {\n            return stash[i]->history;\n        }\n        return \"OutOfRange\";\n    }\n    long use_count(unsigned i) {\n        if (i < stash.size()) {\n            return stash[i].use_count();\n        }\n        return -1;\n    }\n};\n\nstruct SftTrampoline : Sft, py::trampoline_self_life_support {\n    using Sft::Sft;\n};\n\nlong use_count(const std::shared_ptr<Sft> &obj) { return obj.use_count(); }\n\nlong pass_shared_ptr(const std::shared_ptr<Sft> &obj) {\n    auto sft = obj->shared_from_this();\n    if (!sft->history.empty()) {\n        sft->history += \"_PassSharedPtr\";\n    }\n    return sft.use_count();\n}\n\nstd::string pass_unique_ptr_cref(const std::unique_ptr<Sft> &obj) {\n    return obj ? obj->history : \"<NULLPTR>\";\n}\nvoid pass_unique_ptr_rref(std::unique_ptr<Sft> &&) {\n    throw std::runtime_error(\"Expected to not be reached.\");\n}\n\nSft *make_pure_cpp_sft_raw_ptr(const std::string &history_seed) { return new Sft{history_seed}; }\n\nstd::unique_ptr<Sft> make_pure_cpp_sft_unq_ptr(const std::string &history_seed) {\n    return std::unique_ptr<Sft>(new Sft{history_seed});\n}\n\nstd::shared_ptr<Sft> make_pure_cpp_sft_shd_ptr(const std::string &history_seed) {\n    return std::make_shared<Sft>(history_seed);\n}\n\nstd::shared_ptr<Sft> pass_through_shd_ptr(const std::shared_ptr<Sft> &obj) { return obj; }\n\n} // namespace class_sh_trampoline_shared_from_this\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::class_sh_trampoline_shared_from_this;\n\nTEST_SUBMODULE(class_sh_trampoline_shared_from_this, m) {\n    py::classh<Sft, SftTrampoline>(m, \"Sft\")\n        .def(py::init<const std::string &>())\n        .def(py::init([](const std::string &history, int) {\n            return std::make_shared<SftTrampoline>(history);\n        }))\n        .def_readonly(\"history\", &Sft::history)\n        // This leads to multiple entries in registered_instances:\n        .def(py::init([](const std::shared_ptr<Sft> &existing) { return existing; }));\n\n    py::classh<SftSharedPtrStash>(m, \"SftSharedPtrStash\")\n        .def(py::init<int>())\n        .def(\"Clear\", &SftSharedPtrStash::Clear)\n        .def(\"Add\", &SftSharedPtrStash::Add)\n        .def(\"AddSharedFromThis\", &SftSharedPtrStash::AddSharedFromThis)\n        .def(\"history\", &SftSharedPtrStash::history)\n        .def(\"use_count\", &SftSharedPtrStash::use_count);\n\n    m.def(\"use_count\", use_count);\n    m.def(\"pass_shared_ptr\", pass_shared_ptr);\n    m.def(\"pass_unique_ptr_cref\", pass_unique_ptr_cref);\n    m.def(\"pass_unique_ptr_rref\", pass_unique_ptr_rref);\n    m.def(\"make_pure_cpp_sft_raw_ptr\", make_pure_cpp_sft_raw_ptr);\n    m.def(\"make_pure_cpp_sft_unq_ptr\", make_pure_cpp_sft_unq_ptr);\n    m.def(\"make_pure_cpp_sft_shd_ptr\", make_pure_cpp_sft_shd_ptr);\n    m.def(\"pass_through_shd_ptr\", pass_through_shd_ptr);\n}\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_shared_from_this.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport weakref\n\nimport pytest\n\nimport env\nimport pybind11_tests.class_sh_trampoline_shared_from_this as m\n\n\nclass PySft(m.Sft):\n    pass\n\n\ndef test_release_and_shared_from_this():\n    # Exercises the most direct path from building a shared_from_this-visible\n    # shared_ptr to calling shared_from_this.\n    obj = PySft(\"PySft\")\n    assert obj.history == \"PySft\"\n    assert m.use_count(obj) == 1\n    assert m.pass_shared_ptr(obj) == 2\n    assert obj.history == \"PySft_PassSharedPtr\"\n    assert m.use_count(obj) == 1\n    assert m.pass_shared_ptr(obj) == 2\n    assert obj.history == \"PySft_PassSharedPtr_PassSharedPtr\"\n    assert m.use_count(obj) == 1\n\n\ndef test_release_and_shared_from_this_leak():\n    obj = PySft(\"\")\n    while True:\n        m.pass_shared_ptr(obj)\n        assert not obj.history\n        assert m.use_count(obj) == 1\n        break  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_release_and_stash():\n    # Exercises correct functioning of guarded_delete weak_ptr.\n    obj = PySft(\"PySft\")\n    stash1 = m.SftSharedPtrStash(1)\n    stash1.Add(obj)\n    exp_hist = \"PySft_Stash1Add\"\n    assert obj.history == exp_hist\n    assert m.use_count(obj) == 2\n    assert stash1.history(0) == exp_hist\n    assert stash1.use_count(0) == 1\n    assert m.pass_shared_ptr(obj) == 3\n    exp_hist += \"_PassSharedPtr\"\n    assert obj.history == exp_hist\n    assert m.use_count(obj) == 2\n    assert stash1.history(0) == exp_hist\n    assert stash1.use_count(0) == 1\n    stash2 = m.SftSharedPtrStash(2)\n    stash2.Add(obj)\n    exp_hist += \"_Stash2Add\"\n    assert obj.history == exp_hist\n    assert m.use_count(obj) == 3\n    assert stash2.history(0) == exp_hist\n    assert stash2.use_count(0) == 2\n    stash2.Add(obj)\n    exp_hist += \"_Stash2Add\"\n    assert obj.history == exp_hist\n    assert m.use_count(obj) == 4\n    assert stash1.history(0) == exp_hist\n    assert stash1.use_count(0) == 3\n    assert stash2.history(0) == exp_hist\n    assert stash2.use_count(0) == 3\n    assert stash2.history(1) == exp_hist\n    assert stash2.use_count(1) == 3\n    del obj\n    assert stash2.history(0) == exp_hist\n    assert stash2.use_count(0) == 3\n    assert stash2.history(1) == exp_hist\n    assert stash2.use_count(1) == 3\n    stash2.Clear()\n    assert stash1.history(0) == exp_hist\n    assert stash1.use_count(0) == 1\n\n\ndef test_release_and_stash_leak():\n    obj = PySft(\"\")\n    while True:\n        stash1 = m.SftSharedPtrStash(1)\n        stash1.Add(obj)\n        assert not obj.history\n        assert m.use_count(obj) == 2\n        assert stash1.use_count(0) == 1\n        stash1.Add(obj)\n        assert not obj.history\n        assert m.use_count(obj) == 3\n        assert stash1.use_count(0) == 2\n        assert stash1.use_count(1) == 2\n        break  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_release_and_stash_via_shared_from_this():\n    # Exercises that the smart_holder vptr is invisible to the shared_from_this mechanism.\n    obj = PySft(\"PySft\")\n    stash1 = m.SftSharedPtrStash(1)\n    with pytest.raises(RuntimeError) as exc_info:\n        stash1.AddSharedFromThis(obj)\n    assert str(exc_info.value) == \"bad_weak_ptr\"\n    stash1.Add(obj)\n    assert obj.history == \"PySft_Stash1Add\"\n    assert stash1.use_count(0) == 1\n    stash1.AddSharedFromThis(obj)\n    assert obj.history == \"PySft_Stash1Add_Stash1AddSharedFromThis\"\n    assert stash1.use_count(0) == 2\n    assert stash1.use_count(1) == 2\n\n\ndef test_release_and_stash_via_shared_from_this_leak():\n    obj = PySft(\"\")\n    while True:\n        stash1 = m.SftSharedPtrStash(1)\n        with pytest.raises(RuntimeError) as exc_info:\n            stash1.AddSharedFromThis(obj)\n        assert str(exc_info.value) == \"bad_weak_ptr\"\n        stash1.Add(obj)\n        assert not obj.history\n        assert stash1.use_count(0) == 1\n        stash1.AddSharedFromThis(obj)\n        assert not obj.history\n        assert stash1.use_count(0) == 2\n        assert stash1.use_count(1) == 2\n        break  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_pass_released_shared_ptr_as_unique_ptr():\n    # Exercises that returning a unique_ptr fails while a shared_from_this\n    # visible shared_ptr exists.\n    obj = PySft(\"PySft\")\n    stash1 = m.SftSharedPtrStash(1)\n    stash1.Add(obj)  # Releases shared_ptr to C++.\n    assert m.pass_unique_ptr_cref(obj) == \"PySft_Stash1Add\"\n    assert obj.history == \"PySft_Stash1Add\"\n    with pytest.raises(ValueError) as exc_info:\n        m.pass_unique_ptr_rref(obj)\n    assert str(exc_info.value) == (\n        \"Python instance is currently owned by a std::shared_ptr.\"\n    )\n    assert obj.history == \"PySft_Stash1Add\"\n\n\n@pytest.mark.parametrize(\n    \"make_f\",\n    [\n        m.make_pure_cpp_sft_raw_ptr,\n        m.make_pure_cpp_sft_unq_ptr,\n        m.make_pure_cpp_sft_shd_ptr,\n    ],\n)\ndef test_pure_cpp_sft_raw_ptr(make_f):\n    # Exercises void_cast_raw_ptr logic for different situations.\n    obj = make_f(\"PureCppSft\")\n    assert m.pass_shared_ptr(obj) == 3\n    assert obj.history == \"PureCppSft_PassSharedPtr\"\n    obj = make_f(\"PureCppSft\")\n    stash1 = m.SftSharedPtrStash(1)\n    stash1.AddSharedFromThis(obj)\n    assert obj.history == \"PureCppSft_Stash1AddSharedFromThis\"\n\n\ndef test_multiple_registered_instances_for_same_pointee():\n    obj0 = PySft(\"PySft\")\n    obj0.attachment_in_dict = \"Obj0\"\n    assert m.pass_through_shd_ptr(obj0) is obj0\n    while True:\n        obj = m.Sft(obj0)\n        assert obj is not obj0\n        obj_pt = m.pass_through_shd_ptr(obj)\n        # Unpredictable! Because registered_instances is as std::unordered_multimap.\n        assert obj_pt is obj0 or obj_pt is obj\n        # Multiple registered_instances for the same pointee can lead to unpredictable results:\n        if obj_pt is obj0:\n            assert obj_pt.attachment_in_dict == \"Obj0\"\n        else:\n            assert not hasattr(obj_pt, \"attachment_in_dict\")\n        assert obj0.history == \"PySft\"\n        break  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_multiple_registered_instances_for_same_pointee_leak():\n    obj0 = PySft(\"\")\n    while True:\n        stash1 = m.SftSharedPtrStash(1)\n        stash1.Add(m.Sft(obj0))\n        assert stash1.use_count(0) == 1\n        stash1.Add(m.Sft(obj0))\n        assert stash1.use_count(0) == 1\n        assert stash1.use_count(1) == 1\n        assert not obj0.history\n        break  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_multiple_registered_instances_for_same_pointee_recursive():\n    while True:\n        obj0 = PySft(\"PySft\")\n        if not env.PYPY:\n            obj0_wr = weakref.ref(obj0)\n        obj = obj0\n        # This loop creates a chain of instances linked by shared_ptrs.\n        for _ in range(10):\n            obj_next = m.Sft(obj)\n            assert obj_next is not obj\n            obj = obj_next\n            del obj_next\n            assert obj.history == \"PySft\"\n        del obj0\n        if not env.PYPY and not env.GRAALPY:\n            assert obj0_wr() is not None\n        del obj  # This releases the chain recursively.\n        if not env.PYPY and not env.GRAALPY:\n            assert obj0_wr() is None\n        break  # Comment out for manual leak checking (use `top` command).\n\n\n# As of 2021-07-10 the pybind11 GitHub Actions valgrind build uses Python 3.9.\nWORKAROUND_ENABLING_ROLLBACK_OF_PR3068 = env.LINUX and sys.version_info == (3, 9)\n\n\ndef test_std_make_shared_factory():\n    class PySftMakeShared(m.Sft):\n        def __init__(self, history):\n            super().__init__(history, 0)\n\n    obj = PySftMakeShared(\"PySftMakeShared\")\n    assert obj.history == \"PySftMakeShared\"\n    if WORKAROUND_ENABLING_ROLLBACK_OF_PR3068:\n        try:\n            m.pass_through_shd_ptr(obj)\n        except RuntimeError as e:\n            str_exc_info_value = str(e)\n        else:\n            str_exc_info_value = \"RuntimeError NOT RAISED\"\n    else:\n        with pytest.raises(RuntimeError) as exc_info:\n            m.pass_through_shd_ptr(obj)\n        str_exc_info_value = str(exc_info.value)\n    assert (\n        str_exc_info_value\n        == \"smart_holder_type_casters load_as_shared_ptr failure: not implemented:\"\n        \" trampoline-self-life-support for external shared_ptr to type inheriting\"\n        \" from std::enable_shared_from_this.\"\n    )\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_shared_ptr_cpp_arg.cpp",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_shared_ptr_cpp_arg {\n\n// For testing whether a python subclass of a C++ object dies when the\n// last python reference is lost\nstruct SpBase {\n    // returns true if the base virtual function is called\n    virtual bool is_base_used() { return true; }\n\n    // returns true if there's an associated python instance\n    bool has_python_instance() {\n        auto *tinfo = py::detail::get_type_info(typeid(SpBase));\n        return (bool) py::detail::get_object_handle(this, tinfo);\n    }\n\n    SpBase() = default;\n    SpBase(const SpBase &) = delete;\n    virtual ~SpBase() = default;\n};\n\nstd::shared_ptr<SpBase> pass_through_shd_ptr(const std::shared_ptr<SpBase> &obj) { return obj; }\n\nstruct PySpBase : SpBase, py::trampoline_self_life_support {\n    using SpBase::SpBase;\n    bool is_base_used() override { PYBIND11_OVERRIDE(bool, SpBase, is_base_used); }\n};\n\nstruct SpBaseTester {\n    std::shared_ptr<SpBase> get_object() const { return m_obj; }\n    void set_object(std::shared_ptr<SpBase> obj) { m_obj = std::move(obj); }\n    bool is_base_used() const { return m_obj->is_base_used(); }\n    bool has_instance() const { return (bool) m_obj; }\n    bool has_python_instance() const { return m_obj && m_obj->has_python_instance(); }\n    void set_nonpython_instance() { m_obj = std::make_shared<SpBase>(); }\n    std::shared_ptr<SpBase> m_obj;\n};\n\n// For testing that a C++ class without an alias does not retain the python\n// portion of the object\nstruct SpGoAway {};\n\nstruct SpGoAwayTester {\n    std::shared_ptr<SpGoAway> m_obj;\n};\n\n} // namespace class_sh_trampoline_shared_ptr_cpp_arg\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::class_sh_trampoline_shared_ptr_cpp_arg;\n\nTEST_SUBMODULE(class_sh_trampoline_shared_ptr_cpp_arg, m) {\n    // For testing whether a python subclass of a C++ object dies when the\n    // last python reference is lost\n\n    py::classh<SpBase, PySpBase>(m, \"SpBase\")\n        .def(py::init<>())\n        .def(py::init([](int) { return std::make_shared<PySpBase>(); }))\n        .def(\"is_base_used\", &SpBase::is_base_used)\n        .def(\"has_python_instance\", &SpBase::has_python_instance);\n\n    m.def(\"pass_through_shd_ptr\", pass_through_shd_ptr);\n    m.def(\"pass_through_shd_ptr_release_gil\",\n          pass_through_shd_ptr,\n          py::call_guard<py::gil_scoped_release>()); // PR #4196\n\n    py::classh<SpBaseTester>(m, \"SpBaseTester\")\n        .def(py::init<>())\n        .def(\"get_object\", &SpBaseTester::get_object)\n        .def(\"set_object\", &SpBaseTester::set_object)\n        .def(\"is_base_used\", &SpBaseTester::is_base_used)\n        .def(\"has_instance\", &SpBaseTester::has_instance)\n        .def(\"has_python_instance\", &SpBaseTester::has_python_instance)\n        .def(\"set_nonpython_instance\", &SpBaseTester::set_nonpython_instance)\n        .def_readwrite(\"obj\", &SpBaseTester::m_obj);\n\n    // For testing that a C++ class without an alias does not retain the python\n    // portion of the object\n\n    py::classh<SpGoAway>(m, \"SpGoAway\").def(py::init<>());\n\n    py::classh<SpGoAwayTester>(m, \"SpGoAwayTester\")\n        .def(py::init<>())\n        .def_readwrite(\"obj\", &SpGoAwayTester::m_obj);\n}\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_shared_ptr_cpp_arg.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nimport pybind11_tests.class_sh_trampoline_shared_ptr_cpp_arg as m\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_cpp_arg():\n    import weakref\n\n    class PyChild(m.SpBase):\n        def is_base_used(self):\n            return False\n\n    tester = m.SpBaseTester()\n\n    obj = PyChild()\n    objref = weakref.ref(obj)\n\n    # Pass the last python reference to the C++ function\n    tester.set_object(obj)\n    del obj\n    pytest.gc_collect()\n\n    # python reference is still around since C++ has it now\n    assert objref() is not None\n    assert tester.is_base_used() is False\n    assert tester.obj.is_base_used() is False\n    assert tester.get_object() is objref()\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_cpp_prop():\n    class PyChild(m.SpBase):\n        def is_base_used(self):\n            return False\n\n    tester = m.SpBaseTester()\n\n    # Set the last python reference as a property of the C++ object\n    tester.obj = PyChild()\n    pytest.gc_collect()\n\n    # python reference is still around since C++ has it now\n    assert tester.is_base_used() is False\n    assert tester.has_python_instance() is True\n    assert tester.obj.is_base_used() is False\n    assert tester.obj.has_python_instance() is True\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_arg_identity():\n    import weakref\n\n    tester = m.SpBaseTester()\n\n    obj = m.SpBase()\n    objref = weakref.ref(obj)\n\n    tester.set_object(obj)\n    del obj\n    pytest.gc_collect()\n\n    # NOTE: the behavior below is DIFFERENT from PR #2839\n    # python reference is gone because it is not an Alias instance\n    assert objref() is None\n    assert tester.has_python_instance() is False\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_alias_nonpython():\n    tester = m.SpBaseTester()\n\n    # C++ creates the object, a python instance shouldn't exist\n    tester.set_nonpython_instance()\n    assert tester.is_base_used() is True\n    assert tester.has_instance() is True\n    assert tester.has_python_instance() is False\n\n    # Now a python instance exists\n    cobj = tester.get_object()\n    assert cobj.has_python_instance()\n    assert tester.has_instance() is True\n    assert tester.has_python_instance() is True\n\n    # Now it's gone\n    del cobj\n    pytest.gc_collect()\n    assert tester.has_instance() is True\n    assert tester.has_python_instance() is False\n\n    # When we pass it as an arg to a new tester the python instance should\n    # disappear because it wasn't created with an alias\n    new_tester = m.SpBaseTester()\n\n    cobj = tester.get_object()\n    assert cobj.has_python_instance()\n\n    new_tester.set_object(cobj)\n    assert tester.has_python_instance() is True\n    assert new_tester.has_python_instance() is True\n\n    del cobj\n    pytest.gc_collect()\n\n    # Gone!\n    assert tester.has_instance() is True\n    assert tester.has_python_instance() is False\n    assert new_tester.has_instance() is True\n    assert new_tester.has_python_instance() is False\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_goaway():\n    import weakref\n\n    tester = m.SpGoAwayTester()\n\n    obj = m.SpGoAway()\n    objref = weakref.ref(obj)\n\n    assert tester.obj is None\n\n    tester.obj = obj\n    del obj\n    pytest.gc_collect()\n\n    # python reference is no longer around\n    assert objref() is None\n    # C++ reference is still around\n    assert tester.obj is not None\n\n\ndef test_infinite():\n    tester = m.SpBaseTester()\n    while True:\n        tester.set_object(m.SpBase())\n        break  # Comment out for manual leak checking (use `top` command).\n\n\n@pytest.mark.parametrize(\n    \"pass_through_func\", [m.pass_through_shd_ptr, m.pass_through_shd_ptr_release_gil]\n)\ndef test_std_make_shared_factory(pass_through_func):\n    class PyChild(m.SpBase):\n        def __init__(self):\n            super().__init__(0)\n\n    obj = PyChild()\n    while True:\n        assert pass_through_func(obj) is obj\n        break  # Comment out for manual leak checking (use `top` command).\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_unique_ptr.cpp",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11/trampoline_self_life_support.h\"\n#include \"pybind11_tests.h\"\n\n#include <cstdint>\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_unique_ptr {\n\nclass Class {\npublic:\n    virtual ~Class() = default;\n\n    void setVal(std::uint64_t val) { val_ = val; }\n    std::uint64_t getVal() const { return val_; }\n\n    virtual std::unique_ptr<Class> clone() const = 0;\n    virtual int foo() const = 0;\n\nprotected:\n    Class() = default;\n\n    // Some compilers complain about implicitly defined versions of some of the following:\n    Class(const Class &) = default;\n\nprivate:\n    std::uint64_t val_ = 0;\n};\n\n} // namespace class_sh_trampoline_unique_ptr\n} // namespace pybind11_tests\n\nnamespace pybind11_tests {\nnamespace class_sh_trampoline_unique_ptr {\n\nclass PyClass : public Class, public py::trampoline_self_life_support {\npublic:\n    std::unique_ptr<Class> clone() const override {\n        PYBIND11_OVERRIDE_PURE(std::unique_ptr<Class>, Class, clone);\n    }\n\n    int foo() const override { PYBIND11_OVERRIDE_PURE(int, Class, foo); }\n};\n\n} // namespace class_sh_trampoline_unique_ptr\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(class_sh_trampoline_unique_ptr, m) {\n    using namespace pybind11_tests::class_sh_trampoline_unique_ptr;\n\n    py::classh<Class, PyClass>(m, \"Class\")\n        .def(py::init<>())\n        .def(\"set_val\", &Class::setVal)\n        .def(\"get_val\", &Class::getVal)\n        .def(\"clone\", &Class::clone)\n        .def(\"foo\", &Class::foo);\n\n    m.def(\"clone\", [](const Class &obj) { return obj.clone(); });\n    m.def(\"clone_and_foo\", [](const Class &obj) { return obj.clone()->foo(); });\n}\n"
  },
  {
    "path": "tests/test_class_sh_trampoline_unique_ptr.py",
    "content": "from __future__ import annotations\n\nimport pybind11_tests.class_sh_trampoline_unique_ptr as m\n\n\nclass MyClass(m.Class):\n    def foo(self):\n        return 10 + self.get_val()\n\n    def clone(self):\n        cloned = MyClass()\n        cloned.set_val(self.get_val() + 3)\n        return cloned\n\n\ndef test_m_clone():\n    obj = MyClass()\n    while True:\n        obj.set_val(5)\n        obj = m.clone(obj)\n        assert obj.get_val() == 5 + 3\n        assert obj.foo() == 10 + 5 + 3\n        return  # Comment out for manual leak checking (use `top` command).\n\n\ndef test_m_clone_and_foo():\n    obj = MyClass()\n    obj.set_val(7)\n    while True:\n        assert m.clone_and_foo(obj) == 10 + 7 + 3\n        return  # Comment out for manual leak checking (use `top` command).\n"
  },
  {
    "path": "tests/test_class_sh_unique_ptr_custom_deleter.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_unique_ptr_custom_deleter {\n\n// Reduced from a PyCLIF use case in the wild by @wangxf123456.\nclass Pet {\npublic:\n    using Ptr = std::unique_ptr<Pet, std::function<void(Pet *)>>;\n\n    std::string name;\n\n    static Ptr New(const std::string &name) {\n        return Ptr(new Pet(name), std::default_delete<Pet>());\n    }\n\nprivate:\n    explicit Pet(const std::string &name) : name(name) {}\n};\n\nTEST_SUBMODULE(class_sh_unique_ptr_custom_deleter, m) {\n    py::classh<Pet>(m, \"Pet\").def_readwrite(\"name\", &Pet::name);\n\n    m.def(\"create\", &Pet::New);\n}\n\n} // namespace class_sh_unique_ptr_custom_deleter\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_class_sh_unique_ptr_custom_deleter.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import class_sh_unique_ptr_custom_deleter as m\n\n\ndef test_create():\n    pet = m.create(\"abc\")\n    assert pet.name == \"abc\"\n"
  },
  {
    "path": "tests/test_class_sh_unique_ptr_member.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_unique_ptr_member {\n\nclass pointee { // NOT copyable.\npublic:\n    pointee() = default;\n\n    int get_int() const { return 213; }\n\n    pointee(const pointee &) = delete;\n    pointee(pointee &&) = delete;\n    pointee &operator=(const pointee &) = delete;\n    pointee &operator=(pointee &&) = delete;\n};\n\ninline std::unique_ptr<pointee> make_unique_pointee() {\n    return std::unique_ptr<pointee>(new pointee);\n}\n\nclass ptr_owner {\npublic:\n    explicit ptr_owner(std::unique_ptr<pointee> ptr) : ptr_(std::move(ptr)) {}\n\n    bool is_owner() const { return bool(ptr_); }\n\n    std::unique_ptr<pointee> give_up_ownership_via_unique_ptr() { return std::move(ptr_); }\n    std::shared_ptr<pointee> give_up_ownership_via_shared_ptr() { return std::move(ptr_); }\n\nprivate:\n    std::unique_ptr<pointee> ptr_;\n};\n\nTEST_SUBMODULE(class_sh_unique_ptr_member, m) {\n    py::classh<pointee>(m, \"pointee\").def(py::init<>()).def(\"get_int\", &pointee::get_int);\n\n    m.def(\"make_unique_pointee\", make_unique_pointee);\n\n    py::class_<ptr_owner>(m, \"ptr_owner\")\n        .def(py::init<std::unique_ptr<pointee>>(), py::arg(\"ptr\"))\n        .def(\"is_owner\", &ptr_owner::is_owner)\n        .def(\"give_up_ownership_via_unique_ptr\", &ptr_owner::give_up_ownership_via_unique_ptr)\n        .def(\"give_up_ownership_via_shared_ptr\", &ptr_owner::give_up_ownership_via_shared_ptr);\n}\n\n} // namespace class_sh_unique_ptr_member\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_class_sh_unique_ptr_member.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_unique_ptr_member as m\n\n\ndef test_make_unique_pointee():\n    obj = m.make_unique_pointee()\n    assert obj.get_int() == 213\n\n\n@pytest.mark.parametrize(\n    \"give_up_ownership_via\",\n    [\"give_up_ownership_via_unique_ptr\", \"give_up_ownership_via_shared_ptr\"],\n)\ndef test_pointee_and_ptr_owner(give_up_ownership_via):\n    obj = m.pointee()\n    assert obj.get_int() == 213\n    owner = m.ptr_owner(obj)\n    with pytest.raises(ValueError, match=\"Python instance was disowned\"):\n        obj.get_int()\n    assert owner.is_owner()\n    reclaimed = getattr(owner, give_up_ownership_via)()\n    assert not owner.is_owner()\n    assert reclaimed.get_int() == 213\n"
  },
  {
    "path": "tests/test_class_sh_virtual_py_cpp_mix.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace class_sh_virtual_py_cpp_mix {\n\nclass Base {\npublic:\n    virtual ~Base() = default;\n    virtual int get() const { return 101; }\n\n    // Some compilers complain about implicitly defined versions of some of the following:\n    Base() = default;\n    Base(const Base &) = default;\n};\n\nclass CppDerivedPlain : public Base {\npublic:\n    int get() const override { return 202; }\n};\n\nclass CppDerived : public Base {\npublic:\n    int get() const override { return 212; }\n};\n\nint get_from_cpp_plainc_ptr(const Base *b) { return b->get() + 4000; }\n\nint get_from_cpp_unique_ptr(std::unique_ptr<Base> b) { return b->get() + 5000; }\n\nstruct BaseVirtualOverrider : Base, py::trampoline_self_life_support {\n    using Base::Base;\n\n    int get() const override { PYBIND11_OVERRIDE(int, Base, get); }\n};\n\nstruct CppDerivedVirtualOverrider : CppDerived, py::trampoline_self_life_support {\n    using CppDerived::CppDerived;\n\n    int get() const override { PYBIND11_OVERRIDE(int, CppDerived, get); }\n};\n\n} // namespace class_sh_virtual_py_cpp_mix\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::class_sh_virtual_py_cpp_mix;\n\nTEST_SUBMODULE(class_sh_virtual_py_cpp_mix, m) {\n    py::classh<Base, BaseVirtualOverrider>(m, \"Base\").def(py::init<>()).def(\"get\", &Base::get);\n\n    py::classh<CppDerivedPlain, Base>(m, \"CppDerivedPlain\").def(py::init<>());\n\n    py::classh<CppDerived, Base, CppDerivedVirtualOverrider>(m, \"CppDerived\").def(py::init<>());\n\n    m.def(\"get_from_cpp_plainc_ptr\", get_from_cpp_plainc_ptr, py::arg(\"b\"));\n    m.def(\"get_from_cpp_unique_ptr\", get_from_cpp_unique_ptr, py::arg(\"b\"));\n}\n"
  },
  {
    "path": "tests/test_class_sh_virtual_py_cpp_mix.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import class_sh_virtual_py_cpp_mix as m\n\n\nclass PyBase(m.Base):  # Avoiding name PyDerived, for more systematic naming.\n    def __init__(self):\n        m.Base.__init__(self)\n\n    def get(self):\n        return 323\n\n\nclass PyCppDerived(m.CppDerived):\n    def __init__(self):\n        m.CppDerived.__init__(self)\n\n    def get(self):\n        return 434\n\n\n@pytest.mark.parametrize(\n    (\"ctor\", \"expected\"),\n    [\n        (m.Base, 101),\n        (PyBase, 323),\n        (m.CppDerivedPlain, 202),\n        (m.CppDerived, 212),\n        (PyCppDerived, 434),\n    ],\n)\ndef test_base_get(ctor, expected):\n    obj = ctor()\n    assert obj.get() == expected\n\n\n@pytest.mark.parametrize(\n    (\"ctor\", \"expected\"),\n    [\n        (m.Base, 4101),\n        (PyBase, 4323),\n        (m.CppDerivedPlain, 4202),\n        (m.CppDerived, 4212),\n        (PyCppDerived, 4434),\n    ],\n)\ndef test_get_from_cpp_plainc_ptr(ctor, expected):\n    obj = ctor()\n    assert m.get_from_cpp_plainc_ptr(obj) == expected\n\n\n@pytest.mark.parametrize(\n    (\"ctor\", \"expected\"),\n    [\n        (m.Base, 5101),\n        (PyBase, 5323),\n        (m.CppDerivedPlain, 5202),\n        (m.CppDerived, 5212),\n        (PyCppDerived, 5434),\n    ],\n)\ndef test_get_from_cpp_unique_ptr(ctor, expected):\n    obj = ctor()\n    assert m.get_from_cpp_unique_ptr(obj) == expected\n"
  },
  {
    "path": "tests/test_cmake_build/CMakeLists.txt",
    "content": "add_custom_target(test_cmake_build)\n\nfunction(pybind11_add_build_test name)\n  cmake_parse_arguments(ARG \"INSTALL\" \"\" \"\" ${ARGN})\n\n  set(build_options \"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}\")\n\n  list(APPEND build_options \"-DPYBIND11_FINDPYTHON=${PYBIND11_FINDPYTHON}\")\n  if(PYBIND11_FINDPYTHON)\n    if(DEFINED Python_ROOT_DIR)\n      list(APPEND build_options \"-DPython_ROOT_DIR=${Python_ROOT_DIR}\")\n    endif()\n\n    list(APPEND build_options \"-DPython_EXECUTABLE=${Python_EXECUTABLE}\")\n  else()\n    list(APPEND build_options \"-DPYTHON_EXECUTABLE=${PYTHON_EXECUTABLE}\")\n  endif()\n\n  if(DEFINED CMAKE_CXX_STANDARD)\n    list(APPEND build_options \"-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}\")\n  endif()\n\n  if(NOT ARG_INSTALL)\n    list(APPEND build_options \"-Dpybind11_SOURCE_DIR=${pybind11_SOURCE_DIR}\")\n  else()\n    list(APPEND build_options \"-DCMAKE_PREFIX_PATH=${pybind11_BINARY_DIR}/mock_install\")\n  endif()\n\n  add_custom_target(\n    test_build_${name}\n    ${CMAKE_CTEST_COMMAND}\n    --build-and-test\n    \"${CMAKE_CURRENT_SOURCE_DIR}/${name}\"\n    \"${CMAKE_CURRENT_BINARY_DIR}/${name}\"\n    --build-config\n    Release\n    --build-noclean\n    --build-generator\n    ${CMAKE_GENERATOR}\n    $<$<BOOL:${CMAKE_GENERATOR_PLATFORM}>:--build-generator-platform>\n    ${CMAKE_GENERATOR_PLATFORM}\n    --build-makeprogram\n    ${CMAKE_MAKE_PROGRAM}\n    --build-target\n    check_${name}\n    --build-options\n    ${build_options})\n  if(ARG_INSTALL)\n    add_dependencies(test_build_${name} mock_install)\n  endif()\n  add_dependencies(test_cmake_build test_build_${name})\nendfunction()\n\nif(PYBIND11_TEST_SMART_HOLDER)\n  add_compile_definitions(\n    -DPYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE)\nendif()\n\npossibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)\n\npybind11_add_build_test(subdirectory_function)\npybind11_add_build_test(subdirectory_target)\nif(\"${PYTHON_MODULE_EXTENSION}\" MATCHES \"pypy\"\n   OR \"${Python_INTERPRETER_ID}\" STREQUAL \"PyPy\"\n   OR \"${PYTHON_MODULE_EXTENSION}\" MATCHES \"graalpy\")\n  message(STATUS \"Skipping embed test on PyPy or GraalPy\")\nelse()\n  pybind11_add_build_test(subdirectory_embed)\nendif()\n\nif(PYBIND11_INSTALL)\n  add_custom_target(\n    mock_install ${CMAKE_COMMAND} \"-DCMAKE_INSTALL_PREFIX=${pybind11_BINARY_DIR}/mock_install\" -P\n                 \"${pybind11_BINARY_DIR}/cmake_install.cmake\")\n\n  if(NOT \"${PYTHON_MODULE_EXTENSION}\" MATCHES \"graalpy\")\n    pybind11_add_build_test(installed_function INSTALL)\n  endif()\n  pybind11_add_build_test(installed_target INSTALL)\n  if(NOT\n     (\"${PYTHON_MODULE_EXTENSION}\" MATCHES \"pypy\"\n      OR \"${Python_INTERPRETER_ID}\" STREQUAL \"PyPy\"\n      OR \"${PYTHON_MODULE_EXTENSION}\" MATCHES \"graalpy\"))\n    pybind11_add_build_test(installed_embed INSTALL)\n  endif()\nendif()\n\nadd_dependencies(check test_cmake_build)\n\nadd_subdirectory(subdirectory_target EXCLUDE_FROM_ALL)\nadd_subdirectory(subdirectory_embed EXCLUDE_FROM_ALL)\n"
  },
  {
    "path": "tests/test_cmake_build/embed.cpp",
    "content": "#include <pybind11/embed.h>\nnamespace py = pybind11;\n\nPYBIND11_EMBEDDED_MODULE(test_cmake_build, m) {\n    m.def(\"add\", [](int i, int j) { return i + j; });\n}\n\nint main(int argc, char *argv[]) {\n    if (argc != 2) {\n        throw std::runtime_error(\"Expected test.py file as the first argument\");\n    }\n    auto *test_py_file = argv[1];\n\n    py::scoped_interpreter guard{};\n\n    auto m = py::module_::import(\"test_cmake_build\");\n    if (m.attr(\"add\")(1, 2).cast<int>() != 3) {\n        throw std::runtime_error(\"embed.cpp failed\");\n    }\n\n    py::module_::import(\"sys\").attr(\"argv\") = py::make_tuple(\"test.py\", \"embed.cpp\");\n    py::eval_file(test_py_file, py::globals());\n}\n"
  },
  {
    "path": "tests/test_cmake_build/installed_embed/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_installed_embed CXX)\n\nfind_package(pybind11 CONFIG REQUIRED)\nmessage(STATUS \"Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}\")\n\nadd_executable(test_installed_embed ../embed.cpp)\ntarget_link_libraries(test_installed_embed PRIVATE pybind11::embed)\nset_target_properties(test_installed_embed PROPERTIES OUTPUT_NAME test_cmake_build)\n\n# Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::embed).\n# This may be needed to resolve header conflicts, e.g. between Python release and debug headers.\nset_target_properties(test_installed_embed PROPERTIES NO_SYSTEM_FROM_IMPORTED ON)\n\nadd_custom_target(\n  check_installed_embed\n  $<TARGET_FILE:test_installed_embed> ${PROJECT_SOURCE_DIR}/../test.py\n  DEPENDS test_installed_embed)\n"
  },
  {
    "path": "tests/test_cmake_build/installed_function/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_installed_function CXX)\n\nfind_package(pybind11 CONFIG REQUIRED)\nmessage(\n  STATUS \"Found pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}: ${pybind11_INCLUDE_DIRS}\")\n\npybind11_add_module(test_installed_function SHARED NO_EXTRAS ../main.cpp)\nset_target_properties(test_installed_function PROPERTIES OUTPUT_NAME test_cmake_build)\n\nif(DEFINED Python_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${Python_EXECUTABLE}\")\nelseif(DEFINED PYTHON_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nelse()\n  message(FATAL_ERROR \"No Python executable defined (should not be possible at this stage)\")\nendif()\n\nadd_custom_target(\n  check_installed_function\n  ${CMAKE_COMMAND}\n  -E\n  env\n  PYTHONPATH=$<TARGET_FILE_DIR:test_installed_function>\n  ${_Python_EXECUTABLE}\n  ${PROJECT_SOURCE_DIR}/../test.py\n  ${PROJECT_NAME}\n  DEPENDS test_installed_function)\n"
  },
  {
    "path": "tests/test_cmake_build/installed_target/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_installed_target CXX)\n\nfind_package(pybind11 CONFIG REQUIRED)\nmessage(STATUS \"Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}\")\n\nadd_library(test_installed_target MODULE ../main.cpp)\n\ntarget_link_libraries(test_installed_target PRIVATE pybind11::module)\nset_target_properties(test_installed_target PROPERTIES OUTPUT_NAME test_cmake_build)\n\n# Make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib\npybind11_extension(test_installed_target)\n\n# Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::module).\n# This may be needed to resolve header conflicts, e.g. between Python release and debug headers.\nset_target_properties(test_installed_target PROPERTIES NO_SYSTEM_FROM_IMPORTED ON)\n\nif(DEFINED Python_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${Python_EXECUTABLE}\")\nelseif(DEFINED PYTHON_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nelse()\n  message(FATAL_ERROR \"No Python executable defined (should not be possible at this stage)\")\nendif()\n\nadd_custom_target(\n  check_installed_target\n  ${CMAKE_COMMAND}\n  -E\n  env\n  PYTHONPATH=$<TARGET_FILE_DIR:test_installed_target>\n  ${_Python_EXECUTABLE}\n  ${PROJECT_SOURCE_DIR}/../test.py\n  ${PROJECT_NAME}\n  DEPENDS test_installed_target)\n"
  },
  {
    "path": "tests/test_cmake_build/main.cpp",
    "content": "#include <pybind11/pybind11.h>\nnamespace py = pybind11;\n\nPYBIND11_MODULE(test_cmake_build, m, py::mod_gil_not_used()) {\n    m.def(\"add\", [](int i, int j) { return i + j; });\n}\n"
  },
  {
    "path": "tests/test_cmake_build/subdirectory_embed/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_subdirectory_embed CXX)\n\nset(PYBIND11_INSTALL\n    ON\n    CACHE BOOL \"\")\nset(PYBIND11_EXPORT_NAME test_export)\n\n# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests\n# (makes transition easier while we support both modes).\nif(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)\n  set(Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nendif()\n\nadd_subdirectory(\"${pybind11_SOURCE_DIR}\" pybind11)\n\n# Test basic target functionality\nadd_executable(test_subdirectory_embed ../embed.cpp)\ntarget_link_libraries(test_subdirectory_embed PRIVATE pybind11::embed)\nset_target_properties(test_subdirectory_embed PROPERTIES OUTPUT_NAME test_cmake_build)\n\nadd_custom_target(\n  check_subdirectory_embed\n  $<TARGET_FILE:test_subdirectory_embed> \"${PROJECT_SOURCE_DIR}/../test.py\"\n  DEPENDS test_subdirectory_embed)\n\n# Test custom export group -- PYBIND11_EXPORT_NAME\nadd_library(test_with_catch_lib ../embed.cpp)\ntarget_link_libraries(test_with_catch_lib PRIVATE pybind11::embed)\n\ninstall(\n  TARGETS test_with_catch_lib\n  EXPORT test_export\n  ARCHIVE DESTINATION bin\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION lib)\ninstall(EXPORT test_export DESTINATION lib/cmake/test_export/test_export-Targets.cmake)\n"
  },
  {
    "path": "tests/test_cmake_build/subdirectory_function/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_subdirectory_function CXX)\n\n# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests\n# (makes transition easier while we support both modes).\nif(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)\n  set(Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nendif()\n\nadd_subdirectory(\"${pybind11_SOURCE_DIR}\" pybind11)\npybind11_add_module(test_subdirectory_function ../main.cpp)\nset_target_properties(test_subdirectory_function PROPERTIES OUTPUT_NAME test_cmake_build)\n\nif(DEFINED Python_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${Python_EXECUTABLE}\")\nelseif(DEFINED PYTHON_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nelse()\n  message(FATAL_ERROR \"No Python executable defined (should not be possible at this stage)\")\nendif()\n\nadd_custom_target(\n  check_subdirectory_function\n  ${CMAKE_COMMAND}\n  -E\n  env\n  PYTHONPATH=$<TARGET_FILE_DIR:test_subdirectory_function>\n  ${_Python_EXECUTABLE}\n  ${PROJECT_SOURCE_DIR}/../test.py\n  ${PROJECT_NAME}\n  DEPENDS test_subdirectory_function)\n"
  },
  {
    "path": "tests/test_cmake_build/subdirectory_target/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nproject(test_subdirectory_target CXX)\n\n# Allow PYTHON_EXECUTABLE if in FINDPYTHON mode and building pybind11's tests\n# (makes transition easier while we support both modes).\nif(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE)\n  set(Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nendif()\n\nadd_subdirectory(\"${pybind11_SOURCE_DIR}\" pybind11)\n\nadd_library(test_subdirectory_target MODULE ../main.cpp)\nset_target_properties(test_subdirectory_target PROPERTIES OUTPUT_NAME test_cmake_build)\n\ntarget_link_libraries(test_subdirectory_target PRIVATE pybind11::module)\n\n# Make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib\npybind11_extension(test_subdirectory_target)\n\nif(DEFINED Python_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${Python_EXECUTABLE}\")\nelseif(DEFINED PYTHON_EXECUTABLE)\n  set(_Python_EXECUTABLE \"${PYTHON_EXECUTABLE}\")\nelse()\n  message(FATAL_ERROR \"No Python executable defined (should not be possible at this stage)\")\nendif()\n\nadd_custom_target(\n  check_subdirectory_target\n  ${CMAKE_COMMAND}\n  -E\n  env\n  PYTHONPATH=$<TARGET_FILE_DIR:test_subdirectory_target>\n  ${_Python_EXECUTABLE}\n  ${PROJECT_SOURCE_DIR}/../test.py\n  ${PROJECT_NAME}\n  DEPENDS test_subdirectory_target)\n"
  },
  {
    "path": "tests/test_cmake_build/test.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport test_cmake_build\n\nassert isinstance(__file__, str)  # Test this is properly set\n\nassert test_cmake_build.add(1, 2) == 3\nprint(f\"{sys.argv[1]} imports, runs, and adds: 1 + 2 = 3\")\n"
  },
  {
    "path": "tests/test_const_name.cpp",
    "content": "// Copyright (c) 2021 The Pybind Development Team.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11_tests.h\"\n\n// IUT = Implementation Under Test\n#define CONST_NAME_TESTS(TEST_FUNC, IUT)                                                          \\\n    std::string TEST_FUNC(int selector) {                                                         \\\n        switch (selector) {                                                                       \\\n            case 0:                                                                               \\\n                return IUT(\"\").text;                                                              \\\n            case 1:                                                                               \\\n                return IUT(\"A\").text;                                                             \\\n            case 2:                                                                               \\\n                return IUT(\"Bd\").text;                                                            \\\n            case 3:                                                                               \\\n                return IUT(\"Cef\").text;                                                           \\\n            case 4:                                                                               \\\n                return IUT<int>().text; /*NOLINT(bugprone-macro-parentheses)*/                    \\\n            case 5:                                                                               \\\n                return IUT<std::string>().text; /*NOLINT(bugprone-macro-parentheses)*/            \\\n            case 6:                                                                               \\\n                return IUT<true>(\"T1\", \"T2\").text; /*NOLINT(bugprone-macro-parentheses)*/         \\\n            case 7:                                                                               \\\n                return IUT<false>(\"U1\", \"U2\").text; /*NOLINT(bugprone-macro-parentheses)*/        \\\n            case 8:                                                                               \\\n                /*NOLINTNEXTLINE(bugprone-macro-parentheses)*/                                    \\\n                return IUT<true>(IUT(\"D1\"), IUT(\"D2\")).text;                                      \\\n            case 9:                                                                               \\\n                /*NOLINTNEXTLINE(bugprone-macro-parentheses)*/                                    \\\n                return IUT<false>(IUT(\"E1\"), IUT(\"E2\")).text;                                     \\\n            case 10:                                                                              \\\n                return IUT(\"KeepAtEnd\").text;                                                     \\\n            default:                                                                              \\\n                break;                                                                            \\\n        }                                                                                         \\\n        throw std::runtime_error(\"Invalid selector value.\");                                      \\\n    }\n\nCONST_NAME_TESTS(const_name_tests, py::detail::const_name)\n\n#ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY\nCONST_NAME_TESTS(underscore_tests, py::detail::_)\n#endif\n\nTEST_SUBMODULE(const_name, m) {\n    m.def(\"const_name_tests\", const_name_tests);\n\n#if defined(PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY)\n    m.def(\"underscore_tests\", underscore_tests);\n#else\n    m.attr(\"underscore_tests\") = \"PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY not defined.\";\n#endif\n}\n"
  },
  {
    "path": "tests/test_const_name.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import const_name as m\n\n\n@pytest.mark.parametrize(\"func\", [m.const_name_tests, m.underscore_tests])\n@pytest.mark.parametrize(\n    (\"selector\", \"expected\"),\n    enumerate(\n        (\n            \"\",\n            \"A\",\n            \"Bd\",\n            \"Cef\",\n            \"%\",\n            \"%\",\n            \"T1\",\n            \"U2\",\n            \"D1\",\n            \"E2\",\n            \"KeepAtEnd\",\n        )\n    ),\n)\ndef test_const_name(func, selector, expected):\n    if isinstance(func, str):\n        pytest.skip(func)\n    text = func(selector)\n    assert text == expected\n"
  },
  {
    "path": "tests/test_constants_and_functions.cpp",
    "content": "/*\n    tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw\n    byte strings\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nenum MyEnum { EFirstEntry = 1, ESecondEntry };\n\nstd::string test_function1() { return \"test_function()\"; }\n\nstd::string test_function2(MyEnum k) { return \"test_function(enum=\" + std::to_string(k) + \")\"; }\n\nstd::string test_function3(int i) { return \"test_function(\" + std::to_string(i) + \")\"; }\n\npy::str test_function4() { return \"test_function()\"; }\npy::str test_function4(char *) { return \"test_function(char *)\"; }\npy::str test_function4(int, float) { return \"test_function(int, float)\"; }\npy::str test_function4(float, int) { return \"test_function(float, int)\"; }\n\npy::bytes return_bytes() {\n    const char *data = \"\\x01\\x00\\x02\\x00\";\n    return std::string(data, 4);\n}\n\nstd::string print_bytes(const py::bytes &bytes) {\n    std::string ret = \"bytes[\";\n    const auto value = static_cast<std::string>(bytes);\n    for (char c : value) {\n        ret += std::to_string(static_cast<int>(c)) + ' ';\n    }\n    ret.back() = ']';\n    return ret;\n}\n\n// Test that we properly handle C++17 exception specifiers (which are part of the function\n// signature in C++17).  These should all still work before C++17, but don't affect the function\n// signature.\nnamespace test_exc_sp {\n// [workaround(intel)] Unable to use noexcept instead of noexcept(true)\n// Make the f1 test basically the same as the f2 test in C++17 mode for the Intel compiler as\n// it fails to compile with a plain noexcept (tested with icc (ICC) 2021.1 Beta 20200827).\n#if defined(__INTEL_COMPILER) && defined(PYBIND11_CPP17)\nint f1(int x) noexcept(true) { return x + 1; }\n#else\nint f1(int x) noexcept { return x + 1; }\n#endif\nint f2(int x) noexcept(true) { return x + 2; }\nint f3(int x) noexcept(false) { return x + 3; }\nPYBIND11_WARNING_PUSH\nPYBIND11_WARNING_DISABLE_GCC(\"-Wdeprecated\")\n#if defined(__clang_major__) && __clang_major__ >= 5\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wdeprecated-dynamic-exception-spec\")\n#else\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wdeprecated\")\n#endif\n// NOLINTNEXTLINE(modernize-use-noexcept)\nint f4(int x) throw() { return x + 4; } // Deprecated equivalent to noexcept(true)\nPYBIND11_WARNING_POP\nstruct C {\n    int m1(int x) noexcept { return x - 1; }\n    int m2(int x) const noexcept { return x - 2; }\n    int m3(int x) noexcept(true) { return x - 3; }\n    int m4(int x) const noexcept(true) { return x - 4; }\n    int m5(int x) noexcept(false) { return x - 5; }\n    int m6(int x) const noexcept(false) { return x - 6; }\n    PYBIND11_WARNING_PUSH\n    PYBIND11_WARNING_DISABLE_GCC(\"-Wdeprecated\")\n    PYBIND11_WARNING_DISABLE_CLANG(\"-Wdeprecated\")\n    // NOLINTNEXTLINE(modernize-use-noexcept)\n    int m7(int x) throw() { return x - 7; }\n    // NOLINTNEXTLINE(modernize-use-noexcept)\n    int m8(int x) const throw() { return x - 8; }\n    PYBIND11_WARNING_POP\n};\n} // namespace test_exc_sp\n\nTEST_SUBMODULE(constants_and_functions, m) {\n    // test_constants\n    m.attr(\"some_constant\") = py::int_(14);\n\n    // test_function_overloading\n    m.def(\"test_function\", &test_function1);\n    m.def(\"test_function\", &test_function2);\n    m.def(\"test_function\", &test_function3);\n\n#if defined(PYBIND11_OVERLOAD_CAST)\n    m.def(\"test_function\", py::overload_cast<>(&test_function4));\n    m.def(\"test_function\", py::overload_cast<char *>(&test_function4));\n    m.def(\"test_function\", py::overload_cast<int, float>(&test_function4));\n    m.def(\"test_function\", py::overload_cast<float, int>(&test_function4));\n#else\n    m.def(\"test_function\", static_cast<py::str (*)()>(&test_function4));\n    m.def(\"test_function\", static_cast<py::str (*)(char *)>(&test_function4));\n    m.def(\"test_function\", static_cast<py::str (*)(int, float)>(&test_function4));\n    m.def(\"test_function\", static_cast<py::str (*)(float, int)>(&test_function4));\n#endif\n\n    py::enum_<MyEnum>(m, \"MyEnum\")\n        .value(\"EFirstEntry\", EFirstEntry)\n        .value(\"ESecondEntry\", ESecondEntry)\n        .export_values();\n\n    // test_bytes\n    m.def(\"return_bytes\", &return_bytes);\n    m.def(\"print_bytes\", &print_bytes);\n\n    // test_exception_specifiers\n    using namespace test_exc_sp;\n    py::class_<C>(m, \"C\")\n        .def(py::init<>())\n        .def(\"m1\", &C::m1)\n        .def(\"m2\", &C::m2)\n        .def(\"m3\", &C::m3)\n        .def(\"m4\", &C::m4)\n        .def(\"m5\", &C::m5)\n        .def(\"m6\", &C::m6)\n        .def(\"m7\", &C::m7)\n        .def(\"m8\", &C::m8);\n    m.def(\"f1\", f1);\n    m.def(\"f2\", f2);\n\n    PYBIND11_WARNING_PUSH\n    PYBIND11_WARNING_DISABLE_INTEL(878) // incompatible exception specifications\n    m.def(\"f3\", f3);\n    PYBIND11_WARNING_POP\n\n    m.def(\"f4\", f4);\n\n    // test_function_record_leaks\n    m.def(\"register_large_capture_with_invalid_arguments\", [](py::module_ m) {\n        // This should always be enough to trigger the alternative branch\n        // where `sizeof(capture) > sizeof(rec->data)`\n        uint64_t capture[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n#if defined(__GNUC__) && __GNUC__ == 4 // CentOS7\n        py::detail::silence_unused_warnings(capture);\n#endif\n        m.def(\n            \"should_raise\", [capture](int) { return capture[9] + 33; }, py::kw_only(), py::arg());\n    });\n    m.def(\"register_with_raising_repr\", [](py::module_ m, const py::object &default_value) {\n        m.def(\n            \"should_raise\",\n            [](int, int, const py::object &) { return 42; },\n            \"some docstring\",\n            py::arg_v(\"x\", 42),\n            py::arg_v(\"y\", 42, \"<the answer>\"),\n            py::arg_v(\"z\", default_value));\n    });\n\n    // test noexcept(true) lambda (#4565)\n    m.def(\"l1\", []() noexcept(true) { return 0; });\n}\n"
  },
  {
    "path": "tests/test_constants_and_functions.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nm = pytest.importorskip(\"pybind11_tests.constants_and_functions\")\n\n\ndef test_constants():\n    assert m.some_constant == 14\n\n\ndef test_function_overloading():\n    assert m.test_function() == \"test_function()\"\n    assert m.test_function(7) == \"test_function(7)\"\n    assert m.test_function(m.MyEnum.EFirstEntry) == \"test_function(enum=1)\"\n    assert m.test_function(m.MyEnum.ESecondEntry) == \"test_function(enum=2)\"\n\n    assert m.test_function() == \"test_function()\"\n    assert m.test_function(\"abcd\") == \"test_function(char *)\"\n    assert m.test_function(1, 1.0) == \"test_function(int, float)\"\n    assert m.test_function(1, 1.0) == \"test_function(int, float)\"\n    assert m.test_function(2.0, 2) == \"test_function(float, int)\"\n\n\ndef test_bytes():\n    assert m.print_bytes(m.return_bytes()) == \"bytes[1 0 2 0]\"\n\n\ndef test_exception_specifiers():\n    c = m.C()\n    assert c.m1(2) == 1\n    assert c.m2(3) == 1\n    assert c.m3(5) == 2\n    assert c.m4(7) == 3\n    assert c.m5(10) == 5\n    assert c.m6(14) == 8\n    assert c.m7(20) == 13\n    assert c.m8(29) == 21\n\n    assert m.f1(33) == 34\n    assert m.f2(53) == 55\n    assert m.f3(86) == 89\n    assert m.f4(140) == 144\n\n\ndef test_function_record_leaks():\n    class RaisingRepr:\n        def __repr__(self):\n            raise RuntimeError(\"Surprise!\")\n\n    with pytest.raises(RuntimeError):\n        m.register_large_capture_with_invalid_arguments(m)\n    with pytest.raises(RuntimeError):\n        m.register_with_raising_repr(m, RaisingRepr())\n\n\ndef test_noexcept_lambda():\n    assert m.l1() == 0\n"
  },
  {
    "path": "tests/test_copy_move.cpp",
    "content": "/*\n    tests/test_copy_move_policies.cpp -- 'copy' and 'move' return value policies\n                                         and related tests\n\n    Copyright (c) 2016 Ben North <ben@redfrontdoor.org>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <type_traits>\n\ntemplate <typename derived>\nstruct empty {\n    static const derived &get_one() { return instance_; }\n    static derived instance_;\n\nprivate:\n    empty() = default;\n    friend derived;\n};\n\nstruct lacking_copy_ctor : public empty<lacking_copy_ctor> {\n    lacking_copy_ctor() = default;\n    lacking_copy_ctor(const lacking_copy_ctor &other) = delete;\n};\n\ntemplate <>\nlacking_copy_ctor empty<lacking_copy_ctor>::instance_ = {};\n\nstruct lacking_move_ctor : public empty<lacking_move_ctor> {\n    lacking_move_ctor() = default;\n    lacking_move_ctor(const lacking_move_ctor &other) = delete;\n    lacking_move_ctor(lacking_move_ctor &&other) = delete;\n};\n\ntemplate <>\nlacking_move_ctor empty<lacking_move_ctor>::instance_ = {};\n\n/* Custom type caster move/copy test classes */\nclass MoveOnlyInt {\npublic:\n    MoveOnlyInt() { print_default_created(this); }\n    explicit MoveOnlyInt(int v) : value{v} { print_created(this, value); }\n    MoveOnlyInt(MoveOnlyInt &&m) noexcept {\n        print_move_created(this, m.value);\n        std::swap(value, m.value);\n    }\n    MoveOnlyInt &operator=(MoveOnlyInt &&m) noexcept {\n        print_move_assigned(this, m.value);\n        std::swap(value, m.value);\n        return *this;\n    }\n    MoveOnlyInt(const MoveOnlyInt &) = delete;\n    MoveOnlyInt &operator=(const MoveOnlyInt &) = delete;\n    ~MoveOnlyInt() { print_destroyed(this); }\n\n    int value;\n};\nclass MoveOrCopyInt {\npublic:\n    MoveOrCopyInt() { print_default_created(this); }\n    explicit MoveOrCopyInt(int v) : value{v} { print_created(this, value); }\n    MoveOrCopyInt(MoveOrCopyInt &&m) noexcept {\n        print_move_created(this, m.value);\n        std::swap(value, m.value);\n    }\n    MoveOrCopyInt &operator=(MoveOrCopyInt &&m) noexcept {\n        print_move_assigned(this, m.value);\n        std::swap(value, m.value);\n        return *this;\n    }\n    MoveOrCopyInt(const MoveOrCopyInt &c) {\n        print_copy_created(this, c.value);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = c.value;\n    }\n    MoveOrCopyInt &operator=(const MoveOrCopyInt &c) {\n        print_copy_assigned(this, c.value);\n        value = c.value;\n        return *this;\n    }\n    ~MoveOrCopyInt() { print_destroyed(this); }\n\n    int value;\n};\nclass CopyOnlyInt {\npublic:\n    CopyOnlyInt() { print_default_created(this); }\n    explicit CopyOnlyInt(int v) : value{v} { print_created(this, value); }\n    CopyOnlyInt(const CopyOnlyInt &c) {\n        print_copy_created(this, c.value);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = c.value;\n    }\n    CopyOnlyInt &operator=(const CopyOnlyInt &c) {\n        print_copy_assigned(this, c.value);\n        value = c.value;\n        return *this;\n    }\n    ~CopyOnlyInt() { print_destroyed(this); }\n\n    int value;\n};\nPYBIND11_NAMESPACE_BEGIN(pybind11)\nPYBIND11_NAMESPACE_BEGIN(detail)\ntemplate <>\nstruct type_caster<MoveOnlyInt> {\n    PYBIND11_TYPE_CASTER(MoveOnlyInt, const_name(\"MoveOnlyInt\"));\n    bool load(handle src, bool) {\n        value = MoveOnlyInt(src.cast<int>());\n        return true;\n    }\n    static handle cast(const MoveOnlyInt &m, return_value_policy r, handle p) {\n        return pybind11::cast(m.value, r, p);\n    }\n};\n\ntemplate <>\nstruct type_caster<MoveOrCopyInt> {\n    PYBIND11_TYPE_CASTER(MoveOrCopyInt, const_name(\"MoveOrCopyInt\"));\n    bool load(handle src, bool) {\n        value = MoveOrCopyInt(src.cast<int>());\n        return true;\n    }\n    static handle cast(const MoveOrCopyInt &m, return_value_policy r, handle p) {\n        return pybind11::cast(m.value, r, p);\n    }\n};\n\ntemplate <>\nstruct type_caster<CopyOnlyInt> {\nprotected:\n    CopyOnlyInt value;\n\npublic:\n    static constexpr auto name = const_name(\"CopyOnlyInt\");\n    bool load(handle src, bool) {\n        value = CopyOnlyInt(src.cast<int>());\n        return true;\n    }\n    static handle cast(const CopyOnlyInt &m, return_value_policy r, handle p) {\n        return pybind11::cast(m.value, r, p);\n    }\n    static handle cast(const CopyOnlyInt *src, return_value_policy policy, handle parent) {\n        if (!src) {\n            return none().release();\n        }\n        return cast(*src, policy, parent);\n    }\n    explicit operator CopyOnlyInt *() { return &value; }\n    explicit operator CopyOnlyInt &() { return value; }\n    template <typename T>\n    using cast_op_type = pybind11::detail::cast_op_type<T>;\n};\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(pybind11)\n\nnamespace {\n\npy::object CastUnusualOpRefConstRef(const UnusualOpRef &cref) { return py::cast(cref); }\npy::object CastUnusualOpRefMovable(UnusualOpRef &&mvbl) { return py::cast(std::move(mvbl)); }\n\n} // namespace\n\nTEST_SUBMODULE(copy_move_policies, m) {\n    // test_lacking_copy_ctor\n    py::class_<lacking_copy_ctor>(m, \"lacking_copy_ctor\")\n        .def_static(\"get_one\", &lacking_copy_ctor::get_one, py::return_value_policy::copy);\n    // test_lacking_move_ctor\n    py::class_<lacking_move_ctor>(m, \"lacking_move_ctor\")\n        .def_static(\"get_one\", &lacking_move_ctor::get_one, py::return_value_policy::move);\n\n    // test_move_and_copy_casts\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    m.def(\"move_and_copy_casts\", [](const py::object &o) {\n        int r = 0;\n        r += py::cast<MoveOrCopyInt>(o).value; /* moves */\n        r += py::cast<MoveOnlyInt>(o).value;   /* moves */\n        r += py::cast<CopyOnlyInt>(o).value;   /* copies */\n        auto m1(py::cast<MoveOrCopyInt>(o));   /* moves */\n        auto m2(py::cast<MoveOnlyInt>(o));     /* moves */\n        auto m3(py::cast<CopyOnlyInt>(o));     /* copies */\n        r += m1.value + m2.value + m3.value;\n\n        return r;\n    });\n\n    // test_move_and_copy_loads\n    m.def(\"move_only\", [](MoveOnlyInt m) { return m.value; });\n    // NOLINTNEXTLINE(performance-unnecessary-value-param): we want to test copying\n    m.def(\"move_or_copy\", [](MoveOrCopyInt m) { return m.value; });\n    // NOLINTNEXTLINE(performance-unnecessary-value-param): we want to test copying\n    m.def(\"copy_only\", [](CopyOnlyInt m) { return m.value; });\n    m.def(\"move_pair\",\n          [](std::pair<MoveOnlyInt, MoveOrCopyInt> p) { return p.first.value + p.second.value; });\n    m.def(\"move_tuple\", [](std::tuple<MoveOnlyInt, MoveOrCopyInt, MoveOnlyInt> t) {\n        return std::get<0>(t).value + std::get<1>(t).value + std::get<2>(t).value;\n    });\n    m.def(\"copy_tuple\", [](std::tuple<CopyOnlyInt, CopyOnlyInt> t) {\n        return std::get<0>(t).value + std::get<1>(t).value;\n    });\n    m.def(\"move_copy_nested\",\n          [](std::pair<MoveOnlyInt,\n                       std::pair<std::tuple<MoveOrCopyInt, CopyOnlyInt, std::tuple<MoveOnlyInt>>,\n                                 MoveOrCopyInt>> x) {\n              return x.first.value + std::get<0>(x.second.first).value\n                     + std::get<1>(x.second.first).value\n                     + std::get<0>(std::get<2>(x.second.first)).value + x.second.second.value;\n          });\n    m.def(\"move_and_copy_cstats\", []() {\n        ConstructorStats::gc();\n        // Reset counts to 0 so that previous tests don't affect later ones:\n        auto &mc = ConstructorStats::get<MoveOrCopyInt>();\n        mc.move_assignments = mc.move_constructions = mc.copy_assignments = mc.copy_constructions\n            = 0;\n        auto &mo = ConstructorStats::get<MoveOnlyInt>();\n        mo.move_assignments = mo.move_constructions = mo.copy_assignments = mo.copy_constructions\n            = 0;\n        auto &co = ConstructorStats::get<CopyOnlyInt>();\n        co.move_assignments = co.move_constructions = co.copy_assignments = co.copy_constructions\n            = 0;\n        py::dict d;\n        d[\"MoveOrCopyInt\"] = py::cast(mc, py::return_value_policy::reference);\n        d[\"MoveOnlyInt\"] = py::cast(mo, py::return_value_policy::reference);\n        d[\"CopyOnlyInt\"] = py::cast(co, py::return_value_policy::reference);\n        return d;\n    });\n#ifdef PYBIND11_HAS_OPTIONAL\n    // test_move_and_copy_load_optional\n    m.attr(\"has_optional\") = true;\n    m.def(\"move_optional\", [](std::optional<MoveOnlyInt> o) { return o->value; });\n    m.def(\"move_or_copy_optional\", [](std::optional<MoveOrCopyInt> o) { return o->value; });\n    m.def(\"copy_optional\", [](std::optional<CopyOnlyInt> o) { return o->value; });\n    m.def(\"move_optional_tuple\",\n          [](std::optional<std::tuple<MoveOrCopyInt, MoveOnlyInt, CopyOnlyInt>> x) {\n              return std::get<0>(*x).value + std::get<1>(*x).value + std::get<2>(*x).value;\n          });\n#else\n    m.attr(\"has_optional\") = false;\n#endif\n\n    // #70 compilation issue if operator new is not public - simple body added\n    // but not needed on most compilers; MSVC and nvcc don't like a local\n    // struct not having a method defined when declared, since it can not be\n    // added later.\n    struct PrivateOpNew {\n        int value = 1;\n\n    private:\n        void *operator new(size_t bytes) {\n            void *ptr = std::malloc(bytes);\n            if (ptr) {\n                return ptr;\n            }\n            throw std::bad_alloc{};\n        }\n    };\n    py::class_<PrivateOpNew>(m, \"PrivateOpNew\").def_readonly(\"value\", &PrivateOpNew::value);\n    m.def(\"private_op_new_value\", []() { return PrivateOpNew(); });\n    m.def(\n        \"private_op_new_reference\",\n        []() -> const PrivateOpNew & {\n            static PrivateOpNew x{};\n            return x;\n        },\n        py::return_value_policy::reference);\n\n    // test_move_fallback\n    // #389: rvp::move should fall-through to copy on non-movable objects\n    struct MoveIssue1 {\n        int v;\n        explicit MoveIssue1(int v) : v{v} {}\n        MoveIssue1(const MoveIssue1 &c) = default;\n        MoveIssue1(MoveIssue1 &&) = delete;\n    };\n    py::class_<MoveIssue1>(m, \"MoveIssue1\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &MoveIssue1::v);\n\n    struct MoveIssue2 {\n        int v;\n        explicit MoveIssue2(int v) : v{v} {}\n        MoveIssue2(MoveIssue2 &&) = default;\n    };\n    py::class_<MoveIssue2>(m, \"MoveIssue2\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &MoveIssue2::v);\n\n    // #2742: Don't expect ownership of raw pointer to `new`ed object to be transferred with\n    // `py::return_value_policy::move`\n    m.def(\n        \"get_moveissue1\",\n        [](int i) { return std::unique_ptr<MoveIssue1>(new MoveIssue1(i)); },\n        py::return_value_policy::move);\n    m.def(\"get_moveissue2\", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);\n\n    // Make sure that cast from pytype rvalue to other pytype works\n    m.def(\"get_pytype_rvalue_castissue\", [](double i) { return py::float_(i).cast<py::int_>(); });\n\n    py::class_<UnusualOpRef>(m, \"UnusualOpRef\");\n    m.def(\"CallCastUnusualOpRefConstRef\",\n          []() { return CastUnusualOpRefConstRef(UnusualOpRef()); });\n    m.def(\"CallCastUnusualOpRefMovable\", []() { return CastUnusualOpRefMovable(UnusualOpRef()); });\n}\n\n/*\n * Rest of the file:\n * static_assert based tests for pybind11 adaptations of\n * std::is_move_constructible, std::is_copy_constructible and\n * std::is_copy_assignable (no adaptation of std::is_move_assignable).\n * Difference between pybind11 and std traits: pybind11 traits will also check\n * the contained value_types.\n */\n\nstruct NotMovable {\n    NotMovable() = default;\n    NotMovable(NotMovable const &) = default;\n    NotMovable(NotMovable &&) = delete;\n    NotMovable &operator=(NotMovable const &) = default;\n    NotMovable &operator=(NotMovable &&) = delete;\n};\nstatic_assert(!std::is_move_constructible<NotMovable>::value,\n              \"!std::is_move_constructible<NotMovable>::value\");\nstatic_assert(std::is_copy_constructible<NotMovable>::value,\n              \"std::is_copy_constructible<NotMovable>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotMovable>::value,\n              \"!pybind11::detail::is_move_constructible<NotMovable>::value\");\nstatic_assert(pybind11::detail::is_copy_constructible<NotMovable>::value,\n              \"pybind11::detail::is_copy_constructible<NotMovable>::value\");\nstatic_assert(!std::is_move_assignable<NotMovable>::value,\n              \"!std::is_move_assignable<NotMovable>::value\");\nstatic_assert(std::is_copy_assignable<NotMovable>::value,\n              \"std::is_copy_assignable<NotMovable>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotMovable>::value,\n//               \"!pybind11::detail::is_move_assignable<NotMovable>::value\");\nstatic_assert(pybind11::detail::is_copy_assignable<NotMovable>::value,\n              \"pybind11::detail::is_copy_assignable<NotMovable>::value\");\n\nstruct NotCopyable {\n    NotCopyable() = default;\n    NotCopyable(NotCopyable const &) = delete;\n    NotCopyable(NotCopyable &&) = default;\n    NotCopyable &operator=(NotCopyable const &) = delete;\n    NotCopyable &operator=(NotCopyable &&) = default;\n};\nstatic_assert(std::is_move_constructible<NotCopyable>::value,\n              \"std::is_move_constructible<NotCopyable>::value\");\nstatic_assert(!std::is_copy_constructible<NotCopyable>::value,\n              \"!std::is_copy_constructible<NotCopyable>::value\");\nstatic_assert(pybind11::detail::is_move_constructible<NotCopyable>::value,\n              \"pybind11::detail::is_move_constructible<NotCopyable>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyable>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyable>::value\");\nstatic_assert(std::is_move_assignable<NotCopyable>::value,\n              \"std::is_move_assignable<NotCopyable>::value\");\nstatic_assert(!std::is_copy_assignable<NotCopyable>::value,\n              \"!std::is_copy_assignable<NotCopyable>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyable>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyable>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyable>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyable>::value\");\n\nstruct NotCopyableNotMovable {\n    NotCopyableNotMovable() = default;\n    NotCopyableNotMovable(NotCopyableNotMovable const &) = delete;\n    NotCopyableNotMovable(NotCopyableNotMovable &&) = delete;\n    NotCopyableNotMovable &operator=(NotCopyableNotMovable const &) = delete;\n    NotCopyableNotMovable &operator=(NotCopyableNotMovable &&) = delete;\n};\nstatic_assert(!std::is_move_constructible<NotCopyableNotMovable>::value,\n              \"!std::is_move_constructible<NotCopyableNotMovable>::value\");\nstatic_assert(!std::is_copy_constructible<NotCopyableNotMovable>::value,\n              \"!std::is_copy_constructible<NotCopyableNotMovable>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovable>::value,\n              \"!pybind11::detail::is_move_constructible<NotCopyableNotMovable>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovable>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyableNotMovable>::value\");\nstatic_assert(!std::is_move_assignable<NotCopyableNotMovable>::value,\n              \"!std::is_move_assignable<NotCopyableNotMovable>::value\");\nstatic_assert(!std::is_copy_assignable<NotCopyableNotMovable>::value,\n              \"!std::is_copy_assignable<NotCopyableNotMovable>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovable>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyableNotMovable>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovable>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyableNotMovable>::value\");\n\nstruct NotMovableVector : std::vector<NotMovable> {};\nstatic_assert(std::is_move_constructible<NotMovableVector>::value,\n              \"std::is_move_constructible<NotMovableVector>::value\");\nstatic_assert(std::is_copy_constructible<NotMovableVector>::value,\n              \"std::is_copy_constructible<NotMovableVector>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotMovableVector>::value,\n              \"!pybind11::detail::is_move_constructible<NotMovableVector>::value\");\nstatic_assert(pybind11::detail::is_copy_constructible<NotMovableVector>::value,\n              \"pybind11::detail::is_copy_constructible<NotMovableVector>::value\");\nstatic_assert(std::is_move_assignable<NotMovableVector>::value,\n              \"std::is_move_assignable<NotMovableVector>::value\");\nstatic_assert(std::is_copy_assignable<NotMovableVector>::value,\n              \"std::is_copy_assignable<NotMovableVector>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotMovableVector>::value,\n//               \"!pybind11::detail::is_move_assignable<NotMovableVector>::value\");\nstatic_assert(pybind11::detail::is_copy_assignable<NotMovableVector>::value,\n              \"pybind11::detail::is_copy_assignable<NotMovableVector>::value\");\n\nstruct NotCopyableVector : std::vector<NotCopyable> {};\nstatic_assert(std::is_move_constructible<NotCopyableVector>::value,\n              \"std::is_move_constructible<NotCopyableVector>::value\");\nstatic_assert(std::is_copy_constructible<NotCopyableVector>::value,\n              \"std::is_copy_constructible<NotCopyableVector>::value\");\nstatic_assert(pybind11::detail::is_move_constructible<NotCopyableVector>::value,\n              \"pybind11::detail::is_move_constructible<NotCopyableVector>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyableVector>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyableVector>::value\");\nstatic_assert(std::is_move_assignable<NotCopyableVector>::value,\n              \"std::is_move_assignable<NotCopyableVector>::value\");\nstatic_assert(std::is_copy_assignable<NotCopyableVector>::value,\n              \"std::is_copy_assignable<NotCopyableVector>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyableVector>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyableVector>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyableVector>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyableVector>::value\");\n\nstruct NotCopyableNotMovableVector : std::vector<NotCopyableNotMovable> {};\nstatic_assert(std::is_move_constructible<NotCopyableNotMovableVector>::value,\n              \"std::is_move_constructible<NotCopyableNotMovableVector>::value\");\nstatic_assert(std::is_copy_constructible<NotCopyableNotMovableVector>::value,\n              \"std::is_copy_constructible<NotCopyableNotMovableVector>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovableVector>::value,\n              \"!pybind11::detail::is_move_constructible<NotCopyableNotMovableVector>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovableVector>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyableNotMovableVector>::value\");\nstatic_assert(std::is_move_assignable<NotCopyableNotMovableVector>::value,\n              \"std::is_move_assignable<NotCopyableNotMovableVector>::value\");\nstatic_assert(std::is_copy_assignable<NotCopyableNotMovableVector>::value,\n              \"std::is_copy_assignable<NotCopyableNotMovableVector>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovableVector>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyableNotMovableVector>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovableVector>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyableNotMovableVector>::value\");\n\nstruct NotMovableMap : std::map<int, NotMovable> {};\nstatic_assert(std::is_move_constructible<NotMovableMap>::value,\n              \"std::is_move_constructible<NotMovableMap>::value\");\nstatic_assert(std::is_copy_constructible<NotMovableMap>::value,\n              \"std::is_copy_constructible<NotMovableMap>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotMovableMap>::value,\n              \"!pybind11::detail::is_move_constructible<NotMovableMap>::value\");\nstatic_assert(pybind11::detail::is_copy_constructible<NotMovableMap>::value,\n              \"pybind11::detail::is_copy_constructible<NotMovableMap>::value\");\nstatic_assert(std::is_move_assignable<NotMovableMap>::value,\n              \"std::is_move_assignable<NotMovableMap>::value\");\nstatic_assert(std::is_copy_assignable<NotMovableMap>::value,\n              \"std::is_copy_assignable<NotMovableMap>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotMovableMap>::value,\n//               \"!pybind11::detail::is_move_assignable<NotMovableMap>::value\");\nstatic_assert(pybind11::detail::is_copy_assignable<NotMovableMap>::value,\n              \"pybind11::detail::is_copy_assignable<NotMovableMap>::value\");\n\nstruct NotCopyableMap : std::map<int, NotCopyable> {};\nstatic_assert(std::is_move_constructible<NotCopyableMap>::value,\n              \"std::is_move_constructible<NotCopyableMap>::value\");\nstatic_assert(std::is_copy_constructible<NotCopyableMap>::value,\n              \"std::is_copy_constructible<NotCopyableMap>::value\");\nstatic_assert(pybind11::detail::is_move_constructible<NotCopyableMap>::value,\n              \"pybind11::detail::is_move_constructible<NotCopyableMap>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyableMap>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyableMap>::value\");\nstatic_assert(std::is_move_assignable<NotCopyableMap>::value,\n              \"std::is_move_assignable<NotCopyableMap>::value\");\nstatic_assert(std::is_copy_assignable<NotCopyableMap>::value,\n              \"std::is_copy_assignable<NotCopyableMap>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyableMap>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyableMap>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyableMap>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyableMap>::value\");\n\nstruct NotCopyableNotMovableMap : std::map<int, NotCopyableNotMovable> {};\nstatic_assert(std::is_move_constructible<NotCopyableNotMovableMap>::value,\n              \"std::is_move_constructible<NotCopyableNotMovableMap>::value\");\nstatic_assert(std::is_copy_constructible<NotCopyableNotMovableMap>::value,\n              \"std::is_copy_constructible<NotCopyableNotMovableMap>::value\");\nstatic_assert(!pybind11::detail::is_move_constructible<NotCopyableNotMovableMap>::value,\n              \"!pybind11::detail::is_move_constructible<NotCopyableNotMovableMap>::value\");\nstatic_assert(!pybind11::detail::is_copy_constructible<NotCopyableNotMovableMap>::value,\n              \"!pybind11::detail::is_copy_constructible<NotCopyableNotMovableMap>::value\");\nstatic_assert(std::is_move_assignable<NotCopyableNotMovableMap>::value,\n              \"std::is_move_assignable<NotCopyableNotMovableMap>::value\");\nstatic_assert(std::is_copy_assignable<NotCopyableNotMovableMap>::value,\n              \"std::is_copy_assignable<NotCopyableNotMovableMap>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<NotCopyableNotMovableMap>::value,\n//               \"!pybind11::detail::is_move_assignable<NotCopyableNotMovableMap>::value\");\nstatic_assert(!pybind11::detail::is_copy_assignable<NotCopyableNotMovableMap>::value,\n              \"!pybind11::detail::is_copy_assignable<NotCopyableNotMovableMap>::value\");\n\nstruct RecursiveVector : std::vector<RecursiveVector> {};\nstatic_assert(std::is_move_constructible<RecursiveVector>::value,\n              \"std::is_move_constructible<RecursiveVector>::value\");\nstatic_assert(std::is_copy_constructible<RecursiveVector>::value,\n              \"std::is_copy_constructible<RecursiveVector>::value\");\nstatic_assert(pybind11::detail::is_move_constructible<RecursiveVector>::value,\n              \"pybind11::detail::is_move_constructible<RecursiveVector>::value\");\nstatic_assert(pybind11::detail::is_copy_constructible<RecursiveVector>::value,\n              \"pybind11::detail::is_copy_constructible<RecursiveVector>::value\");\nstatic_assert(std::is_move_assignable<RecursiveVector>::value,\n              \"std::is_move_assignable<RecursiveVector>::value\");\nstatic_assert(std::is_copy_assignable<RecursiveVector>::value,\n              \"std::is_copy_assignable<RecursiveVector>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<RecursiveVector>::value,\n//               \"!pybind11::detail::is_move_assignable<RecursiveVector>::value\");\nstatic_assert(pybind11::detail::is_copy_assignable<RecursiveVector>::value,\n              \"pybind11::detail::is_copy_assignable<RecursiveVector>::value\");\n\nstruct RecursiveMap : std::map<int, RecursiveMap> {};\nstatic_assert(std::is_move_constructible<RecursiveMap>::value,\n              \"std::is_move_constructible<RecursiveMap>::value\");\nstatic_assert(std::is_copy_constructible<RecursiveMap>::value,\n              \"std::is_copy_constructible<RecursiveMap>::value\");\nstatic_assert(pybind11::detail::is_move_constructible<RecursiveMap>::value,\n              \"pybind11::detail::is_move_constructible<RecursiveMap>::value\");\nstatic_assert(pybind11::detail::is_copy_constructible<RecursiveMap>::value,\n              \"pybind11::detail::is_copy_constructible<RecursiveMap>::value\");\nstatic_assert(std::is_move_assignable<RecursiveMap>::value,\n              \"std::is_move_assignable<RecursiveMap>::value\");\nstatic_assert(std::is_copy_assignable<RecursiveMap>::value,\n              \"std::is_copy_assignable<RecursiveMap>::value\");\n// pybind11 does not have this\n// static_assert(!pybind11::detail::is_move_assignable<RecursiveMap>::value,\n//               \"!pybind11::detail::is_move_assignable<RecursiveMap>::value\");\nstatic_assert(pybind11::detail::is_copy_assignable<RecursiveMap>::value,\n              \"pybind11::detail::is_copy_assignable<RecursiveMap>::value\");\n"
  },
  {
    "path": "tests/test_copy_move.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import copy_move_policies as m\n\n\ndef test_lacking_copy_ctor():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.lacking_copy_ctor.get_one()\n    assert \"is non-copyable!\" in str(excinfo.value)\n\n\ndef test_lacking_move_ctor():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.lacking_move_ctor.get_one()\n    assert \"is neither movable nor copyable!\" in str(excinfo.value)\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_move_and_copy_casts():\n    \"\"\"Cast some values in C++ via custom type casters and count the number of moves/copies.\"\"\"\n\n    cstats = m.move_and_copy_cstats()\n    c_m, c_mc, c_c = (\n        cstats[\"MoveOnlyInt\"],\n        cstats[\"MoveOrCopyInt\"],\n        cstats[\"CopyOnlyInt\"],\n    )\n\n    # The type move constructions/assignments below each get incremented: the move assignment comes\n    # from the type_caster load; the move construction happens when extracting that via a cast or\n    # loading into an argument.\n    assert m.move_and_copy_casts(3) == 18\n    assert c_m.copy_assignments + c_m.copy_constructions == 0\n    assert c_m.move_assignments == 2\n    assert c_m.move_constructions >= 2\n    assert c_mc.alive() == 0\n    assert c_mc.copy_assignments + c_mc.copy_constructions == 0\n    assert c_mc.move_assignments == 2\n    assert c_mc.move_constructions >= 2\n    assert c_c.alive() == 0\n    assert c_c.copy_assignments == 2\n    assert c_c.copy_constructions >= 2\n    assert c_m.alive() + c_mc.alive() + c_c.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_move_and_copy_loads():\n    \"\"\"Call some functions that load arguments via custom type casters and count the number of\n    moves/copies.\"\"\"\n\n    cstats = m.move_and_copy_cstats()\n    c_m, c_mc, c_c = (\n        cstats[\"MoveOnlyInt\"],\n        cstats[\"MoveOrCopyInt\"],\n        cstats[\"CopyOnlyInt\"],\n    )\n\n    assert m.move_only(10) == 10  # 1 move, c_m\n    assert m.move_or_copy(11) == 11  # 1 move, c_mc\n    assert m.copy_only(12) == 12  # 1 copy, c_c\n    assert m.move_pair((13, 14)) == 27  # 1 c_m move, 1 c_mc move\n    assert m.move_tuple((15, 16, 17)) == 48  # 2 c_m moves, 1 c_mc move\n    assert m.copy_tuple((18, 19)) == 37  # 2 c_c copies\n    # Direct constructions: 2 c_m moves, 2 c_mc moves, 1 c_c copy\n    # Extra moves/copies when moving pairs/tuples: 3 c_m, 3 c_mc, 2 c_c\n    assert m.move_copy_nested((1, ((2, 3, (4,)), 5))) == 15\n\n    assert c_m.copy_assignments + c_m.copy_constructions == 0\n    assert c_m.move_assignments == 6\n    assert c_m.move_constructions == 21\n    assert c_mc.copy_assignments + c_mc.copy_constructions == 0\n    assert c_mc.move_assignments == 5\n    assert c_mc.move_constructions == 18\n    assert c_c.copy_assignments == 4\n    assert c_c.copy_constructions == 14\n    assert c_m.alive() + c_mc.alive() + c_c.alive() == 0\n\n\n@pytest.mark.skipif(not m.has_optional, reason=\"no <optional>\")\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_move_and_copy_load_optional():\n    \"\"\"Tests move/copy loads of std::optional arguments\"\"\"\n\n    cstats = m.move_and_copy_cstats()\n    c_m, c_mc, c_c = (\n        cstats[\"MoveOnlyInt\"],\n        cstats[\"MoveOrCopyInt\"],\n        cstats[\"CopyOnlyInt\"],\n    )\n\n    # The extra move/copy constructions below come from the std::optional move (which has to move\n    # its arguments):\n    assert m.move_optional(10) == 10  # c_m: 1 move assign, 2 move construct\n    assert m.move_or_copy_optional(11) == 11  # c_mc: 1 move assign, 2 move construct\n    assert m.copy_optional(12) == 12  # c_c: 1 copy assign, 2 copy construct\n    # 1 move assign + move construct moves each of c_m, c_mc, 1 c_c copy\n    # +1 move/copy construct each from moving the tuple\n    # +1 move/copy construct each from moving the optional (which moves the tuple again)\n    assert m.move_optional_tuple((3, 4, 5)) == 12\n\n    assert c_m.copy_assignments + c_m.copy_constructions == 0\n    assert c_m.move_assignments == 2\n    assert c_m.move_constructions == 9\n    assert c_mc.copy_assignments + c_mc.copy_constructions == 0\n    assert c_mc.move_assignments == 2\n    assert c_mc.move_constructions == 9\n    assert c_c.copy_assignments == 2\n    assert c_c.copy_constructions == 9\n    assert c_m.alive() + c_mc.alive() + c_c.alive() == 0\n\n\ndef test_private_op_new():\n    \"\"\"An object with a private `operator new` cannot be returned by value\"\"\"\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.private_op_new_value()\n    assert \"is neither movable nor copyable\" in str(excinfo.value)\n\n    assert m.private_op_new_reference().value == 1\n\n\ndef test_move_fallback():\n    \"\"\"#389: rvp::move should fall-through to copy on non-movable objects\"\"\"\n\n    m1 = m.get_moveissue1(1)\n    assert m1.value == 1\n    m2 = m.get_moveissue2(2)\n    assert m2.value == 2\n\n\ndef test_pytype_rvalue_cast():\n    \"\"\"Make sure that cast from pytype rvalue to other pytype works\"\"\"\n\n    value = m.get_pytype_rvalue_castissue(1.0)\n    assert value == 1\n\n\ndef test_unusual_op_ref():\n    # Merely to test that this still exists and built successfully.\n    assert m.CallCastUnusualOpRefConstRef().__class__.__name__ == \"UnusualOpRef\"\n    assert m.CallCastUnusualOpRefMovable().__class__.__name__ == \"UnusualOpRef\"\n"
  },
  {
    "path": "tests/test_cpp_conduit.cpp",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#include \"pybind11_tests.h\"\n#include \"test_cpp_conduit_traveler_bindings.h\"\n\n#include <typeinfo>\n\nnamespace pybind11_tests {\nnamespace test_cpp_conduit {\n\nTEST_SUBMODULE(cpp_conduit, m) {\n    m.attr(\"PYBIND11_PLATFORM_ABI_ID\") = py::bytes(PYBIND11_PLATFORM_ABI_ID);\n    m.attr(\"cpp_type_info_capsule_Traveler\")\n        = py::capsule(&typeid(Traveler), typeid(std::type_info).name());\n    m.attr(\"cpp_type_info_capsule_int\") = py::capsule(&typeid(int), typeid(std::type_info).name());\n\n    wrap_traveler(m);\n    wrap_lonely_traveler(m);\n}\n\n} // namespace test_cpp_conduit\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_cpp_conduit.py",
    "content": "# Copyright (c) 2024 The pybind Community.\n\nfrom __future__ import annotations\n\nimport importlib\nimport sys\n\nimport pytest\n\nimport env\nfrom pybind11_tests import cpp_conduit as home_planet\n\n\ndef import_warns_freethreaded(name):\n    if name not in sys.modules and not env.sys_is_gil_enabled():\n        with pytest.warns(\n            RuntimeWarning, match=f\"has been enabled to load module '{name}'\"\n        ):\n            return importlib.import_module(name)\n\n    return importlib.import_module(name)\n\n\nexo_planet_c_api = import_warns_freethreaded(\"exo_planet_c_api\")\nexo_planet_pybind11 = import_warns_freethreaded(\"exo_planet_pybind11\")\nhome_planet_very_lonely_traveler = import_warns_freethreaded(\n    \"home_planet_very_lonely_traveler\"\n)\n\n\ndef test_traveler_getattr_actually_exists():\n    t_h = home_planet.Traveler(\"home\")\n    assert t_h.any_name == \"Traveler GetAttr: any_name luggage: home\"\n\n\ndef test_premium_traveler_getattr_actually_exists():\n    t_h = home_planet.PremiumTraveler(\"home\", 7)\n    assert t_h.secret_name == \"PremiumTraveler GetAttr: secret_name points: 7\"\n\n\ndef test_call_cpp_conduit_success():\n    t_h = home_planet.Traveler(\"home\")\n    cap = t_h._pybind11_conduit_v1_(\n        home_planet.PYBIND11_PLATFORM_ABI_ID,\n        home_planet.cpp_type_info_capsule_Traveler,\n        b\"raw_pointer_ephemeral\",\n    )\n    assert cap.__class__.__name__ == \"PyCapsule\" or (\n        # Note: this will become unnecessary in the next GraalPy release\n        env.GRAALPY and cap.__class__.__name__ == \"capsule\"\n    )\n\n\ndef test_call_cpp_conduit_platform_abi_id_mismatch():\n    t_h = home_planet.Traveler(\"home\")\n    cap = t_h._pybind11_conduit_v1_(\n        home_planet.PYBIND11_PLATFORM_ABI_ID + b\"MISMATCH\",\n        home_planet.cpp_type_info_capsule_Traveler,\n        b\"raw_pointer_ephemeral\",\n    )\n    assert cap is None\n\n\ndef test_call_cpp_conduit_cpp_type_info_capsule_mismatch():\n    t_h = home_planet.Traveler(\"home\")\n    cap = t_h._pybind11_conduit_v1_(\n        home_planet.PYBIND11_PLATFORM_ABI_ID,\n        home_planet.cpp_type_info_capsule_int,\n        b\"raw_pointer_ephemeral\",\n    )\n    assert cap is None\n\n\ndef test_call_cpp_conduit_pointer_kind_invalid():\n    t_h = home_planet.Traveler(\"home\")\n    with pytest.raises(\n        RuntimeError, match='^Invalid pointer_kind: \"raw_pointer_ephemreal\"$'\n    ):\n        t_h._pybind11_conduit_v1_(\n            home_planet.PYBIND11_PLATFORM_ABI_ID,\n            home_planet.cpp_type_info_capsule_Traveler,\n            b\"raw_pointer_ephemreal\",\n        )\n\n\ndef test_home_only_basic():\n    t_h = home_planet.Traveler(\"home\")\n    assert t_h.luggage == \"home\"\n    assert home_planet.get_luggage(t_h) == \"home\"\n\n\ndef test_home_only_premium():\n    p_h = home_planet.PremiumTraveler(\"home\", 2)\n    assert p_h.luggage == \"home\"\n    assert home_planet.get_luggage(p_h) == \"home\"\n    assert home_planet.get_points(p_h) == 2\n\n\ndef test_exo_only_basic():\n    t_e = exo_planet_pybind11.Traveler(\"exo\")\n    assert t_e.luggage == \"exo\"\n    assert exo_planet_pybind11.get_luggage(t_e) == \"exo\"\n\n\ndef test_exo_only_premium():\n    p_e = exo_planet_pybind11.PremiumTraveler(\"exo\", 3)\n    assert p_e.luggage == \"exo\"\n    assert exo_planet_pybind11.get_luggage(p_e) == \"exo\"\n    assert exo_planet_pybind11.get_points(p_e) == 3\n\n\ndef test_home_passed_to_exo_basic():\n    t_h = home_planet.Traveler(\"home\")\n    assert exo_planet_pybind11.get_luggage(t_h) == \"home\"\n\n\ndef test_exo_passed_to_home_basic():\n    t_e = exo_planet_pybind11.Traveler(\"exo\")\n    assert home_planet.get_luggage(t_e) == \"exo\"\n\n\ndef test_home_passed_to_exo_premium():\n    p_h = home_planet.PremiumTraveler(\"home\", 2)\n    assert exo_planet_pybind11.get_luggage(p_h) == \"home\"\n    assert exo_planet_pybind11.get_points(p_h) == 2\n\n\ndef test_exo_passed_to_home_premium():\n    p_e = exo_planet_pybind11.PremiumTraveler(\"exo\", 3)\n    assert home_planet.get_luggage(p_e) == \"exo\"\n    assert home_planet.get_points(p_e) == 3\n\n\n@pytest.mark.parametrize(\n    \"traveler_type\", [home_planet.Traveler, exo_planet_pybind11.Traveler]\n)\ndef test_exo_planet_c_api_traveler(traveler_type):\n    t = traveler_type(\"socks\")\n    assert exo_planet_c_api.GetLuggage(t) == \"socks\"\n\n\n@pytest.mark.parametrize(\n    \"premium_traveler_type\",\n    [home_planet.PremiumTraveler, exo_planet_pybind11.PremiumTraveler],\n)\ndef test_exo_planet_c_api_premium_traveler(premium_traveler_type):\n    pt = premium_traveler_type(\"gucci\", 5)\n    assert exo_planet_c_api.GetLuggage(pt) == \"gucci\"\n    assert exo_planet_c_api.GetPoints(pt) == 5\n\n\ndef test_home_planet_wrap_very_lonely_traveler():\n    # This does not exercise the cpp_conduit feature, but is here to\n    # demonstrate that the cpp_conduit feature does not solve\n    # cross-extension base-and-derived class interoperability issues.\n    # Here is the proof that the following works for extensions with\n    # matching `PYBIND11_INTERNALS_ID`s:\n    #     test_cpp_conduit.cpp:\n    #         py::class_<LonelyTraveler>\n    #     home_planet_very_lonely_traveler.cpp:\n    #         py::class_<VeryLonelyTraveler, LonelyTraveler>\n    # See test_exo_planet_pybind11_wrap_very_lonely_traveler() for the negative\n    # test.\n    assert home_planet.LonelyTraveler is not None  # Verify that the base class exists.\n    home_planet_very_lonely_traveler.wrap_very_lonely_traveler()\n    # Ensure that the derived class exists.\n    assert home_planet_very_lonely_traveler.VeryLonelyTraveler is not None\n\n\ndef test_exo_planet_pybind11_wrap_very_lonely_traveler():\n    # See comment under test_home_planet_wrap_very_lonely_traveler() first.\n    # Here the `PYBIND11_INTERNALS_ID`s don't match between:\n    #     test_cpp_conduit.cpp:\n    #         py::class_<LonelyTraveler>\n    #     exo_planet_pybind11.cpp:\n    #         py::class_<VeryLonelyTraveler, LonelyTraveler>\n    assert home_planet.LonelyTraveler is not None  # Verify that the base class exists.\n    with pytest.raises(\n        RuntimeError,\n        match='^generic_type: type \"VeryLonelyTraveler\" referenced unknown base type '\n        '\"pybind11_tests::test_cpp_conduit::LonelyTraveler\"$',\n    ):\n        exo_planet_pybind11.wrap_very_lonely_traveler()\n"
  },
  {
    "path": "tests/test_cpp_conduit_traveler_bindings.h",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#pragma once\n\n#include <pybind11/pybind11.h>\n\n#include \"test_cpp_conduit_traveler_types.h\"\n\n#include <string>\n\nnamespace pybind11_tests {\nnamespace test_cpp_conduit {\n\nnamespace py = pybind11;\n\ninline void wrap_traveler(py::module_ m) {\n    py::class_<Traveler>(m, \"Traveler\")\n        .def(py::init<std::string>())\n        .def_readwrite(\"luggage\", &Traveler::luggage)\n        // See issue #3788:\n        .def(\"__getattr__\", [](const Traveler &self, const std::string &key) {\n            return \"Traveler GetAttr: \" + key + \" luggage: \" + self.luggage;\n        });\n\n    m.def(\"get_luggage\", [](const Traveler &person) { return person.luggage; });\n\n    py::class_<PremiumTraveler, Traveler>(m, \"PremiumTraveler\")\n        .def(py::init<std::string, int>())\n        .def_readwrite(\"points\", &PremiumTraveler::points)\n        // See issue #3788:\n        .def(\"__getattr__\", [](const PremiumTraveler &self, const std::string &key) {\n            return \"PremiumTraveler GetAttr: \" + key + \" points: \" + std::to_string(self.points);\n        });\n\n    m.def(\"get_points\", [](const PremiumTraveler &person) { return person.points; });\n}\n\ninline void wrap_lonely_traveler(py::module_ m) {\n    py::class_<LonelyTraveler>(std::move(m), \"LonelyTraveler\");\n}\n\ninline void wrap_very_lonely_traveler(py::module_ m) {\n    py::class_<VeryLonelyTraveler, LonelyTraveler>(std::move(m), \"VeryLonelyTraveler\");\n}\n\n} // namespace test_cpp_conduit\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_cpp_conduit_traveler_types.h",
    "content": "// Copyright (c) 2024 The pybind Community.\n\n#pragma once\n\n#include <string>\n\nnamespace pybind11_tests {\nnamespace test_cpp_conduit {\n\nstruct Traveler {\n    explicit Traveler(const std::string &luggage) : luggage(luggage) {}\n    std::string luggage;\n};\n\nstruct PremiumTraveler : Traveler {\n    explicit PremiumTraveler(const std::string &luggage, int points)\n        : Traveler(luggage), points(points) {}\n    int points;\n};\n\nstruct LonelyTraveler {};\nstruct VeryLonelyTraveler : LonelyTraveler {};\n\n} // namespace test_cpp_conduit\n} // namespace pybind11_tests\n"
  },
  {
    "path": "tests/test_cross_module_rtti/CMakeLists.txt",
    "content": "possibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)\n\nset(CMAKE_CXX_VISIBILITY_PRESET hidden)\n\nif(\"${PYTHON_MODULE_EXTENSION}\" MATCHES \"pypy\"\n   OR \"${Python_INTERPRETER_ID}\" STREQUAL \"PyPy\"\n   OR \"${PYTHON_MODULE_EXTENSION}\" MATCHES \"graalpy\")\n  message(STATUS \"Skipping visibility test on PyPy or GraalPy\")\n  add_custom_target(test_cross_module_rtti\n  )# Dummy target on PyPy or GraalPy. Embedding is not supported.\n  set(_suppress_unused_variable_warning \"${DOWNLOAD_CATCH}\")\n  return()\nendif()\n\nif(TARGET Python::Module AND NOT TARGET Python::Python)\n  message(STATUS \"Skipping visibility test since no embed libs found\")\n  add_custom_target(test_cross_module_rtti) # Dummy target since embedding is not supported.\n  set(_suppress_unused_variable_warning \"${DOWNLOAD_CATCH}\")\n  return()\nendif()\n\nfind_package(Catch 2.13.10)\n\nif(CATCH_FOUND)\n  message(STATUS \"Building interpreter tests using Catch v${CATCH_VERSION}\")\nelse()\n  message(STATUS \"Catch not detected. Interpreter tests will be skipped. Install Catch headers\"\n                 \" manually or use `cmake -DDOWNLOAD_CATCH=ON` to fetch them automatically.\")\n  return()\nendif()\n\ninclude(GenerateExportHeader)\n\nadd_library(test_cross_module_rtti_lib SHARED lib.h lib.cpp)\nadd_library(test_cross_module_rtti_lib::test_cross_module_rtti_lib ALIAS\n            test_cross_module_rtti_lib)\ntarget_include_directories(test_cross_module_rtti_lib PUBLIC ${CMAKE_CURRENT_BINARY_DIR})\ntarget_include_directories(test_cross_module_rtti_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})\ntarget_compile_features(test_cross_module_rtti_lib PUBLIC cxx_std_11)\n\ngenerate_export_header(test_cross_module_rtti_lib)\n\npybind11_add_module(test_cross_module_rtti_bindings SHARED bindings.cpp)\ntarget_link_libraries(test_cross_module_rtti_bindings\n                      PUBLIC test_cross_module_rtti_lib::test_cross_module_rtti_lib)\n\nadd_executable(test_cross_module_rtti_main catch.cpp test_cross_module_rtti.cpp)\ntarget_link_libraries(\n  test_cross_module_rtti_main PUBLIC test_cross_module_rtti_lib::test_cross_module_rtti_lib\n                                     pybind11::embed Catch2::Catch2)\n\n# Ensure that we have built the python bindings since we load them in main\nadd_dependencies(test_cross_module_rtti_main test_cross_module_rtti_bindings)\n\npybind11_enable_warnings(test_cross_module_rtti_main)\npybind11_enable_warnings(test_cross_module_rtti_bindings)\npybind11_enable_warnings(test_cross_module_rtti_lib)\n\nadd_custom_target(\n  test_cross_module_rtti\n  COMMAND \"$<TARGET_FILE:test_cross_module_rtti_main>\"\n  DEPENDS test_cross_module_rtti_main\n  WORKING_DIRECTORY \"$<TARGET_FILE_DIR:test_cross_module_rtti_main>\"\n  USES_TERMINAL # Ensures output is shown immediately (not buffered and possibly lost on crash)\n)\n\nset_target_properties(test_cross_module_rtti_bindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY\n                                                                 \"${CMAKE_CURRENT_BINARY_DIR}\")\n\nadd_dependencies(check test_cross_module_rtti)\n"
  },
  {
    "path": "tests/test_cross_module_rtti/bindings.cpp",
    "content": "#include <pybind11/pybind11.h>\n\n#include <lib.h>\n\nclass BaseTrampoline : public lib::Base, public pybind11::trampoline_self_life_support {\npublic:\n    using lib::Base::Base;\n    int get() const override { PYBIND11_OVERLOAD(int, lib::Base, get); }\n};\n\nPYBIND11_MODULE(test_cross_module_rtti_bindings, m) {\n    pybind11::classh<lib::Base, BaseTrampoline>(m, \"Base\")\n        .def(pybind11::init<int, int>())\n        .def_readwrite(\"a\", &lib::Base::a)\n        .def_readwrite(\"b\", &lib::Base::b);\n\n    m.def(\"get_foo\", [](int a, int b) -> std::shared_ptr<lib::Base> {\n        return std::make_shared<lib::Foo>(a, b);\n    });\n}\n"
  },
  {
    "path": "tests/test_cross_module_rtti/catch.cpp",
    "content": "// The Catch implementation is compiled here. This is a standalone\n// translation unit to avoid recompiling it for every test change.\n\n#include <pybind11/embed.h>\n\n// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to\n// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).\nPYBIND11_WARNING_DISABLE_MSVC(4996)\n\n// Catch uses _ internally, which breaks gettext style defines\n#ifdef _\n#    undef _\n#endif\n\n#define CATCH_CONFIG_RUNNER\n#include <catch.hpp>\n\nint main(int argc, char *argv[]) {\n    pybind11::scoped_interpreter guard{};\n    auto result = Catch::Session().run(argc, argv);\n    return result < 0xff ? result : 0xff;\n}\n"
  },
  {
    "path": "tests/test_cross_module_rtti/lib.cpp",
    "content": "#include <lib.h>\n\nnamespace lib {\n\nBase::Base(int a, int b) : a(a), b(b) {}\n\nint Base::get() const { return a + b; }\n\nFoo::Foo(int a, int b) : Base{a, b} {}\n\nint Foo::get() const { return 2 * a + b; }\n\n} // namespace lib\n"
  },
  {
    "path": "tests/test_cross_module_rtti/lib.h",
    "content": "#pragma once\n\n#include <memory>\n#include <test_cross_module_rtti_lib_export.h>\n\n#if defined(_MSC_VER)\n__pragma(warning(disable : 4251))\n#endif\n\n    namespace lib {\n\n    class TEST_CROSS_MODULE_RTTI_LIB_EXPORT Base : public std::enable_shared_from_this<Base> {\n    public:\n        Base(int a, int b);\n        Base(const Base &) = default;\n        virtual ~Base() = default;\n\n        virtual int get() const;\n\n        int a;\n        int b;\n    };\n\n    class TEST_CROSS_MODULE_RTTI_LIB_EXPORT Foo : public Base {\n    public:\n        Foo(int a, int b);\n\n        int get() const override;\n    };\n\n} // namespace lib\n"
  },
  {
    "path": "tests/test_cross_module_rtti/test_cross_module_rtti.cpp",
    "content": "\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n\n#include <catch.hpp>\n#include <lib.h>\n\nstatic constexpr auto script = R\"(\nimport test_cross_module_rtti_bindings\n\nclass Bar(test_cross_module_rtti_bindings.Base):\n    def __init__(self, a, b):\n        test_cross_module_rtti_bindings.Base.__init__(self, a, b)\n\n    def get(self):\n        return 4 * self.a + self.b\n\n\ndef get_bar(a, b):\n    return Bar(a, b)\n\n)\";\n\nTEST_CASE(\"Simple case where without is_alias\") {\n    // \"Simple\" case this will not have `python_instance_is_alias` set in type_cast_base.h:771\n    auto bindings = pybind11::module_::import(\"test_cross_module_rtti_bindings\");\n    auto holder = bindings.attr(\"get_foo\")(1, 2);\n    auto foo = holder.cast<std::shared_ptr<lib::Base>>();\n    REQUIRE(foo->get() == 4); // 2 * 1 + 2 = 4\n}\n\nTEST_CASE(\"Complex case where with it_alias\") {\n    // \"Complex\" case this will have `python_instance_is_alias` set in type_cast_base.h:771\n    pybind11::exec(script);\n    auto main = pybind11::module::import(\"__main__\");\n\n    // The critical part of \"Bar\" is that it will have the `is_alias` `instance` flag set.\n    // I'm not quite sure what is required to get that flag, this code is derived from a\n    // larger code where this issue was observed.\n    auto holder2 = main.attr(\"get_bar\")(1, 2);\n\n    // this will trigger `std::get_deleter<memory::guarded_delete>` in type_cast_base.h:772\n    // This will fail since the program will see two different typeids for `memory::guarded_delete`\n    // on from the bindings module and one from \"main\", which will both have\n    // `__is_type_name_unique` as true and but still have different values. Hence we will not find\n    // the deleter and the cast fill fail. See \"__eq(__type_name_t __lhs, __type_name_t __rhs)\" in\n    // typeinfo in libc++\n    auto bar = holder2.cast<std::shared_ptr<lib::Base>>();\n    REQUIRE(bar->get() == 6); // 4 * 1 + 2 = 6\n}\n"
  },
  {
    "path": "tests/test_custom_type_casters.cpp",
    "content": "/*\n    tests/test_custom_type_casters.cpp -- tests type_caster<T>\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n// py::arg/py::arg_v testing: these arguments just record their argument when invoked\nclass ArgInspector1 {\npublic:\n    std::string arg = \"(default arg inspector 1)\";\n};\nclass ArgInspector2 {\npublic:\n    std::string arg = \"(default arg inspector 2)\";\n};\nclass ArgAlwaysConverts {};\n\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <>\nstruct type_caster<ArgInspector1> {\npublic:\n    // Classic\n#ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY\n    PYBIND11_TYPE_CASTER(ArgInspector1, _(\"ArgInspector1\"));\n#else\n    PYBIND11_TYPE_CASTER(ArgInspector1, const_name(\"ArgInspector1\"));\n#endif\n\n    bool load(handle src, bool convert) {\n        value.arg = \"loading ArgInspector1 argument \" + std::string(convert ? \"WITH\" : \"WITHOUT\")\n                    + \" conversion allowed.  \"\n                      \"Argument value = \"\n                    + (std::string) str(src);\n        return true;\n    }\n\n    static handle cast(const ArgInspector1 &src, return_value_policy, handle) {\n        return str(src.arg).release();\n    }\n};\ntemplate <>\nstruct type_caster<ArgInspector2> {\npublic:\n    PYBIND11_TYPE_CASTER(ArgInspector2, const_name(\"ArgInspector2\"));\n\n    bool load(handle src, bool convert) {\n        value.arg = \"loading ArgInspector2 argument \" + std::string(convert ? \"WITH\" : \"WITHOUT\")\n                    + \" conversion allowed.  \"\n                      \"Argument value = \"\n                    + (std::string) str(src);\n        return true;\n    }\n\n    static handle cast(const ArgInspector2 &src, return_value_policy, handle) {\n        return str(src.arg).release();\n    }\n};\ntemplate <>\nstruct type_caster<ArgAlwaysConverts> {\npublic:\n    PYBIND11_TYPE_CASTER(ArgAlwaysConverts, const_name(\"ArgAlwaysConverts\"));\n\n    bool load(handle, bool convert) { return convert; }\n\n    static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) {\n        return py::none().release();\n    }\n};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n\n// test_custom_caster_destruction\nclass DestructionTester {\npublic:\n    DestructionTester() { print_default_created(this); }\n    ~DestructionTester() { print_destroyed(this); }\n    DestructionTester(const DestructionTester &) { print_copy_created(this); }\n    DestructionTester(DestructionTester &&) noexcept { print_move_created(this); }\n    DestructionTester &operator=(const DestructionTester &) {\n        print_copy_assigned(this);\n        return *this;\n    }\n    DestructionTester &operator=(DestructionTester &&) noexcept {\n        print_move_assigned(this);\n        return *this;\n    }\n};\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <>\nstruct type_caster<DestructionTester> {\n    PYBIND11_TYPE_CASTER(DestructionTester, const_name(\"DestructionTester\"));\n    bool load(handle, bool) { return true; }\n\n    static handle cast(const DestructionTester &, return_value_policy, handle) {\n        return py::bool_(true).release();\n    }\n};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n\n// Define type caster outside of `pybind11::detail` and then alias it.\nnamespace other_lib {\nstruct MyType {};\n// Corrupt `py` shorthand alias for surrounding context.\nnamespace py {}\n// Corrupt unqualified relative `pybind11` namespace.\nnamespace PYBIND11_NAMESPACE {}\n// Correct alias.\nnamespace py_ = ::pybind11;\n// Define caster. This is effectively no-op, we only ensure it compiles and we\n// don't have any symbol collision when using macro mixin.\nstruct my_caster {\n    PYBIND11_TYPE_CASTER(MyType, py_::detail::const_name(\"MyType\"));\n    bool load(py_::handle, bool) { return true; }\n\n    static py_::handle cast(const MyType &, py_::return_value_policy, py_::handle) {\n        return py_::bool_(true).release();\n    }\n};\n} // namespace other_lib\n// Effectively \"alias\" it into correct namespace (via inheritance).\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <>\nstruct type_caster<other_lib::MyType> : public other_lib::my_caster {};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n\n// This simply is required to compile\nnamespace ADL_issue {\ntemplate <typename OutStringType = std::string, typename... Args>\nOutStringType concat(Args &&...) {\n    return OutStringType();\n}\n\nstruct test {};\n} // namespace ADL_issue\n\nTEST_SUBMODULE(custom_type_casters, m) {\n    // test_custom_type_casters\n\n    // test_noconvert_args\n    //\n    // Test converting.  The ArgAlwaysConverts is just there to make the first no-conversion pass\n    // fail so that our call always ends up happening via the second dispatch (the one that allows\n    // some conversion).\n    class ArgInspector {\n    public:\n        ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; }\n        std::string g(const ArgInspector1 &a,\n                      const ArgInspector1 &b,\n                      int c,\n                      ArgInspector2 *d,\n                      ArgAlwaysConverts) {\n            return a.arg + \"\\n\" + b.arg + \"\\n\" + std::to_string(c) + \"\\n\" + d->arg;\n        }\n        static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; }\n    };\n    // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.\n    py::class_<ArgInspector>(m, \"ArgInspector\")\n        .def(py::init<>())\n        .def(\"f\", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts())\n        .def(\"g\",\n             &ArgInspector::g,\n             \"a\"_a.noconvert(),\n             \"b\"_a,\n             \"c\"_a.noconvert() = 13,\n             \"d\"_a = ArgInspector2(),\n             py::arg() = ArgAlwaysConverts())\n        .def_static(\"h\", &ArgInspector::h, py::arg{}.noconvert(), py::arg() = ArgAlwaysConverts());\n    m.def(\n        \"arg_inspect_func\",\n        [](const ArgInspector2 &a, const ArgInspector1 &b, ArgAlwaysConverts) {\n            return a.arg + \"\\n\" + b.arg;\n        },\n        py::arg{}.noconvert(false),\n        py::arg_v(nullptr, ArgInspector1()).noconvert(true),\n        py::arg() = ArgAlwaysConverts());\n\n    m.def(\"floats_preferred\", [](double f) { return 0.5 * f; }, \"f\"_a);\n    m.def(\"floats_only\", [](double f) { return 0.5 * f; }, \"f\"_a.noconvert());\n    m.def(\"ints_preferred\", [](int i) { return i / 2; }, \"i\"_a);\n    m.def(\"ints_only\", [](int i) { return i / 2; }, \"i\"_a.noconvert());\n\n    // test_custom_caster_destruction\n    // Test that `take_ownership` works on types with a custom type caster when given a pointer\n\n    // default policy: don't take ownership:\n    m.def(\"custom_caster_no_destroy\", []() {\n        static auto *dt = new DestructionTester();\n        return dt;\n    });\n\n    m.def(\n        \"custom_caster_destroy\",\n        []() { return new DestructionTester(); },\n        py::return_value_policy::take_ownership); // Takes ownership: destroy when finished\n    m.def(\n        \"custom_caster_destroy_const\",\n        []() -> const DestructionTester * { return new DestructionTester(); },\n        py::return_value_policy::take_ownership); // Likewise (const doesn't inhibit destruction)\n    m.def(\"destruction_tester_cstats\",\n          &ConstructorStats::get<DestructionTester>,\n          py::return_value_policy::reference);\n\n    m.def(\"other_lib_type\", [](other_lib::MyType x) { return x; });\n\n    m.def(\"_adl_issue\", [](const ADL_issue::test &) {});\n}\n"
  },
  {
    "path": "tests/test_custom_type_casters.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import custom_type_casters as m\n\n\ndef test_noconvert_args(msg):\n    a = m.ArgInspector()\n    assert (\n        msg(a.f(\"hi\"))\n        == \"\"\"\n        loading ArgInspector1 argument WITH conversion allowed.  Argument value = hi\n    \"\"\"\n    )\n    assert (\n        msg(a.g(\"this is a\", \"this is b\"))\n        == \"\"\"\n        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a\n        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b\n        13\n        loading ArgInspector2 argument WITH conversion allowed.  Argument value = (default arg inspector 2)\n    \"\"\"\n    )\n    assert (\n        msg(a.g(\"this is a\", \"this is b\", 42))\n        == \"\"\"\n        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a\n        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b\n        42\n        loading ArgInspector2 argument WITH conversion allowed.  Argument value = (default arg inspector 2)\n    \"\"\"\n    )\n    assert (\n        msg(a.g(\"this is a\", \"this is b\", 42, \"this is d\"))\n        == \"\"\"\n        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = this is a\n        loading ArgInspector1 argument WITH conversion allowed.  Argument value = this is b\n        42\n        loading ArgInspector2 argument WITH conversion allowed.  Argument value = this is d\n    \"\"\"\n    )\n    assert (\n        a.h(\"arg 1\")\n        == \"loading ArgInspector2 argument WITHOUT conversion allowed.  Argument value = arg 1\"\n    )\n    assert (\n        msg(m.arg_inspect_func(\"A1\", \"A2\"))\n        == \"\"\"\n        loading ArgInspector2 argument WITH conversion allowed.  Argument value = A1\n        loading ArgInspector1 argument WITHOUT conversion allowed.  Argument value = A2\n    \"\"\"\n    )\n\n    assert m.floats_preferred(4) == 2.0\n    assert m.floats_only(4.0) == 2.0\n    assert m.floats_only(4) == 2.0\n\n    assert m.ints_preferred(4) == 2\n    assert m.ints_preferred(True) == 0\n    with pytest.raises(TypeError) as excinfo:\n        m.ints_preferred(4.0)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        ints_preferred(): incompatible function arguments. The following argument types are supported:\n            1. (i: typing.SupportsInt | typing.SupportsIndex) -> int\n\n        Invoked with: 4.0\n    \"\"\"\n    )\n\n    assert m.ints_only(4) == 2\n    with pytest.raises(TypeError) as excinfo:\n        m.ints_only(4.0)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        ints_only(): incompatible function arguments. The following argument types are supported:\n            1. (i: int) -> int\n\n        Invoked with: 4.0\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_custom_caster_destruction():\n    \"\"\"Tests that returning a pointer to a type that gets converted with a custom type caster gets\n    destroyed when the function has py::return_value_policy::take_ownership policy applied.\n    \"\"\"\n\n    cstats = m.destruction_tester_cstats()\n    # This one *doesn't* have take_ownership: the pointer should be used but not destroyed:\n    z = m.custom_caster_no_destroy()\n    assert cstats.alive() == 1\n    assert cstats.default_constructions == 1\n    assert z\n\n    # take_ownership applied: this constructs a new object, casts it, then destroys it:\n    z = m.custom_caster_destroy()\n    assert z\n    assert cstats.default_constructions == 2\n\n    # Same, but with a const pointer return (which should *not* inhibit destruction):\n    z = m.custom_caster_destroy_const()\n    assert z\n    assert cstats.default_constructions == 3\n\n    # Make sure we still only have the original object (from ..._no_destroy()) alive:\n    assert cstats.alive() == 1\n\n\ndef test_custom_caster_other_lib():\n    assert m.other_lib_type(True)\n"
  },
  {
    "path": "tests/test_custom_type_setup.cpp",
    "content": "/*\n    tests/test_custom_type_setup.cpp -- Tests `pybind11::custom_type_setup`\n\n    Copyright (c) Google LLC\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/detail/internals.h>\n#include <pybind11/pybind11.h>\n\n#include \"pybind11_tests.h\"\n\n#include <vector>\n\nnamespace py = pybind11;\n\nnamespace {\nstruct ContainerOwnsPythonObjects {\n    std::vector<py::object> list;\n\n    void append(const py::object &obj) { list.emplace_back(obj); }\n    py::object at(py::ssize_t index) const {\n        if (index >= size() || index < 0) {\n            throw py::index_error(\"Index out of range\");\n        }\n        return list.at(py::size_t(index));\n    }\n    py::ssize_t size() const { return py::ssize_t_cast(list.size()); }\n    void clear() { list.clear(); }\n};\n\nvoid add_gc_checkers_with_weakrefs(const py::object &obj) {\n    py::handle global_capsule = py::detail::get_internals_capsule();\n    if (!global_capsule) {\n        throw std::runtime_error(\"No global internals capsule found\");\n    }\n    (void) py::weakref(obj, py::cpp_function([global_capsule](py::handle weakref) -> void {\n                           py::handle current_global_capsule = py::detail::get_internals_capsule();\n                           if (!current_global_capsule.is(global_capsule)) {\n                               throw std::runtime_error(\n                                   \"Global internals capsule was destroyed prematurely\");\n                           }\n                           weakref.dec_ref();\n                       }))\n        .release();\n\n    py::handle local_capsule = py::detail::get_local_internals_capsule();\n    if (!local_capsule) {\n        throw std::runtime_error(\"No local internals capsule found\");\n    }\n    (void) py::weakref(\n        obj, py::cpp_function([local_capsule](py::handle weakref) -> void {\n            py::handle current_local_capsule = py::detail::get_local_internals_capsule();\n            if (!current_local_capsule.is(local_capsule)) {\n                throw std::runtime_error(\"Local internals capsule was destroyed prematurely\");\n            }\n            weakref.dec_ref();\n        }))\n        .release();\n}\n} // namespace\n\nTEST_SUBMODULE(custom_type_setup, m) {\n    py::class_<ContainerOwnsPythonObjects> cls(\n        m,\n        \"ContainerOwnsPythonObjects\",\n        // Please review/update docs/advanced/classes.rst after making changes here.\n        py::custom_type_setup([](PyHeapTypeObject *heap_type) {\n            auto *type = &heap_type->ht_type;\n            type->tp_flags |= Py_TPFLAGS_HAVE_GC;\n            type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {\n// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse\n#if PY_VERSION_HEX >= 0x03090000\n                Py_VISIT(Py_TYPE(self_base));\n#endif\n                if (py::detail::is_holder_constructed(self_base)) {\n                    auto &self = py::cast<ContainerOwnsPythonObjects &>(py::handle(self_base));\n                    for (auto &item : self.list) {\n                        Py_VISIT(item.ptr());\n                    }\n                }\n                return 0;\n            };\n            type->tp_clear = [](PyObject *self_base) {\n                if (py::detail::is_holder_constructed(self_base)) {\n                    auto &self = py::cast<ContainerOwnsPythonObjects &>(py::handle(self_base));\n                    for (auto &item : self.list) {\n                        Py_CLEAR(item.ptr());\n                    }\n                    self.list.clear();\n                }\n                return 0;\n            };\n        }));\n    cls.def(py::init<>());\n    cls.def(\"append\", &ContainerOwnsPythonObjects::append);\n    cls.def(\"at\", &ContainerOwnsPythonObjects::at);\n    cls.def(\"size\", &ContainerOwnsPythonObjects::size);\n    cls.def(\"clear\", &ContainerOwnsPythonObjects::clear);\n\n    m.def(\"add_gc_checkers_with_weakrefs\", &add_gc_checkers_with_weakrefs);\n}\n"
  },
  {
    "path": "tests/test_custom_type_setup.py",
    "content": "from __future__ import annotations\n\nimport gc\nimport os\nimport weakref\n\nimport pytest\n\nimport env\nimport pybind11_tests\nfrom pybind11_tests import custom_type_setup as m\n\n\n@pytest.fixture\ndef gc_tester():\n    \"\"\"Tests that an object is garbage collected.\n\n    Assumes that any unreferenced objects are fully collected after calling\n    `gc.collect()`.  That is true on CPython, but does not appear to reliably\n    hold on PyPy.\n    \"\"\"\n\n    weak_refs = []\n\n    def add_ref(obj):\n        # PyPy does not support `gc.is_tracked`.\n        if hasattr(gc, \"is_tracked\"):\n            assert gc.is_tracked(obj)\n        weak_refs.append(weakref.ref(obj))\n\n    yield add_ref\n\n    gc.collect()\n    for ref in weak_refs:\n        assert ref() is None\n\n\n# PyPy does not seem to reliably garbage collect.\n@pytest.mark.skipif(\"env.PYPY or env.GRAALPY\")\ndef test_self_cycle(gc_tester):\n    obj = m.ContainerOwnsPythonObjects()\n    obj.append(obj)\n    gc_tester(obj)\n\n\n# PyPy does not seem to reliably garbage collect.\n@pytest.mark.skipif(\"env.PYPY or env.GRAALPY\")\ndef test_indirect_cycle(gc_tester):\n    obj = m.ContainerOwnsPythonObjects()\n    obj.append([obj])\n    gc_tester(obj)\n\n\n@pytest.mark.skipif(\"env.PYPY or env.GRAALPY\")\ndef test_py_cast_useable_on_shutdown():\n    \"\"\"Test that py::cast works during interpreter shutdown.\n\n    See PR #5972 and https://github.com/pybind/pybind11/pull/5958#discussion_r2717645230.\n    \"\"\"\n    env.check_script_success_in_subprocess(\n        f\"\"\"\n        import sys\n\n        sys.path.insert(0, {os.path.dirname(env.__file__)!r})\n        sys.path.insert(0, {os.path.dirname(pybind11_tests.__file__)!r})\n\n        from pybind11_tests import custom_type_setup as m\n\n        # Create a self-referential cycle that will be collected during shutdown.\n        # The tp_traverse and tp_clear callbacks call py::cast, which requires\n        # internals to still be valid.\n        obj = m.ContainerOwnsPythonObjects()\n        obj.append(obj)\n\n        # Add weakref callbacks that verify the capsule is still alive when the\n        # pybind11 object is garbage collected during shutdown.\n        m.add_gc_checkers_with_weakrefs(obj)\n        \"\"\"\n    )\n"
  },
  {
    "path": "tests/test_docs_advanced_cast_custom.cpp",
    "content": "// #########################################################################\n// PLEASE UPDATE docs/advanced/cast/custom.rst IF ANY CHANGES ARE MADE HERE.\n// #########################################################################\n\n#include \"pybind11_tests.h\"\n\nnamespace user_space {\n\nstruct Point2D {\n    double x;\n    double y;\n};\n\nPoint2D negate(const Point2D &point) { return Point2D{-point.x, -point.y}; }\n\n} // namespace user_space\n\nnamespace pybind11 {\nnamespace detail {\n\ntemplate <>\nstruct type_caster<user_space::Point2D> {\n    // This macro inserts a lot of boilerplate code and sets the type hint.\n    // `io_name` is used to specify different type hints for arguments and return values.\n    // The signature of our negate function would then look like:\n    // `negate(collections.abc.Sequence[float]) -> tuple[float, float]`\n    PYBIND11_TYPE_CASTER(user_space::Point2D,\n                         io_name(\"collections.abc.Sequence[float]\", \"tuple[float, float]\"));\n\n    // C++ -> Python: convert `Point2D` to `tuple[float, float]`. The second and third arguments\n    // are used to indicate the return value policy and parent object (for\n    // return_value_policy::reference_internal) and are often ignored by custom casters.\n    // The return value should reflect the type hint specified by the second argument of `io_name`.\n    static handle\n    cast(const user_space::Point2D &number, return_value_policy /*policy*/, handle /*parent*/) {\n        return py::make_tuple(number.x, number.y).release();\n    }\n\n    // Python -> C++: convert a `PyObject` into a `Point2D` and return false upon failure. The\n    // second argument indicates whether implicit conversions should be allowed.\n    // The accepted types should reflect the type hint specified by the first argument of\n    // `io_name`.\n    bool load(handle src, bool /*convert*/) {\n        // Check if handle is a Sequence\n        if (!py::isinstance<py::sequence>(src)) {\n            return false;\n        }\n        auto seq = py::reinterpret_borrow<py::sequence>(src);\n        // Check if exactly two values are in the Sequence\n        if (seq.size() != 2) {\n            return false;\n        }\n        // Check if each element is either a float or an int\n        for (auto item : seq) {\n            if (!py::isinstance<py::float_>(item) && !py::isinstance<py::int_>(item)) {\n                return false;\n            }\n        }\n        value.x = seq[0].cast<double>();\n        value.y = seq[1].cast<double>();\n        return true;\n    }\n};\n\n} // namespace detail\n} // namespace pybind11\n\n// Bind the negate function\nTEST_SUBMODULE(docs_advanced_cast_custom, m) { m.def(\"negate\", user_space::negate); }\n"
  },
  {
    "path": "tests/test_docs_advanced_cast_custom.py",
    "content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Sequence\n\nif TYPE_CHECKING:\n    from conftest import SanitizedString\n\nfrom pybind11_tests import docs_advanced_cast_custom as m\n\n\ndef assert_negate_function(\n    input_sequence: Sequence[float],\n    target: tuple[float, float],\n) -> None:\n    output = m.negate(input_sequence)\n    assert isinstance(output, tuple)\n    assert len(output) == 2\n    assert isinstance(output[0], float)\n    assert isinstance(output[1], float)\n    assert output == target\n\n\ndef test_negate(doc: SanitizedString) -> None:\n    assert (\n        doc(m.negate)\n        == \"negate(arg0: collections.abc.Sequence[float]) -> tuple[float, float]\"\n    )\n    assert_negate_function([1.0, -1.0], (-1.0, 1.0))\n    assert_negate_function((1.0, -1.0), (-1.0, 1.0))\n    assert_negate_function([1, -1], (-1.0, 1.0))\n    assert_negate_function((1, -1), (-1.0, 1.0))\n\n\ndef test_docs() -> None:\n    ###########################################################################\n    # PLEASE UPDATE docs/advanced/cast/custom.rst IF ANY CHANGES ARE MADE HERE.\n    ###########################################################################\n    point1 = [1.0, -1.0]\n    point2 = m.negate(point1)\n    assert point2 == (-1.0, 1.0)\n"
  },
  {
    "path": "tests/test_docstring_options.cpp",
    "content": "/*\n    tests/test_docstring_options.cpp -- generation of docstrings and signatures\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(docstring_options, m) {\n    // test_docstring_options\n    {\n        py::options options;\n        options.disable_function_signatures();\n\n        m.def(\"test_function1\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"));\n        m.def(\"test_function2\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"), \"A custom docstring\");\n\n        m.def(\"test_overloaded1\", [](int) {}, py::arg(\"i\"), \"Overload docstring\");\n        m.def(\"test_overloaded1\", [](double) {}, py::arg(\"d\"));\n\n        m.def(\"test_overloaded2\", [](int) {}, py::arg(\"i\"), \"overload docstring 1\");\n        m.def(\"test_overloaded2\", [](double) {}, py::arg(\"d\"), \"overload docstring 2\");\n\n        m.def(\"test_overloaded3\", [](int) {}, py::arg(\"i\"));\n        m.def(\"test_overloaded3\", [](double) {}, py::arg(\"d\"), \"Overload docstr\");\n\n        options.enable_function_signatures();\n\n        m.def(\"test_function3\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"));\n        m.def(\"test_function4\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"), \"A custom docstring\");\n\n        options.disable_function_signatures().disable_user_defined_docstrings();\n\n        m.def(\"test_function5\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"), \"A custom docstring\");\n\n        {\n            py::options nested_options;\n            nested_options.enable_user_defined_docstrings();\n            m.def(\n                \"test_function6\",\n                [](int, int) {},\n                py::arg(\"a\"),\n                py::arg(\"b\"),\n                \"A custom docstring\");\n        }\n    }\n\n    m.def(\"test_function7\", [](int, int) {}, py::arg(\"a\"), py::arg(\"b\"), \"A custom docstring\");\n\n    {\n        py::options options;\n        options.disable_user_defined_docstrings();\n        options.disable_function_signatures();\n\n        m.def(\"test_function8\", []() {});\n    }\n\n    {\n        py::options options;\n        options.disable_user_defined_docstrings();\n\n        struct DocstringTestFoo {\n            int value;\n            void setValue(int v) { value = v; }\n            int getValue() const { return value; }\n        };\n        py::class_<DocstringTestFoo>(m, \"DocstringTestFoo\", \"This is a class docstring\")\n            .def_property(\"value_prop\",\n                          &DocstringTestFoo::getValue,\n                          &DocstringTestFoo::setValue,\n                          \"This is a property docstring\");\n    }\n\n    {\n        enum class DocstringTestEnum1 { Member1, Member2 };\n\n        py::enum_<DocstringTestEnum1>(m, \"DocstringTestEnum1\", \"Enum docstring\")\n            .value(\"Member1\", DocstringTestEnum1::Member1)\n            .value(\"Member2\", DocstringTestEnum1::Member2);\n    }\n\n    {\n        py::options options;\n        options.enable_enum_members_docstring();\n\n        enum class DocstringTestEnum2 { Member1, Member2 };\n\n        py::enum_<DocstringTestEnum2>(m, \"DocstringTestEnum2\", \"Enum docstring\")\n            .value(\"Member1\", DocstringTestEnum2::Member1)\n            .value(\"Member2\", DocstringTestEnum2::Member2);\n    }\n\n    {\n        py::options options;\n        options.disable_enum_members_docstring();\n\n        enum class DocstringTestEnum3 { Member1, Member2 };\n\n        py::enum_<DocstringTestEnum3>(m, \"DocstringTestEnum3\", \"Enum docstring\")\n            .value(\"Member1\", DocstringTestEnum3::Member1)\n            .value(\"Member2\", DocstringTestEnum3::Member2);\n    }\n\n    {\n        py::options options;\n        options.disable_user_defined_docstrings();\n\n        enum class DocstringTestEnum4 { Member1, Member2 };\n\n        py::enum_<DocstringTestEnum4>(m, \"DocstringTestEnum4\", \"Enum docstring\")\n            .value(\"Member1\", DocstringTestEnum4::Member1)\n            .value(\"Member2\", DocstringTestEnum4::Member2);\n    }\n\n    {\n        py::options options;\n        options.disable_user_defined_docstrings();\n        options.disable_enum_members_docstring();\n\n        enum class DocstringTestEnum5 { Member1, Member2 };\n\n        py::enum_<DocstringTestEnum5>(m, \"DocstringTestEnum5\", \"Enum docstring\")\n            .value(\"Member1\", DocstringTestEnum5::Member1)\n            .value(\"Member2\", DocstringTestEnum5::Member2);\n    }\n}\n"
  },
  {
    "path": "tests/test_docstring_options.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import docstring_options as m\n\n\ndef test_docstring_options():\n    # options.disable_function_signatures()\n    assert not m.test_function1.__doc__\n\n    assert m.test_function2.__doc__ == \"A custom docstring\"\n\n    # docstring specified on just the first overload definition:\n    assert m.test_overloaded1.__doc__ == \"Overload docstring\"\n\n    # docstring on both overloads:\n    assert m.test_overloaded2.__doc__ == \"overload docstring 1\\noverload docstring 2\"\n\n    # docstring on only second overload:\n    assert m.test_overloaded3.__doc__ == \"Overload docstr\"\n\n    # options.enable_function_signatures()\n    assert m.test_function3.__doc__.startswith(\n        \"test_function3(a: typing.SupportsInt | typing.SupportsIndex, b: typing.SupportsInt | typing.SupportsIndex) -> None\"\n    )\n\n    assert m.test_function4.__doc__.startswith(\n        \"test_function4(a: typing.SupportsInt | typing.SupportsIndex, b: typing.SupportsInt | typing.SupportsIndex) -> None\"\n    )\n    assert m.test_function4.__doc__.endswith(\"A custom docstring\\n\")\n\n    # options.disable_function_signatures()\n    # options.disable_user_defined_docstrings()\n    assert not m.test_function5.__doc__\n\n    # nested options.enable_user_defined_docstrings()\n    assert m.test_function6.__doc__ == \"A custom docstring\"\n\n    # RAII destructor\n    assert m.test_function7.__doc__.startswith(\n        \"test_function7(a: typing.SupportsInt | typing.SupportsIndex, b: typing.SupportsInt | typing.SupportsIndex) -> None\"\n    )\n    assert m.test_function7.__doc__.endswith(\"A custom docstring\\n\")\n\n    # when all options are disabled, no docstring (instead of an empty one) should be generated\n    assert m.test_function8.__doc__ is None\n\n    # Suppression of user-defined docstrings for non-function objects\n    assert not m.DocstringTestFoo.__doc__\n    assert not m.DocstringTestFoo.value_prop.__doc__\n\n    # Check existing behaviour of enum docstings\n    assert (\n        m.DocstringTestEnum1.__doc__\n        == \"Enum docstring\\n\\nMembers:\\n\\n  Member1\\n\\n  Member2\"\n    )\n\n    # options.enable_enum_members_docstring()\n    assert (\n        m.DocstringTestEnum2.__doc__\n        == \"Enum docstring\\n\\nMembers:\\n\\n  Member1\\n\\n  Member2\"\n    )\n\n    # options.disable_enum_members_docstring()\n    assert m.DocstringTestEnum3.__doc__ == \"Enum docstring\"\n\n    # options.disable_user_defined_docstrings()\n    assert m.DocstringTestEnum4.__doc__ == \"Members:\\n\\n  Member1\\n\\n  Member2\"\n\n    # options.disable_user_defined_docstrings()\n    # options.disable_enum_members_docstring()\n    # When all options are disabled, no docstring (instead of an empty one) should be generated\n    assert m.DocstringTestEnum5.__doc__ is None\n"
  },
  {
    "path": "tests/test_eigen_matrix.cpp",
    "content": "/*\n    tests/eigen.cpp -- automatic conversion of Eigen types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/eigen/matrix.h>\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\nPYBIND11_WARNING_DISABLE_MSVC(4996)\n\n#include <Eigen/Cholesky>\n\nusing MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the\n// (1-based) row/column number.\ntemplate <typename M>\nvoid reset_ref(M &x) {\n    for (int i = 0; i < x.rows(); i++) {\n        for (int j = 0; j < x.cols(); j++) {\n            x(i, j) = 11 + 10 * i + j;\n        }\n    }\n}\n\n// Returns a static, column-major matrix\nEigen::MatrixXd &get_cm() {\n    static Eigen::MatrixXd *x;\n    if (!x) {\n        x = new Eigen::MatrixXd(3, 3);\n        reset_ref(*x);\n    }\n    return *x;\n}\n// Likewise, but row-major\nMatrixXdR &get_rm() {\n    static MatrixXdR *x;\n    if (!x) {\n        x = new MatrixXdR(3, 3);\n        reset_ref(*x);\n    }\n    return *x;\n}\n// Resets the values of the static matrices returned by get_cm()/get_rm()\nvoid reset_refs() {\n    reset_ref(get_cm());\n    reset_ref(get_rm());\n}\n\n// Returns element 2,1 from a matrix (used to test copy/nocopy)\ndouble get_elem(const Eigen::Ref<const Eigen::MatrixXd> &m) { return m(2, 1); }\n\n// Returns a matrix with 10*r + 100*c added to each matrix element (to help test that the matrix\n// reference is referencing rows/columns correctly).\ntemplate <typename MatrixArgType>\nEigen::MatrixXd adjust_matrix(MatrixArgType m) {\n    Eigen::MatrixXd ret(m);\n    for (int c = 0; c < m.cols(); c++) {\n        for (int r = 0; r < m.rows(); r++) {\n            ret(r, c) += 10 * r + 100 * c; // NOLINT(clang-analyzer-core.uninitialized.Assign)\n        }\n    }\n    return ret;\n}\n\nstruct CustomOperatorNew {\n    CustomOperatorNew() = default;\n\n    Eigen::Matrix4d a = Eigen::Matrix4d::Zero();\n    Eigen::Matrix4d b = Eigen::Matrix4d::Identity();\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nTEST_SUBMODULE(eigen_matrix, m) {\n    using FixedMatrixR = Eigen::Matrix<float, 5, 6, Eigen::RowMajor>;\n    using FixedMatrixC = Eigen::Matrix<float, 5, 6>;\n    using DenseMatrixR = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    using DenseMatrixC = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;\n    using FourRowMatrixC = Eigen::Matrix<float, 4, Eigen::Dynamic>;\n    using FourColMatrixC = Eigen::Matrix<float, Eigen::Dynamic, 4>;\n    using FourRowMatrixR = Eigen::Matrix<float, 4, Eigen::Dynamic>;\n    using FourColMatrixR = Eigen::Matrix<float, Eigen::Dynamic, 4>;\n    using SparseMatrixR = Eigen::SparseMatrix<float, Eigen::RowMajor>;\n    using SparseMatrixC = Eigen::SparseMatrix<float>;\n\n    // various tests\n    m.def(\"double_col\", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return 2.0f * x; });\n    m.def(\"double_row\",\n          [](const Eigen::RowVectorXf &x) -> Eigen::RowVectorXf { return 2.0f * x; });\n    m.def(\"double_complex\",\n          [](const Eigen::VectorXcf &x) -> Eigen::VectorXcf { return 2.0f * x; });\n    m.def(\"double_threec\", [](py::EigenDRef<Eigen::Vector3f> x) { x *= 2; });\n    m.def(\"double_threer\", [](py::EigenDRef<Eigen::RowVector3f> x) { x *= 2; });\n    m.def(\"double_mat_cm\", [](const Eigen::MatrixXf &x) -> Eigen::MatrixXf { return 2.0f * x; });\n    m.def(\"double_mat_rm\", [](const DenseMatrixR &x) -> DenseMatrixR { return 2.0f * x; });\n\n    // test_eigen_ref_to_python\n    // Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended\n    m.def(\"cholesky1\",\n          [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n    m.def(\"cholesky2\", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {\n        return x.llt().matrixL();\n    });\n    m.def(\"cholesky3\",\n          [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });\n    m.def(\"cholesky4\", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {\n        return x.llt().matrixL();\n    });\n\n    // test_eigen_ref_mutators\n    // Mutators: these add some value to the given element using Eigen, but Eigen should be mapping\n    // into the numpy array data and so the result should show up there.  There are three versions:\n    // one that works on a contiguous-row matrix (numpy's default), one for a contiguous-column\n    // matrix, and one for any matrix.\n    auto add_rm = [](Eigen::Ref<MatrixXdR> x, int r, int c, double v) { x(r, c) += v; };\n    auto add_cm = [](Eigen::Ref<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; };\n\n    // Mutators (Eigen maps into numpy variables):\n    m.def(\"add_rm\", add_rm); // Only takes row-contiguous\n    m.def(\"add_cm\", add_cm); // Only takes column-contiguous\n    // Overloaded versions that will accept either row or column contiguous:\n    m.def(\"add1\", add_rm);\n    m.def(\"add1\", add_cm);\n    m.def(\"add2\", add_cm);\n    m.def(\"add2\", add_rm);\n    // This one accepts a matrix of any stride:\n    m.def(\"add_any\",\n          [](py::EigenDRef<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; });\n\n    // Return mutable references (numpy maps into eigen variables)\n    m.def(\"get_cm_ref\", []() { return Eigen::Ref<Eigen::MatrixXd>(get_cm()); });\n    m.def(\"get_rm_ref\", []() { return Eigen::Ref<MatrixXdR>(get_rm()); });\n    // The same references, but non-mutable (numpy maps into eigen variables, but is !writeable)\n    m.def(\"get_cm_const_ref\", []() { return Eigen::Ref<const Eigen::MatrixXd>(get_cm()); });\n    m.def(\"get_rm_const_ref\", []() { return Eigen::Ref<const MatrixXdR>(get_rm()); });\n\n    m.def(\"reset_refs\", reset_refs); // Restores get_{cm,rm}_ref to original values\n\n    // Increments and returns ref to (same) matrix\n    m.def(\n        \"incr_matrix\",\n        [](Eigen::Ref<Eigen::MatrixXd> m, double v) {\n            m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);\n            return m;\n        },\n        py::return_value_policy::reference);\n\n    // Same, but accepts a matrix of any strides\n    m.def(\n        \"incr_matrix_any\",\n        [](py::EigenDRef<Eigen::MatrixXd> m, double v) {\n            m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);\n            return m;\n        },\n        py::return_value_policy::reference);\n\n    // Returns an eigen slice of even rows\n    m.def(\n        \"even_rows\",\n        [](py::EigenDRef<Eigen::MatrixXd> m) {\n            return py::EigenDMap<Eigen::MatrixXd>(\n                m.data(),\n                (m.rows() + 1) / 2,\n                m.cols(),\n                py::EigenDStride(m.outerStride(), 2 * m.innerStride()));\n        },\n        py::return_value_policy::reference);\n\n    // Returns an eigen slice of even columns\n    m.def(\n        \"even_cols\",\n        [](py::EigenDRef<Eigen::MatrixXd> m) {\n            return py::EigenDMap<Eigen::MatrixXd>(\n                m.data(),\n                m.rows(),\n                (m.cols() + 1) / 2,\n                py::EigenDStride(2 * m.outerStride(), m.innerStride()));\n        },\n        py::return_value_policy::reference);\n\n    // Returns diagonals: a vector-like object with an inner stride != 1\n    m.def(\"diagonal\", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });\n    m.def(\"diagonal_1\",\n          [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });\n    m.def(\"diagonal_n\",\n          [](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });\n\n    // Return a block of a matrix (gives non-standard strides)\n    m.def(\"block\",\n          [m](const py::object &x_obj,\n              int start_row,\n              int start_col,\n              int block_rows,\n              int block_cols) {\n              return m.attr(\"_block\")(x_obj, x_obj, start_row, start_col, block_rows, block_cols);\n          });\n\n    m.def(\n        \"_block\",\n        [](const py::object &x_obj,\n           const Eigen::Ref<const Eigen::MatrixXd> &x,\n           int start_row,\n           int start_col,\n           int block_rows,\n           int block_cols) {\n            // See PR #4217 for background. This test is a bit over the top, but might be useful\n            // as a concrete example to point to when explaining the dangling reference trap.\n            auto i0 = py::make_tuple(0, 0);\n            auto x0_orig = x_obj[*i0].cast<double>();\n            if (x(0, 0) != x0_orig) {\n                throw std::runtime_error(\n                    \"Something in the type_caster for Eigen::Ref is terribly wrong.\");\n            }\n            double x0_mod = x0_orig + 1;\n            x_obj[*i0] = x0_mod;\n            auto copy_detected = (x(0, 0) != x0_mod);\n            x_obj[*i0] = x0_orig;\n            if (copy_detected) {\n                throw std::runtime_error(\"type_caster for Eigen::Ref made a copy.\");\n            }\n            return x.block(start_row, start_col, block_rows, block_cols);\n        },\n        py::keep_alive<0, 1>());\n\n    // test_eigen_return_references, test_eigen_keepalive\n    // return value referencing/copying tests:\n    class ReturnTester {\n        Eigen::MatrixXd mat = create();\n\n    public:\n        ReturnTester() { print_created(this); }\n        ReturnTester(const ReturnTester &) = default;\n        ~ReturnTester() { print_destroyed(this); }\n        static Eigen::MatrixXd create() { return Eigen::MatrixXd::Ones(10, 10); }\n        // NOLINTNEXTLINE(readability-const-return-type)\n        static const Eigen::MatrixXd createConst() { return Eigen::MatrixXd::Ones(10, 10); }\n        Eigen::MatrixXd &get() { return mat; }\n        Eigen::MatrixXd *getPtr() { return &mat; }\n        const Eigen::MatrixXd &view() { return mat; }\n        const Eigen::MatrixXd *viewPtr() { return &mat; }\n        Eigen::Ref<Eigen::MatrixXd> ref() { return mat; }\n        Eigen::Ref<const Eigen::MatrixXd> refConst() { return mat; }\n        Eigen::Block<Eigen::MatrixXd> block(int r, int c, int nrow, int ncol) {\n            return mat.block(r, c, nrow, ncol);\n        }\n        Eigen::Block<const Eigen::MatrixXd> blockConst(int r, int c, int nrow, int ncol) const {\n            return mat.block(r, c, nrow, ncol);\n        }\n        py::EigenDMap<Eigen::Matrix2d> corners() {\n            return py::EigenDMap<Eigen::Matrix2d>(\n                mat.data(),\n                py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),\n                                 mat.innerStride() * (mat.innerSize() - 1)));\n        }\n        py::EigenDMap<const Eigen::Matrix2d> cornersConst() const {\n            return py::EigenDMap<const Eigen::Matrix2d>(\n                mat.data(),\n                py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),\n                                 mat.innerStride() * (mat.innerSize() - 1)));\n        }\n    };\n    using rvp = py::return_value_policy;\n    py::class_<ReturnTester>(m, \"ReturnTester\")\n        .def(py::init<>())\n        .def_static(\"create\", &ReturnTester::create)\n        .def_static(\"create_const\", &ReturnTester::createConst)\n        .def(\"get\", &ReturnTester::get, rvp::reference_internal)\n        .def(\"get_ptr\", &ReturnTester::getPtr, rvp::reference_internal)\n        .def(\"view\", &ReturnTester::view, rvp::reference_internal)\n        .def(\"view_ptr\", &ReturnTester::view, rvp::reference_internal)\n        .def(\"copy_get\", &ReturnTester::get)       // Default rvp: copy\n        .def(\"copy_view\", &ReturnTester::view)     //         \"\n        .def(\"ref\", &ReturnTester::ref)            // Default for Ref is to reference\n        .def(\"ref_const\", &ReturnTester::refConst) // Likewise, but const\n        .def(\"ref_safe\", &ReturnTester::ref, rvp::reference_internal)\n        .def(\"ref_const_safe\", &ReturnTester::refConst, rvp::reference_internal)\n        .def(\"copy_ref\", &ReturnTester::ref, rvp::copy)\n        .def(\"copy_ref_const\", &ReturnTester::refConst, rvp::copy)\n        .def(\"block\", &ReturnTester::block)\n        .def(\"block_safe\", &ReturnTester::block, rvp::reference_internal)\n        .def(\"block_const\", &ReturnTester::blockConst, rvp::reference_internal)\n        .def(\"copy_block\", &ReturnTester::block, rvp::copy)\n        .def(\"corners\", &ReturnTester::corners, rvp::reference_internal)\n        .def(\"corners_const\", &ReturnTester::cornersConst, rvp::reference_internal);\n\n    // test_special_matrix_objects\n    // Returns a DiagonalMatrix with diagonal (1,2,3,...)\n    m.def(\"incr_diag\", [](int k) {\n        Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);\n        for (int i = 0; i < k; i++) {\n            m.diagonal()[i] = i + 1;\n        }\n        return m;\n    });\n\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_lower\",\n          [](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Lower>(); });\n    // Returns a SelfAdjointView referencing the lower triangle of m\n    m.def(\"symmetric_upper\",\n          [](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Upper>(); });\n\n    // Test matrix for various functions below.\n    Eigen::MatrixXf mat(5, 6);\n    mat << 0, 3, 0, 0, 0, 11, 22, 0, 0, 0, 17, 11, 7, 5, 0, 1, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 14,\n        0, 8, 11;\n\n    // test_fixed, and various other tests\n    m.def(\"fixed_r\", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); });\n    // Our Eigen does a hack which respects constness through the numpy writeable flag.\n    // Therefore, the const return actually affects this type despite being an rvalue.\n    // NOLINTNEXTLINE(readability-const-return-type)\n    m.def(\"fixed_r_const\", [mat]() -> const FixedMatrixR { return FixedMatrixR(mat); });\n    m.def(\"fixed_c\", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); });\n    m.def(\"fixed_copy_r\", [](const FixedMatrixR &m) -> FixedMatrixR { return m; });\n    m.def(\"fixed_copy_c\", [](const FixedMatrixC &m) -> FixedMatrixC { return m; });\n    // test_mutator_descriptors\n    m.def(\"fixed_mutator_r\", [](const Eigen::Ref<FixedMatrixR> &) {});\n    m.def(\"fixed_mutator_c\", [](const Eigen::Ref<FixedMatrixC> &) {});\n    m.def(\"fixed_mutator_a\", [](const py::EigenDRef<FixedMatrixC> &) {});\n    // test_dense\n    m.def(\"dense_r\", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); });\n    m.def(\"dense_c\", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); });\n    m.def(\"dense_copy_r\", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });\n    m.def(\"dense_copy_c\", [](const DenseMatrixC &m) -> DenseMatrixC { return m; });\n    // test_defaults\n    bool have_numpy = true;\n    try {\n        py::module_::import(\"numpy\");\n    } catch (const py::error_already_set &) {\n        have_numpy = false;\n    }\n    if (have_numpy) {\n        py::module_::import(\"numpy\");\n        Eigen::Matrix<double, 3, 3> defaultMatrix = Eigen::Matrix3d::Identity();\n        m.def(\"defaults_mat\", [](const Eigen::Matrix3d &) {}, py::arg(\"mat\") = defaultMatrix);\n\n        Eigen::VectorXd defaultVector = Eigen::VectorXd::Ones(32);\n        m.def(\"defaults_vec\", [](const Eigen::VectorXd &) {}, py::arg(\"vec\") = defaultMatrix);\n    }\n    // test_sparse, test_sparse_signature\n    m.def(\"sparse_r\", [mat]() -> SparseMatrixR {\n        // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)\n        return Eigen::SparseView<Eigen::MatrixXf>(mat);\n    });\n    m.def(\"sparse_c\",\n          [mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); });\n    m.def(\"sparse_copy_r\", [](const SparseMatrixR &m) -> SparseMatrixR { return m; });\n    m.def(\"sparse_copy_c\", [](const SparseMatrixC &m) -> SparseMatrixC { return m; });\n    // test_partially_fixed\n    m.def(\"partial_copy_four_rm_r\", [](const FourRowMatrixR &m) -> FourRowMatrixR { return m; });\n    m.def(\"partial_copy_four_rm_c\", [](const FourColMatrixR &m) -> FourColMatrixR { return m; });\n    m.def(\"partial_copy_four_cm_r\", [](const FourRowMatrixC &m) -> FourRowMatrixC { return m; });\n    m.def(\"partial_copy_four_cm_c\", [](const FourColMatrixC &m) -> FourColMatrixC { return m; });\n\n    // test_cpp_casting\n    // Test that we can cast a numpy object to a Eigen::MatrixXd explicitly\n    m.def(\"cpp_copy\", [](py::handle m) { return m.cast<Eigen::MatrixXd>()(1, 0); });\n    m.def(\"cpp_ref_c\", [](py::handle m) { return m.cast<Eigen::Ref<Eigen::MatrixXd>>()(1, 0); });\n    m.def(\"cpp_ref_r\", [](py::handle m) { return m.cast<Eigen::Ref<MatrixXdR>>()(1, 0); });\n    m.def(\"cpp_ref_any\",\n          [](py::handle m) { return m.cast<py::EigenDRef<Eigen::MatrixXd>>()(1, 0); });\n\n    // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.\n\n    // test_nocopy_wrapper\n    // Test that we can prevent copying into an argument that would normally copy: First a version\n    // that would allow copying (if types or strides don't match) for comparison:\n    m.def(\"get_elem\", &get_elem);\n    // Now this alternative that calls the tells pybind to fail rather than copy:\n    m.def(\n        \"get_elem_nocopy\",\n        [](const Eigen::Ref<const Eigen::MatrixXd> &m) -> double { return get_elem(m); },\n        py::arg{}.noconvert());\n    // Also test a row-major-only no-copy const ref:\n    m.def(\n        \"get_elem_rm_nocopy\",\n        [](Eigen::Ref<const Eigen::Matrix<long, -1, -1, Eigen::RowMajor>> &m) -> long {\n            return m(2, 1);\n        },\n        py::arg{}.noconvert());\n\n    // test_issue738, test_zero_length\n    // Issue #738: 1×N or N×1 2D matrices were neither accepted nor properly copied with an\n    // incompatible stride value on the length-1 dimension--but that should be allowed (without\n    // requiring a copy!) because the stride value can be safely ignored on a size-1 dimension.\n    // Similarly, 0×N or N×0 matrices were not accepted--again, these should be allowed since\n    // they contain no data. This particularly affects numpy ≥ 1.23, which sets the strides to\n    // 0 if any dimension size is 0.\n    m.def(\"iss738_f1\",\n          &adjust_matrix<const Eigen::Ref<const Eigen::MatrixXd> &>,\n          py::arg{}.noconvert());\n    m.def(\"iss738_f2\",\n          &adjust_matrix<const Eigen::Ref<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> &>,\n          py::arg{}.noconvert());\n\n    // test_issue1105\n    // Issue #1105: when converting from a numpy two-dimensional (Nx1) or (1xN) value into a dense\n    // eigen Vector or RowVector, the argument would fail to load because the numpy copy would\n    // fail: numpy won't broadcast a Nx1 into a 1-dimensional vector.\n    m.def(\"iss1105_col\", [](const Eigen::VectorXd &) { return true; });\n    m.def(\"iss1105_row\", [](const Eigen::RowVectorXd &) { return true; });\n\n    // test_named_arguments\n    // Make sure named arguments are working properly:\n    m.def(\n        \"matrix_multiply\",\n        [](const py::EigenDRef<const Eigen::MatrixXd> &A,\n           const py::EigenDRef<const Eigen::MatrixXd> &B) -> Eigen::MatrixXd {\n            if (A.cols() != B.rows()) {\n                throw std::domain_error(\"Nonconformable matrices!\");\n            }\n            return A * B;\n        },\n        py::arg(\"A\"),\n        py::arg(\"B\"));\n\n    // test_custom_operator_new\n    py::class_<CustomOperatorNew>(m, \"CustomOperatorNew\")\n        .def(py::init<>())\n        .def_readonly(\"a\", &CustomOperatorNew::a)\n        .def_readonly(\"b\", &CustomOperatorNew::b);\n\n    // test_eigen_ref_life_support\n    // In case of a failure (the caster's temp array does not live long enough), creating\n    // a new array (np.ones(10)) increases the chances that the temp array will be garbage\n    // collected and/or that its memory will be overridden with different values.\n    m.def(\"get_elem_direct\", [](const Eigen::Ref<const Eigen::VectorXd> &v) {\n        py::module_::import(\"numpy\").attr(\"ones\")(10);\n        return v(5);\n    });\n    m.def(\"get_elem_indirect\", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {\n        py::module_::import(\"numpy\").attr(\"ones\")(10);\n        return v[0](5);\n    });\n    m.def(\"round_trip_vector\", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return x; });\n    m.def(\"round_trip_dense\", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });\n    m.def(\"round_trip_dense_ref\",\n          [](const Eigen::Ref<DenseMatrixR> &m) -> Eigen::Ref<DenseMatrixR> { return m; });\n}\n"
  },
  {
    "path": "tests/test_eigen_matrix.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import ConstructorStats\n\nnp = pytest.importorskip(\"numpy\")\nm = pytest.importorskip(\"pybind11_tests.eigen_matrix\")\n\n\nref = np.array(\n    [\n        [0.0, 3, 0, 0, 0, 11],\n        [22, 0, 0, 0, 17, 11],\n        [7, 5, 0, 1, 0, 11],\n        [0, 0, 0, 0, 0, 11],\n        [0, 0, 14, 0, 8, 11],\n    ]\n)\n\n\ndef assert_equal_ref(mat):\n    np.testing.assert_array_equal(mat, ref)\n\n\ndef assert_sparse_equal_ref(sparse_mat):\n    assert_equal_ref(sparse_mat.toarray())\n\n\ndef test_fixed():\n    assert_equal_ref(m.fixed_c())\n    assert_equal_ref(m.fixed_r())\n    assert_equal_ref(m.fixed_copy_r(m.fixed_r()))\n    assert_equal_ref(m.fixed_copy_c(m.fixed_c()))\n    assert_equal_ref(m.fixed_copy_r(m.fixed_c()))\n    assert_equal_ref(m.fixed_copy_c(m.fixed_r()))\n\n\ndef test_dense():\n    assert_equal_ref(m.dense_r())\n    assert_equal_ref(m.dense_c())\n    assert_equal_ref(m.dense_copy_r(m.dense_r()))\n    assert_equal_ref(m.dense_copy_c(m.dense_c()))\n    assert_equal_ref(m.dense_copy_r(m.dense_c()))\n    assert_equal_ref(m.dense_copy_c(m.dense_r()))\n\n\ndef test_partially_fixed():\n    ref2 = np.array([[0.0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])\n    np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2), ref2)\n    np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2), ref2)\n    np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2[:, 1]), ref2[:, [1]])\n    np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2[0, :]), ref2[[0], :])\n    np.testing.assert_array_equal(\n        m.partial_copy_four_rm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]\n    )\n    np.testing.assert_array_equal(\n        m.partial_copy_four_rm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]\n    )\n\n    np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2), ref2)\n    np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2), ref2)\n    np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2[:, 1]), ref2[:, [1]])\n    np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2[0, :]), ref2[[0], :])\n    np.testing.assert_array_equal(\n        m.partial_copy_four_cm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]\n    )\n    np.testing.assert_array_equal(\n        m.partial_copy_four_cm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]\n    )\n\n    # TypeError should be raise for a shape mismatch\n    functions = [\n        m.partial_copy_four_rm_r,\n        m.partial_copy_four_rm_c,\n        m.partial_copy_four_cm_r,\n        m.partial_copy_four_cm_c,\n    ]\n    matrix_with_wrong_shape = [[1, 2], [3, 4]]\n    for f in functions:\n        with pytest.raises(TypeError) as excinfo:\n            f(matrix_with_wrong_shape)\n        assert \"incompatible function arguments\" in str(excinfo.value)\n\n\ndef test_mutator_descriptors():\n    zr = np.arange(30, dtype=\"float32\").reshape(5, 6)  # row-major\n    zc = zr.reshape(6, 5).transpose()  # column-major\n\n    m.fixed_mutator_r(zr)\n    m.fixed_mutator_c(zc)\n    m.fixed_mutator_a(zr)\n    m.fixed_mutator_a(zc)\n    with pytest.raises(TypeError) as excinfo:\n        m.fixed_mutator_r(zc)\n    assert (\n        '(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[5, 6]\",'\n        ' \"flags.writeable\", \"flags.c_contiguous\"]) -> None' in str(excinfo.value)\n    )\n    with pytest.raises(TypeError) as excinfo:\n        m.fixed_mutator_c(zr)\n    assert (\n        '(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[5, 6]\",'\n        ' \"flags.writeable\", \"flags.f_contiguous\"]) -> None' in str(excinfo.value)\n    )\n    with pytest.raises(TypeError) as excinfo:\n        m.fixed_mutator_a(np.array([[1, 2], [3, 4]], dtype=\"float32\"))\n    assert (\n        '(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[5, 6]\", \"flags.writeable\"]) -> None'\n        in str(excinfo.value)\n    )\n    zr.flags.writeable = False\n    with pytest.raises(TypeError):\n        m.fixed_mutator_r(zr)\n    with pytest.raises(TypeError):\n        m.fixed_mutator_a(zr)\n\n\ndef test_cpp_casting():\n    assert m.cpp_copy(m.fixed_r()) == 22.0\n    assert m.cpp_copy(m.fixed_c()) == 22.0\n    z = np.array([[5.0, 6], [7, 8]])\n    assert m.cpp_copy(z) == 7.0\n    assert m.cpp_copy(m.get_cm_ref()) == 21.0\n    assert m.cpp_copy(m.get_rm_ref()) == 21.0\n    assert m.cpp_ref_c(m.get_cm_ref()) == 21.0\n    assert m.cpp_ref_r(m.get_rm_ref()) == 21.0\n    with pytest.raises(RuntimeError) as excinfo:\n        # Can't reference m.fixed_c: it contains floats, m.cpp_ref_any wants doubles\n        m.cpp_ref_any(m.fixed_c())\n    assert \"Unable to cast Python instance\" in str(excinfo.value)\n    with pytest.raises(RuntimeError) as excinfo:\n        # Can't reference m.fixed_r: it contains floats, m.cpp_ref_any wants doubles\n        m.cpp_ref_any(m.fixed_r())\n    assert \"Unable to cast Python instance\" in str(excinfo.value)\n    assert m.cpp_ref_any(m.ReturnTester.create()) == 1.0\n\n    assert m.cpp_ref_any(m.get_cm_ref()) == 21.0\n    assert m.cpp_ref_any(m.get_cm_ref()) == 21.0\n\n\ndef test_pass_readonly_array():\n    z = np.full((5, 6), 42.0)\n    z.flags.writeable = False\n    np.testing.assert_array_equal(z, m.fixed_copy_r(z))\n    np.testing.assert_array_equal(m.fixed_r_const(), m.fixed_r())\n    assert not m.fixed_r_const().flags.writeable\n    np.testing.assert_array_equal(m.fixed_copy_r(m.fixed_r_const()), m.fixed_r_const())\n\n\ndef test_nonunit_stride_from_python():\n    counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))\n    second_row = counting_mat[1, :]\n    second_col = counting_mat[:, 1]\n    np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)\n    np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)\n    np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)\n\n    counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))\n    slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]\n    for ref_mat in slices:\n        np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)\n        np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)\n\n    # Mutator:\n    m.double_threer(second_row)\n    m.double_threec(second_col)\n    np.testing.assert_array_equal(counting_mat, [[0.0, 2, 2], [6, 16, 10], [6, 14, 8]])\n\n\ndef test_negative_stride_from_python(msg):\n    \"\"\"Eigen doesn't support (as of yet) negative strides. When a function takes an Eigen matrix by\n    copy or const reference, we can pass a numpy array that has negative strides.  Otherwise, an\n    exception will be thrown as Eigen will not be able to map the numpy array.\"\"\"\n\n    counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))\n    counting_mat = counting_mat[::-1, ::-1]\n    second_row = counting_mat[1, :]\n    second_col = counting_mat[:, 1]\n    np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)\n    np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)\n    np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)\n    np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)\n\n    counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))\n    counting_3d = counting_3d[::-1, ::-1, ::-1]\n    slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]\n    for ref_mat in slices:\n        np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)\n        np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)\n\n    # Mutator:\n    with pytest.raises(TypeError) as excinfo:\n        m.double_threer(second_row)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        double_threer(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[1, 3]\", \"flags.writeable\"]) -> None\n\n        Invoked with: \"\"\"\n        + repr(np.array([5.0, 4.0, 3.0], dtype=\"float32\"))\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        m.double_threec(second_col)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        double_threec(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[3, 1]\", \"flags.writeable\"]) -> None\n\n        Invoked with: \"\"\"\n        + repr(np.array([7.0, 4.0, 1.0], dtype=\"float32\"))\n    )\n\n\ndef test_block_runtime_error_type_caster_eigen_ref_made_a_copy():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.block(ref, 0, 0, 0, 0)\n    assert str(excinfo.value) == \"type_caster for Eigen::Ref made a copy.\"\n\n\ndef test_nonunit_stride_to_python():\n    assert np.all(m.diagonal(ref) == ref.diagonal())\n    assert np.all(m.diagonal_1(ref) == ref.diagonal(1))\n    for i in range(-5, 7):\n        assert np.all(m.diagonal_n(ref, i) == ref.diagonal(i)), f\"m.diagonal_n({i})\"\n\n    # Must be order=\"F\", otherwise the type_caster will make a copy and\n    # m.block() will return a dangling reference (heap-use-after-free).\n    rof = np.asarray(ref, order=\"F\")\n    assert np.all(m.block(rof, 2, 1, 3, 3) == rof[2:5, 1:4])\n    assert np.all(m.block(rof, 1, 4, 4, 2) == rof[1:, 4:])\n    assert np.all(m.block(rof, 1, 4, 3, 2) == rof[1:4, 4:])\n\n\ndef test_eigen_ref_to_python():\n    chols = [m.cholesky1, m.cholesky2, m.cholesky3, m.cholesky4]\n    for i, chol in enumerate(chols, start=1):\n        mymat = chol(np.array([[1.0, 2, 4], [2, 13, 23], [4, 23, 77]]))\n        assert np.all(mymat == np.array([[1, 0, 0], [2, 3, 0], [4, 5, 6]])), (\n            f\"cholesky{i}\"\n        )\n\n\ndef assign_both(a1, a2, r, c, v):\n    a1[r, c] = v\n    a2[r, c] = v\n\n\ndef array_copy_but_one(a, r, c, v):\n    z = np.array(a, copy=True)\n    z[r, c] = v\n    return z\n\n\ndef test_eigen_return_references():\n    \"\"\"Tests various ways of returning references and non-referencing copies\"\"\"\n\n    primary = np.ones((10, 10))\n    a = m.ReturnTester()\n    a_get1 = a.get()\n    assert not a_get1.flags.owndata\n    assert a_get1.flags.writeable\n    assign_both(a_get1, primary, 3, 3, 5)\n    a_get2 = a.get_ptr()\n    assert not a_get2.flags.owndata\n    assert a_get2.flags.writeable\n    assign_both(a_get1, primary, 2, 3, 6)\n\n    a_view1 = a.view()\n    assert not a_view1.flags.owndata\n    assert not a_view1.flags.writeable\n    with pytest.raises(ValueError):\n        a_view1[2, 3] = 4\n    a_view2 = a.view_ptr()\n    assert not a_view2.flags.owndata\n    assert not a_view2.flags.writeable\n    with pytest.raises(ValueError):\n        a_view2[2, 3] = 4\n\n    a_copy1 = a.copy_get()\n    assert a_copy1.flags.owndata\n    assert a_copy1.flags.writeable\n    np.testing.assert_array_equal(a_copy1, primary)\n    a_copy1[7, 7] = -44  # Shouldn't affect anything else\n    c1want = array_copy_but_one(primary, 7, 7, -44)\n    a_copy2 = a.copy_view()\n    assert a_copy2.flags.owndata\n    assert a_copy2.flags.writeable\n    np.testing.assert_array_equal(a_copy2, primary)\n    a_copy2[4, 4] = -22  # Shouldn't affect anything else\n    c2want = array_copy_but_one(primary, 4, 4, -22)\n\n    a_ref1 = a.ref()\n    assert not a_ref1.flags.owndata\n    assert a_ref1.flags.writeable\n    assign_both(a_ref1, primary, 1, 1, 15)\n    a_ref2 = a.ref_const()\n    assert not a_ref2.flags.owndata\n    assert not a_ref2.flags.writeable\n    with pytest.raises(ValueError):\n        a_ref2[5, 5] = 33\n    a_ref3 = a.ref_safe()\n    assert not a_ref3.flags.owndata\n    assert a_ref3.flags.writeable\n    assign_both(a_ref3, primary, 0, 7, 99)\n    a_ref4 = a.ref_const_safe()\n    assert not a_ref4.flags.owndata\n    assert not a_ref4.flags.writeable\n    with pytest.raises(ValueError):\n        a_ref4[7, 0] = 987654321\n\n    a_copy3 = a.copy_ref()\n    assert a_copy3.flags.owndata\n    assert a_copy3.flags.writeable\n    np.testing.assert_array_equal(a_copy3, primary)\n    a_copy3[8, 1] = 11\n    c3want = array_copy_but_one(primary, 8, 1, 11)\n    a_copy4 = a.copy_ref_const()\n    assert a_copy4.flags.owndata\n    assert a_copy4.flags.writeable\n    np.testing.assert_array_equal(a_copy4, primary)\n    a_copy4[8, 4] = 88\n    c4want = array_copy_but_one(primary, 8, 4, 88)\n\n    a_block1 = a.block(3, 3, 2, 2)\n    assert not a_block1.flags.owndata\n    assert a_block1.flags.writeable\n    a_block1[0, 0] = 55\n    primary[3, 3] = 55\n    a_block2 = a.block_safe(2, 2, 3, 2)\n    assert not a_block2.flags.owndata\n    assert a_block2.flags.writeable\n    a_block2[2, 1] = -123\n    primary[4, 3] = -123\n    a_block3 = a.block_const(6, 7, 4, 3)\n    assert not a_block3.flags.owndata\n    assert not a_block3.flags.writeable\n    with pytest.raises(ValueError):\n        a_block3[2, 2] = -44444\n\n    a_copy5 = a.copy_block(2, 2, 2, 3)\n    assert a_copy5.flags.owndata\n    assert a_copy5.flags.writeable\n    np.testing.assert_array_equal(a_copy5, primary[2:4, 2:5])\n    a_copy5[1, 1] = 777\n    c5want = array_copy_but_one(primary[2:4, 2:5], 1, 1, 777)\n\n    a_corn1 = a.corners()\n    assert not a_corn1.flags.owndata\n    assert a_corn1.flags.writeable\n    a_corn1 *= 50\n    a_corn1[1, 1] = 999\n    primary[0, 0] = 50\n    primary[0, 9] = 50\n    primary[9, 0] = 50\n    primary[9, 9] = 999\n    a_corn2 = a.corners_const()\n    assert not a_corn2.flags.owndata\n    assert not a_corn2.flags.writeable\n    with pytest.raises(ValueError):\n        a_corn2[1, 0] = 51\n\n    # All of the changes made all the way along should be visible everywhere\n    # now (except for the copies, of course)\n    np.testing.assert_array_equal(a_get1, primary)\n    np.testing.assert_array_equal(a_get2, primary)\n    np.testing.assert_array_equal(a_view1, primary)\n    np.testing.assert_array_equal(a_view2, primary)\n    np.testing.assert_array_equal(a_ref1, primary)\n    np.testing.assert_array_equal(a_ref2, primary)\n    np.testing.assert_array_equal(a_ref3, primary)\n    np.testing.assert_array_equal(a_ref4, primary)\n    np.testing.assert_array_equal(a_block1, primary[3:5, 3:5])\n    np.testing.assert_array_equal(a_block2, primary[2:5, 2:4])\n    np.testing.assert_array_equal(a_block3, primary[6:10, 7:10])\n    np.testing.assert_array_equal(\n        a_corn1, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]\n    )\n    np.testing.assert_array_equal(\n        a_corn2, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]\n    )\n\n    np.testing.assert_array_equal(a_copy1, c1want)\n    np.testing.assert_array_equal(a_copy2, c2want)\n    np.testing.assert_array_equal(a_copy3, c3want)\n    np.testing.assert_array_equal(a_copy4, c4want)\n    np.testing.assert_array_equal(a_copy5, c5want)\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef assert_keeps_alive(cl, method, *args):\n    cstats = ConstructorStats.get(cl)\n    start_with = cstats.alive()\n    a = cl()\n    assert cstats.alive() == start_with + 1\n    z = method(a, *args)\n    assert cstats.alive() == start_with + 1\n    del a\n    # Here's the keep alive in action:\n    assert cstats.alive() == start_with + 1\n    del z\n    # Keep alive should have expired:\n    assert cstats.alive() == start_with\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_eigen_keepalive():\n    a = m.ReturnTester()\n    cstats = ConstructorStats.get(m.ReturnTester)\n    assert cstats.alive() == 1\n    unsafe = [a.ref(), a.ref_const(), a.block(1, 2, 3, 4)]\n    copies = [\n        a.copy_get(),\n        a.copy_view(),\n        a.copy_ref(),\n        a.copy_ref_const(),\n        a.copy_block(4, 3, 2, 1),\n    ]\n    del a\n    assert cstats.alive() == 0\n    del unsafe\n    del copies\n\n    for meth in [\n        m.ReturnTester.get,\n        m.ReturnTester.get_ptr,\n        m.ReturnTester.view,\n        m.ReturnTester.view_ptr,\n        m.ReturnTester.ref_safe,\n        m.ReturnTester.ref_const_safe,\n        m.ReturnTester.corners,\n        m.ReturnTester.corners_const,\n    ]:\n        assert_keeps_alive(m.ReturnTester, meth)\n\n    for meth in [m.ReturnTester.block_safe, m.ReturnTester.block_const]:\n        assert_keeps_alive(m.ReturnTester, meth, 4, 3, 2, 1)\n\n\ndef test_eigen_ref_mutators():\n    \"\"\"Tests Eigen's ability to mutate numpy values\"\"\"\n\n    orig = np.array([[1.0, 2, 3], [4, 5, 6], [7, 8, 9]])\n    zr = np.array(orig)\n    zc = np.array(orig, order=\"F\")\n    m.add_rm(zr, 1, 0, 100)\n    assert np.all(zr == np.array([[1.0, 2, 3], [104, 5, 6], [7, 8, 9]]))\n    m.add_cm(zc, 1, 0, 200)\n    assert np.all(zc == np.array([[1.0, 2, 3], [204, 5, 6], [7, 8, 9]]))\n\n    m.add_any(zr, 1, 0, 20)\n    assert np.all(zr == np.array([[1.0, 2, 3], [124, 5, 6], [7, 8, 9]]))\n    m.add_any(zc, 1, 0, 10)\n    assert np.all(zc == np.array([[1.0, 2, 3], [214, 5, 6], [7, 8, 9]]))\n\n    # Can't reference a col-major array with a row-major Ref, and vice versa:\n    with pytest.raises(TypeError):\n        m.add_rm(zc, 1, 0, 1)\n    with pytest.raises(TypeError):\n        m.add_cm(zr, 1, 0, 1)\n\n    # Overloads:\n    m.add1(zr, 1, 0, -100)\n    m.add2(zr, 1, 0, -20)\n    assert np.all(zr == orig)\n    m.add1(zc, 1, 0, -200)\n    m.add2(zc, 1, 0, -10)\n    assert np.all(zc == orig)\n\n    # a non-contiguous slice (this won't work on either the row- or\n    # column-contiguous refs, but should work for the any)\n    cornersr = zr[0::2, 0::2]\n    cornersc = zc[0::2, 0::2]\n\n    assert np.all(cornersr == np.array([[1.0, 3], [7, 9]]))\n    assert np.all(cornersc == np.array([[1.0, 3], [7, 9]]))\n\n    with pytest.raises(TypeError):\n        m.add_rm(cornersr, 0, 1, 25)\n    with pytest.raises(TypeError):\n        m.add_cm(cornersr, 0, 1, 25)\n    with pytest.raises(TypeError):\n        m.add_rm(cornersc, 0, 1, 25)\n    with pytest.raises(TypeError):\n        m.add_cm(cornersc, 0, 1, 25)\n    m.add_any(cornersr, 0, 1, 25)\n    m.add_any(cornersc, 0, 1, 44)\n    assert np.all(zr == np.array([[1.0, 2, 28], [4, 5, 6], [7, 8, 9]]))\n    assert np.all(zc == np.array([[1.0, 2, 47], [4, 5, 6], [7, 8, 9]]))\n\n    # You shouldn't be allowed to pass a non-writeable array to a mutating Eigen method:\n    zro = zr[0:4, 0:4]\n    zro.flags.writeable = False\n    with pytest.raises(TypeError):\n        m.add_rm(zro, 0, 0, 0)\n    with pytest.raises(TypeError):\n        m.add_any(zro, 0, 0, 0)\n    with pytest.raises(TypeError):\n        m.add1(zro, 0, 0, 0)\n    with pytest.raises(TypeError):\n        m.add2(zro, 0, 0, 0)\n\n    # integer array shouldn't be passable to a double-matrix-accepting mutating func:\n    zi = np.array([[1, 2], [3, 4]])\n    with pytest.raises(TypeError):\n        m.add_rm(zi)\n\n\ndef test_numpy_ref_mutators():\n    \"\"\"Tests numpy mutating Eigen matrices (for returned Eigen::Ref<...>s)\"\"\"\n\n    m.reset_refs()  # In case another test already changed it\n\n    zc = m.get_cm_ref()\n    zcro = m.get_cm_const_ref()\n    zr = m.get_rm_ref()\n    zrro = m.get_rm_const_ref()\n\n    assert [zc[1, 2], zcro[1, 2], zr[1, 2], zrro[1, 2]] == [23] * 4\n\n    assert not zc.flags.owndata\n    assert zc.flags.writeable\n    assert not zr.flags.owndata\n    assert zr.flags.writeable\n    assert not zcro.flags.owndata\n    assert not zcro.flags.writeable\n    assert not zrro.flags.owndata\n    assert not zrro.flags.writeable\n\n    zc[1, 2] = 99\n    expect = np.array([[11.0, 12, 13], [21, 22, 99], [31, 32, 33]])\n    # We should have just changed zc, of course, but also zcro and the original eigen matrix\n    assert np.all(zc == expect)\n    assert np.all(zcro == expect)\n    assert np.all(m.get_cm_ref() == expect)\n\n    zr[1, 2] = 99\n    assert np.all(zr == expect)\n    assert np.all(zrro == expect)\n    assert np.all(m.get_rm_ref() == expect)\n\n    # Make sure the readonly ones are numpy-readonly:\n    with pytest.raises(ValueError):\n        zcro[1, 2] = 6\n    with pytest.raises(ValueError):\n        zrro[1, 2] = 6\n\n    # We should be able to explicitly copy like this (and since we're copying,\n    # the const should drop away)\n    y1 = np.array(m.get_cm_const_ref())\n\n    assert y1.flags.owndata\n    assert y1.flags.writeable\n    # We should get copies of the eigen data, which was modified above:\n    assert y1[1, 2] == 99\n    y1[1, 2] += 12\n    assert y1[1, 2] == 111\n    assert zc[1, 2] == 99  # Make sure we aren't referencing the original\n\n\ndef test_both_ref_mutators():\n    \"\"\"Tests a complex chain of nested eigen/numpy references\"\"\"\n\n    m.reset_refs()  # In case another test already changed it\n\n    z = m.get_cm_ref()  # numpy -> eigen\n    z[0, 2] -= 3\n    z2 = m.incr_matrix(z, 1)  # numpy -> eigen -> numpy -> eigen\n    z2[1, 1] += 6\n    z3 = m.incr_matrix(z, 2)  # (numpy -> eigen)^3\n    z3[2, 2] += -5\n    z4 = m.incr_matrix(z, 3)  # (numpy -> eigen)^4\n    z4[1, 1] -= 1\n    z5 = m.incr_matrix(z, 4)  # (numpy -> eigen)^5\n    z5[0, 0] = 0\n    assert np.all(z == z2)\n    assert np.all(z == z3)\n    assert np.all(z == z4)\n    assert np.all(z == z5)\n    expect = np.array([[0.0, 22, 20], [31, 37, 33], [41, 42, 38]])\n    assert np.all(z == expect)\n\n    y = np.array(range(100), dtype=\"float64\").reshape(10, 10)\n    y2 = m.incr_matrix_any(y, 10)  # np -> eigen -> np\n    y3 = m.incr_matrix_any(\n        y2[0::2, 0::2], -33\n    )  # np -> eigen -> np slice -> np -> eigen -> np\n    y4 = m.even_rows(y3)  # numpy -> eigen slice -> (... y3)\n    y5 = m.even_cols(y4)  # numpy -> eigen slice -> (... y4)\n    y6 = m.incr_matrix_any(y5, 1000)  # numpy -> eigen -> (... y5)\n\n    # Apply same mutations using just numpy:\n    yexpect = np.array(range(100), dtype=\"float64\").reshape(10, 10)\n    yexpect += 10\n    yexpect[0::2, 0::2] -= 33\n    yexpect[0::4, 0::4] += 1000\n    assert np.all(y6 == yexpect[0::4, 0::4])\n    assert np.all(y5 == yexpect[0::4, 0::4])\n    assert np.all(y4 == yexpect[0::4, 0::2])\n    assert np.all(y3 == yexpect[0::2, 0::2])\n    assert np.all(y2 == yexpect)\n    assert np.all(y == yexpect)\n\n\ndef test_nocopy_wrapper():\n    # get_elem requires a column-contiguous matrix reference, but should be\n    # callable with other types of matrix (via copying):\n    int_matrix_colmajor = np.array(\n        [[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=\"l\", order=\"F\"\n    )\n    dbl_matrix_colmajor = np.array(\n        int_matrix_colmajor, dtype=\"double\", order=\"F\", copy=True\n    )\n    int_matrix_rowmajor = np.array(int_matrix_colmajor, order=\"C\", copy=True)\n    dbl_matrix_rowmajor = np.array(\n        int_matrix_rowmajor, dtype=\"double\", order=\"C\", copy=True\n    )\n\n    # All should be callable via get_elem:\n    assert m.get_elem(int_matrix_colmajor) == 8\n    assert m.get_elem(dbl_matrix_colmajor) == 8\n    assert m.get_elem(int_matrix_rowmajor) == 8\n    assert m.get_elem(dbl_matrix_rowmajor) == 8\n\n    # All but the second should fail with m.get_elem_nocopy:\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_nocopy(int_matrix_colmajor)\n    assert \"get_elem_nocopy(): incompatible function arguments.\" in str(excinfo.value)\n    assert ', \"flags.f_contiguous\"' in str(excinfo.value)\n    assert m.get_elem_nocopy(dbl_matrix_colmajor) == 8\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_nocopy(int_matrix_rowmajor)\n    assert \"get_elem_nocopy(): incompatible function arguments.\" in str(excinfo.value)\n    assert ', \"flags.f_contiguous\"' in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_nocopy(dbl_matrix_rowmajor)\n    assert \"get_elem_nocopy(): incompatible function arguments.\" in str(excinfo.value)\n    assert ', \"flags.f_contiguous\"' in str(excinfo.value)\n\n    # For the row-major test, we take a long matrix in row-major, so only the third is allowed:\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_rm_nocopy(int_matrix_colmajor)\n    assert \"get_elem_rm_nocopy(): incompatible function arguments.\" in str(\n        excinfo.value\n    )\n    assert ', \"flags.c_contiguous\"' in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_rm_nocopy(dbl_matrix_colmajor)\n    assert \"get_elem_rm_nocopy(): incompatible function arguments.\" in str(\n        excinfo.value\n    )\n    assert ', \"flags.c_contiguous\"' in str(excinfo.value)\n    assert m.get_elem_rm_nocopy(int_matrix_rowmajor) == 8\n    with pytest.raises(TypeError) as excinfo:\n        m.get_elem_rm_nocopy(dbl_matrix_rowmajor)\n    assert \"get_elem_rm_nocopy(): incompatible function arguments.\" in str(\n        excinfo.value\n    )\n    assert ', \"flags.c_contiguous\"' in str(excinfo.value)\n\n\ndef test_eigen_ref_life_support():\n    \"\"\"Ensure the lifetime of temporary arrays created by the `Ref` caster\n\n    The `Ref` caster sometimes creates a copy which needs to stay alive. This needs to\n    happen both for directs casts (just the array) or indirectly (e.g. list of arrays).\n    \"\"\"\n\n    a = np.full(shape=10, fill_value=8, dtype=np.int8)\n    assert m.get_elem_direct(a) == 8\n\n    list_of_a = [a]\n    assert m.get_elem_indirect(list_of_a) == 8\n\n\ndef test_special_matrix_objects():\n    assert np.all(m.incr_diag(7) == np.diag([1.0, 2, 3, 4, 5, 6, 7]))\n\n    asymm = np.array([[1.0, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])\n    symm_lower = np.array(asymm)\n    symm_upper = np.array(asymm)\n    for i in range(4):\n        for j in range(i + 1, 4):\n            symm_lower[i, j] = symm_lower[j, i]\n            symm_upper[j, i] = symm_upper[i, j]\n\n    assert np.all(m.symmetric_lower(asymm) == symm_lower)\n    assert np.all(m.symmetric_upper(asymm) == symm_upper)\n\n\ndef test_dense_signature(doc):\n    assert (\n        doc(m.double_col)\n        == \"\"\"\n        double_col(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, \"[m, 1]\"]) -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, 1]\"]\n    \"\"\"\n    )\n    assert (\n        doc(m.double_row)\n        == \"\"\"\n        double_row(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, \"[1, n]\"]) -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[1, n]\"]\n    \"\"\"\n    )\n    assert doc(m.double_complex) == (\n        \"\"\"\n        double_complex(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.complex64, \"[m, 1]\"])\"\"\"\n        \"\"\" -> typing.Annotated[numpy.typing.NDArray[numpy.complex64], \"[m, 1]\"]\n    \"\"\"\n    )\n    assert doc(m.double_mat_rm) == (\n        \"\"\"\n        double_mat_rm(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, \"[m, n]\"])\"\"\"\n        \"\"\" -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, n]\"]\n    \"\"\"\n    )\n\n\ndef test_defaults(doc):\n    assert \"\\n\" not in str(doc(m.defaults_mat))\n    assert \"\\n\" not in str(doc(m.defaults_vec))\n\n\ndef test_named_arguments():\n    a = np.array([[1.0, 2], [3, 4], [5, 6]])\n    b = np.ones((2, 1))\n\n    assert np.all(m.matrix_multiply(a, b) == np.array([[3.0], [7], [11]]))\n    assert np.all(m.matrix_multiply(A=a, B=b) == np.array([[3.0], [7], [11]]))\n    assert np.all(m.matrix_multiply(B=b, A=a) == np.array([[3.0], [7], [11]]))\n\n    with pytest.raises(ValueError) as excinfo:\n        m.matrix_multiply(b, a)\n    assert str(excinfo.value) == \"Nonconformable matrices!\"\n\n    with pytest.raises(ValueError) as excinfo:\n        m.matrix_multiply(A=b, B=a)\n    assert str(excinfo.value) == \"Nonconformable matrices!\"\n\n    with pytest.raises(ValueError) as excinfo:\n        m.matrix_multiply(B=a, A=b)\n    assert str(excinfo.value) == \"Nonconformable matrices!\"\n\n\ndef test_sparse():\n    pytest.importorskip(\"scipy\")\n    assert_sparse_equal_ref(m.sparse_r())\n    assert_sparse_equal_ref(m.sparse_c())\n    assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_r()))\n    assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_c()))\n    assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_c()))\n    assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_r()))\n\n\ndef test_sparse_signature(doc):\n    pytest.importorskip(\"scipy\")\n    assert (\n        doc(m.sparse_copy_r)\n        == \"\"\"\n        sparse_copy_r(arg0: scipy.sparse.csr_matrix[numpy.float32]) -> scipy.sparse.csr_matrix[numpy.float32]\n    \"\"\"\n    )\n    assert (\n        doc(m.sparse_copy_c)\n        == \"\"\"\n        sparse_copy_c(arg0: scipy.sparse.csc_matrix[numpy.float32]) -> scipy.sparse.csc_matrix[numpy.float32]\n    \"\"\"\n    )\n\n\ndef test_issue738():\n    \"\"\"Ignore strides on a length-1 dimension (even if they would be incompatible length > 1)\"\"\"\n    assert np.all(m.iss738_f1(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))\n    assert np.all(\n        m.iss738_f1(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])\n    )\n\n    assert np.all(m.iss738_f2(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))\n    assert np.all(\n        m.iss738_f2(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])\n    )\n\n\n@pytest.mark.parametrize(\"func\", [m.iss738_f1, m.iss738_f2])\n@pytest.mark.parametrize(\"sizes\", [(0, 2), (2, 0)])\ndef test_zero_length(func, sizes):\n    \"\"\"Ignore strides on a length-0 dimension (even if they would be incompatible length > 1)\"\"\"\n    assert np.all(func(np.zeros(sizes)) == np.zeros(sizes))\n\n\ndef test_issue1105():\n    \"\"\"Issue 1105: 1xN or Nx1 input arrays weren't accepted for eigen\n    compile-time row vectors or column vector\"\"\"\n    assert m.iss1105_row(np.ones((1, 7)))\n    assert m.iss1105_col(np.ones((7, 1)))\n\n    # These should still fail (incompatible dimensions):\n    with pytest.raises(TypeError) as excinfo:\n        m.iss1105_row(np.ones((7, 1)))\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.iss1105_col(np.ones((1, 7)))\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n\ndef test_custom_operator_new():\n    \"\"\"Using Eigen types as member variables requires a class-specific\n    operator new with proper alignment\"\"\"\n\n    o = m.CustomOperatorNew()\n    np.testing.assert_allclose(o.a, 0.0)\n    np.testing.assert_allclose(o.b.diagonal(), 1.0)\n\n\ndef test_arraylike_signature(doc):\n    assert doc(m.round_trip_vector) == (\n        'round_trip_vector(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, \"[m, 1]\"])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, 1]\"]'\n    )\n    assert doc(m.round_trip_dense) == (\n        'round_trip_dense(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32, \"[m, n]\"])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, n]\"]'\n    )\n    assert doc(m.round_trip_dense_ref) == (\n        'round_trip_dense_ref(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, n]\", \"flags.writeable\", \"flags.c_contiguous\"])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float32], \"[m, n]\", \"flags.writeable\", \"flags.c_contiguous\"]'\n    )\n    m.round_trip_vector([1.0, 2.0])\n    m.round_trip_dense([[1.0, 2.0], [3.0, 4.0]])\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.round_trip_dense_ref([[1.0, 2.0], [3.0, 4.0]])\n"
  },
  {
    "path": "tests/test_eigen_tensor.cpp",
    "content": "/*\n    tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#define PYBIND11_TEST_EIGEN_TENSOR_NAMESPACE eigen_tensor\n\n#ifdef EIGEN_AVOID_STL_ARRAY\n#    undef EIGEN_AVOID_STL_ARRAY\n#endif\n\n#include \"test_eigen_tensor.inl\"\n\n#include \"pybind11_tests.h\"\n\ntest_initializer egien_tensor(\"eigen_tensor\", eigen_tensor_test::test_module);\n"
  },
  {
    "path": "tests/test_eigen_tensor.inl",
    "content": "/*\n    tests/eigen_tensor.cpp -- automatic conversion of Eigen Tensor\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/eigen/tensor.h>\n\nPYBIND11_NAMESPACE_BEGIN(eigen_tensor_test)\n\nnamespace py = pybind11;\n\nPYBIND11_WARNING_DISABLE_MSVC(4127)\n\ntemplate <typename M>\nvoid reset_tensor(M &x) {\n    for (int i = 0; i < x.dimension(0); i++) {\n        for (int j = 0; j < x.dimension(1); j++) {\n            for (int k = 0; k < x.dimension(2); k++) {\n                x(i, j, k) = i * (5 * 2) + j * 2 + k;\n            }\n        }\n    }\n}\n\ntemplate <typename M>\nbool check_tensor(M &x) {\n    for (int i = 0; i < x.dimension(0); i++) {\n        for (int j = 0; j < x.dimension(1); j++) {\n            for (int k = 0; k < x.dimension(2); k++) {\n                if (x(i, j, k) != (i * (5 * 2) + j * 2 + k)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\ntemplate <int Options>\nEigen::Tensor<double, 3, Options> &get_tensor() {\n    static Eigen::Tensor<double, 3, Options> *x;\n\n    if (!x) {\n        x = new Eigen::Tensor<double, 3, Options>(3, 5, 2);\n        reset_tensor(*x);\n    }\n\n    return *x;\n}\n\ntemplate <int Options>\nEigen::TensorMap<Eigen::Tensor<double, 3, Options>> &get_tensor_map() {\n    static Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> *x;\n\n    if (!x) {\n        x = new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());\n    }\n\n    return *x;\n}\n\ntemplate <int Options>\nEigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> &get_fixed_tensor() {\n    static Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> *x;\n\n    if (!x) {\n        Eigen::aligned_allocator<Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>\n            allocator;\n        x = new (allocator.allocate(1))\n            Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>();\n        reset_tensor(*x);\n    }\n\n    return *x;\n}\n\ntemplate <int Options>\nconst Eigen::Tensor<double, 3, Options> &get_const_tensor() {\n    return get_tensor<Options>();\n}\n\ntemplate <int Options>\nstruct CustomExample {\n    CustomExample() : member(get_tensor<Options>()), view_member(member) {}\n\n    Eigen::Tensor<double, 3, Options> member;\n    Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> view_member;\n};\n\ntemplate <int Options>\nvoid init_tensor_module(pybind11::module &m) {\n    const char *needed_options = \"\";\n    if (Options == Eigen::ColMajor) {\n        needed_options = \"F\";\n    } else {\n        needed_options = \"C\";\n    }\n    m.attr(\"needed_options\") = needed_options;\n\n    m.def(\"setup\", []() {\n        reset_tensor(get_tensor<Options>());\n        reset_tensor(get_fixed_tensor<Options>());\n    });\n\n    m.def(\"is_ok\", []() {\n        return check_tensor(get_tensor<Options>()) && check_tensor(get_fixed_tensor<Options>());\n    });\n\n    py::class_<CustomExample<Options>>(m, \"CustomExample\", py::module_local())\n        .def(py::init<>())\n        .def_readonly(\n            \"member\", &CustomExample<Options>::member, py::return_value_policy::reference_internal)\n        .def_readonly(\"member_view\",\n                      &CustomExample<Options>::view_member,\n                      py::return_value_policy::reference_internal);\n\n    m.def(\n        \"copy_fixed_tensor\",\n        []() { return &get_fixed_tensor<Options>(); },\n        py::return_value_policy::copy);\n\n    m.def(\"copy_tensor\", []() { return &get_tensor<Options>(); }, py::return_value_policy::copy);\n\n    m.def(\n        \"copy_const_tensor\",\n        []() { return &get_const_tensor<Options>(); },\n        py::return_value_policy::copy);\n\n    m.def(\n        \"move_fixed_tensor_copy\",\n        []() -> Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> {\n            return get_fixed_tensor<Options>();\n        },\n        py::return_value_policy::move);\n\n    m.def(\n        \"move_tensor_copy\",\n        []() -> Eigen::Tensor<double, 3, Options> { return get_tensor<Options>(); },\n        py::return_value_policy::move);\n\n    m.def(\n        \"move_const_tensor\",\n        []() -> const Eigen::Tensor<double, 3, Options> & { return get_const_tensor<Options>(); },\n        py::return_value_policy::move);\n\n    m.def(\n        \"take_fixed_tensor\",\n        []() {\n            Eigen::aligned_allocator<\n                Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>\n                allocator;\n            static auto *obj = new (allocator.allocate(1))\n                Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>(\n                    get_fixed_tensor<Options>());\n            return obj; // take_ownership will fail.\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\n        \"take_tensor\",\n        []() {\n            static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());\n            return obj; // take_ownership will fail.\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\n        \"take_const_tensor\",\n        []() -> const Eigen::Tensor<double, 3, Options> * {\n            static auto *obj = new Eigen::Tensor<double, 3, Options>(get_tensor<Options>());\n            return obj; // take_ownership will fail.\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\n        \"take_view_tensor\",\n        []() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {\n            static auto *obj\n                = new Eigen::TensorMap<Eigen::Tensor<double, 3, Options>>(get_tensor<Options>());\n            return obj; // take_ownership will fail.\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\n        \"reference_tensor\",\n        []() { return &get_tensor<Options>(); },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_tensor_v2\",\n        []() -> Eigen::Tensor<double, 3, Options> & { return get_tensor<Options>(); },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_tensor_internal\",\n        []() { return &get_tensor<Options>(); },\n        py::return_value_policy::reference_internal);\n\n    m.def(\n        \"reference_fixed_tensor\",\n        []() { return &get_tensor<Options>(); },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_const_tensor\",\n        []() { return &get_const_tensor<Options>(); },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_const_tensor_v2\",\n        []() -> const Eigen::Tensor<double, 3, Options> & { return get_const_tensor<Options>(); },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor\",\n        []() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> {\n            return get_tensor_map<Options>();\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor_v2\",\n        // NOLINTNEXTLINE(readability-const-return-type)\n        []() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> {\n            return get_tensor_map<Options>(); // NOLINT(readability-const-return-type)\n        },                                    // NOLINT(readability-const-return-type)\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor_v3\",\n        []() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {\n            return &get_tensor_map<Options>();\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor_v4\",\n        []() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> * {\n            return &get_tensor_map<Options>();\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor_v5\",\n        []() -> Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> & {\n            return get_tensor_map<Options>();\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_tensor_v6\",\n        []() -> const Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> & {\n            return get_tensor_map<Options>();\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"reference_view_of_fixed_tensor\",\n        []() {\n            return Eigen::TensorMap<\n                Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options>>(\n                get_fixed_tensor<Options>());\n        },\n        py::return_value_policy::reference);\n\n    m.def(\"round_trip_tensor\",\n          [](const Eigen::Tensor<double, 3, Options> &tensor) { return tensor; });\n\n    m.def(\n        \"round_trip_tensor_noconvert\",\n        [](const Eigen::Tensor<double, 3, Options> &tensor) { return tensor; },\n        py::arg(\"tensor\").noconvert());\n\n    m.def(\"round_trip_tensor2\",\n          [](const Eigen::Tensor<int32_t, 3, Options> &tensor) { return tensor; });\n\n    m.def(\"round_trip_fixed_tensor\",\n          [](const Eigen::TensorFixedSize<double, Eigen::Sizes<3, 5, 2>, Options> &tensor) {\n              return tensor;\n          });\n\n    m.def(\n        \"round_trip_view_tensor\",\n        [](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> view) { return view; },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"round_trip_view_tensor_ref\",\n        [](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> &view) { return view; },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"round_trip_view_tensor_ptr\",\n        [](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>> *view) { return view; },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"round_trip_aligned_view_tensor\",\n        [](Eigen::TensorMap<Eigen::Tensor<double, 3, Options>, Eigen::Aligned> view) {\n            return view;\n        },\n        py::return_value_policy::reference);\n\n    m.def(\n        \"round_trip_const_view_tensor\",\n        [](Eigen::TensorMap<const Eigen::Tensor<double, 3, Options>> view) {\n            return Eigen::Tensor<double, 3, Options>(view);\n        },\n        py::return_value_policy::move);\n\n    m.def(\n        \"round_trip_rank_0\",\n        [](const Eigen::Tensor<double, 0, Options> &tensor) { return tensor; },\n        py::return_value_policy::move);\n\n    m.def(\n        \"round_trip_rank_0_noconvert\",\n        [](const Eigen::Tensor<double, 0, Options> &tensor) { return tensor; },\n        py::arg(\"tensor\").noconvert(),\n        py::return_value_policy::move);\n\n    m.def(\n        \"round_trip_rank_0_view\",\n        [](Eigen::TensorMap<Eigen::Tensor<double, 0, Options>> &tensor) { return tensor; },\n        py::return_value_policy::reference);\n}\n\nvoid test_module(py::module_ &m) {\n    auto f_style = m.def_submodule(\"f_style\");\n    auto c_style = m.def_submodule(\"c_style\");\n\n    init_tensor_module<Eigen::ColMajor>(f_style);\n    init_tensor_module<Eigen::RowMajor>(c_style);\n}\n\nPYBIND11_NAMESPACE_END(eigen_tensor_test)\n"
  },
  {
    "path": "tests/test_eigen_tensor.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\n\nimport env  # noqa: F401\n\nnp = pytest.importorskip(\"numpy\")\neigen_tensor = pytest.importorskip(\"pybind11_tests.eigen_tensor\")\nsubmodules = [eigen_tensor.c_style, eigen_tensor.f_style]\ntry:\n    import eigen_tensor_avoid_stl_array as avoid\n\n    submodules += [avoid.c_style, avoid.f_style]\nexcept ImportError as e:\n    # Ensure config, build, toolchain, etc. issues are not masked here:\n    msg = (\n        \"import eigen_tensor_avoid_stl_array FAILED, while \"\n        \"import pybind11_tests.eigen_tensor succeeded. \"\n        \"Please ensure that \"\n        \"test_eigen_tensor.cpp & \"\n        \"eigen_tensor_avoid_stl_array.cpp \"\n        \"are built together (or both are not built if Eigen is not available).\"\n    )\n    raise RuntimeError(msg) from e\n\ntensor_ref = np.empty((3, 5, 2), dtype=np.int64)\n\nfor i in range(tensor_ref.shape[0]):\n    for j in range(tensor_ref.shape[1]):\n        for k in range(tensor_ref.shape[2]):\n            tensor_ref[i, j, k] = i * (5 * 2) + j * 2 + k\n\nindices = (2, 3, 1)\n\n\n@pytest.fixture(autouse=True)\ndef cleanup():\n    for module in submodules:\n        module.setup()\n\n    yield\n\n    for module in submodules:\n        assert module.is_ok()\n\n\ndef test_import_avoid_stl_array():\n    pytest.importorskip(\"eigen_tensor_avoid_stl_array\")\n    assert len(submodules) == 4\n\n\ndef assert_equal_tensor_ref(mat, writeable=True, modified=None):\n    assert mat.flags.writeable == writeable\n\n    copy = np.array(tensor_ref)\n    if modified is not None:\n        copy[indices] = modified\n\n    np.testing.assert_array_equal(mat, copy)\n\n\n@pytest.mark.parametrize(\"m\", submodules)\n@pytest.mark.parametrize(\"member_name\", [\"member\", \"member_view\"])\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Different refcounting mechanism\")\ndef test_reference_internal(m, member_name):\n    if not hasattr(sys, \"getrefcount\"):\n        pytest.skip(\"No reference counting\")\n    foo = m.CustomExample()\n    counts = sys.getrefcount(foo)\n    mem = getattr(foo, member_name)\n    assert_equal_tensor_ref(mem, writeable=False)\n    new_counts = sys.getrefcount(foo)\n    assert new_counts == counts + 1\n    assert_equal_tensor_ref(mem, writeable=False)\n    del mem\n    assert sys.getrefcount(foo) == counts\n\n\nassert_equal_funcs = [\n    \"copy_tensor\",\n    \"copy_fixed_tensor\",\n    \"copy_const_tensor\",\n    \"move_tensor_copy\",\n    \"move_fixed_tensor_copy\",\n    \"take_tensor\",\n    \"take_fixed_tensor\",\n    \"reference_tensor\",\n    \"reference_tensor_v2\",\n    \"reference_fixed_tensor\",\n    \"reference_view_of_tensor\",\n    \"reference_view_of_tensor_v3\",\n    \"reference_view_of_tensor_v5\",\n    \"reference_view_of_fixed_tensor\",\n]\n\nassert_equal_const_funcs = [\n    \"reference_view_of_tensor_v2\",\n    \"reference_view_of_tensor_v4\",\n    \"reference_view_of_tensor_v6\",\n    \"reference_const_tensor\",\n    \"reference_const_tensor_v2\",\n]\n\n\n@pytest.mark.parametrize(\"m\", submodules)\n@pytest.mark.parametrize(\"func_name\", assert_equal_funcs + assert_equal_const_funcs)\ndef test_convert_tensor_to_py(m, func_name):\n    writeable = func_name in assert_equal_funcs\n    assert_equal_tensor_ref(getattr(m, func_name)(), writeable=writeable)\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_bad_cpp_to_python_casts(m):\n    with pytest.raises(\n        RuntimeError, match=\"Cannot use reference internal when there is no parent\"\n    ):\n        m.reference_tensor_internal()\n\n    with pytest.raises(RuntimeError, match=\"Cannot move from a constant reference\"):\n        m.move_const_tensor()\n\n    with pytest.raises(\n        RuntimeError, match=\"Cannot take ownership of a const reference\"\n    ):\n        m.take_const_tensor()\n\n    with pytest.raises(\n        RuntimeError,\n        match=\"Invalid return_value_policy for Eigen Map type, must be either reference or reference_internal\",\n    ):\n        m.take_view_tensor()\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_bad_python_to_cpp_casts(m):\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_tensor(np.zeros((2, 3)))\n\n    with pytest.raises(TypeError, match=r\"^Cannot cast array data from dtype\"):\n        m.round_trip_tensor(np.zeros(dtype=np.str_, shape=(2, 3, 1)))\n\n    with pytest.raises(\n        TypeError,\n        match=r\"^round_trip_tensor_noconvert\\(\\): incompatible function arguments\",\n    ):\n        m.round_trip_tensor_noconvert(tensor_ref)\n\n    assert_equal_tensor_ref(\n        m.round_trip_tensor_noconvert(tensor_ref.astype(np.float64))\n    )\n\n    bad_options = \"C\" if m.needed_options == \"F\" else \"F\"\n    # Shape, dtype and the order need to be correct for a TensorMap cast\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_view_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_view_tensor(\n            np.zeros((3, 5, 2), dtype=np.float64, order=bad_options)\n        )\n\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_view_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_view_tensor(\n            np.zeros((3, 5, 2), dtype=np.float32, order=m.needed_options)\n        )\n\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_view_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_view_tensor(\n            np.zeros((3, 5), dtype=np.float64, order=m.needed_options)\n        )\n\n    temp = np.zeros((3, 5, 2), dtype=np.float64, order=m.needed_options)\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_view_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_view_tensor(\n            temp[:, ::-1, :],\n        )\n\n    temp = np.zeros((3, 5, 2), dtype=np.float64, order=m.needed_options)\n    temp.setflags(write=False)\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_view_tensor\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_view_tensor(temp)\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_references_actually_refer(m):\n    a = m.reference_tensor()\n    temp = a[indices]\n    a[indices] = 100\n    assert_equal_tensor_ref(m.copy_const_tensor(), modified=100)\n    a[indices] = temp\n    assert_equal_tensor_ref(m.copy_const_tensor())\n\n    a = m.reference_view_of_tensor()\n    a[indices] = 100\n    assert_equal_tensor_ref(m.copy_const_tensor(), modified=100)\n    a[indices] = temp\n    assert_equal_tensor_ref(m.copy_const_tensor())\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_round_trip(m):\n    assert_equal_tensor_ref(m.round_trip_tensor(tensor_ref))\n\n    with pytest.raises(TypeError, match=\"^Cannot cast array data from\"):\n        assert_equal_tensor_ref(m.round_trip_tensor2(tensor_ref))\n\n    assert_equal_tensor_ref(m.round_trip_tensor2(np.array(tensor_ref, dtype=np.int32)))\n    assert_equal_tensor_ref(m.round_trip_fixed_tensor(tensor_ref))\n    assert_equal_tensor_ref(m.round_trip_aligned_view_tensor(m.reference_tensor()))\n\n    copy = np.array(tensor_ref, dtype=np.float64, order=m.needed_options)\n    assert_equal_tensor_ref(m.round_trip_view_tensor(copy))\n    assert_equal_tensor_ref(m.round_trip_view_tensor_ref(copy))\n    assert_equal_tensor_ref(m.round_trip_view_tensor_ptr(copy))\n    copy.setflags(write=False)\n    assert_equal_tensor_ref(m.round_trip_const_view_tensor(copy))\n\n    np.testing.assert_array_equal(\n        tensor_ref[:, ::-1, :], m.round_trip_tensor(tensor_ref[:, ::-1, :])\n    )\n\n    assert m.round_trip_rank_0(np.float64(3.5)) == 3.5\n    assert m.round_trip_rank_0(3.5) == 3.5\n\n    with pytest.raises(\n        TypeError,\n        match=r\"^round_trip_rank_0_noconvert\\(\\): incompatible function arguments\",\n    ):\n        m.round_trip_rank_0_noconvert(np.float64(3.5))\n\n    with pytest.raises(\n        TypeError,\n        match=r\"^round_trip_rank_0_noconvert\\(\\): incompatible function arguments\",\n    ):\n        m.round_trip_rank_0_noconvert(3.5)\n\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_rank_0_view\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_rank_0_view(np.float64(3.5))\n\n    with pytest.raises(\n        TypeError, match=r\"^round_trip_rank_0_view\\(\\): incompatible function arguments\"\n    ):\n        m.round_trip_rank_0_view(3.5)\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_round_trip_references_actually_refer(m):\n    # Need to create a copy that matches the type on the C side\n    copy = np.array(tensor_ref, dtype=np.float64, order=m.needed_options)\n    a = m.round_trip_view_tensor(copy)\n    temp = a[indices]\n    a[indices] = 100\n    assert_equal_tensor_ref(copy, modified=100)\n    a[indices] = temp\n    assert_equal_tensor_ref(copy)\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_doc_string(m, doc):\n    assert (\n        doc(m.copy_tensor)\n        == 'copy_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"]'\n    )\n    assert (\n        doc(m.copy_fixed_tensor)\n        == 'copy_fixed_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[3, 5, 2]\"]'\n    )\n    assert (\n        doc(m.reference_const_tensor)\n        == 'reference_const_tensor() -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"]'\n    )\n\n    order_flag = f'\"flags.{m.needed_options.lower()}_contiguous\"'\n    assert doc(m.round_trip_view_tensor) == (\n        f'round_trip_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\", \"flags.writeable\", {order_flag}])'\n        f' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\", \"flags.writeable\", {order_flag}]'\n    )\n    assert doc(m.round_trip_const_view_tensor) == (\n        f'round_trip_const_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\", {order_flag}])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"]'\n    )\n\n\n@pytest.mark.parametrize(\"m\", submodules)\ndef test_arraylike_signature(m, doc):\n    order_flag = f'\"flags.{m.needed_options.lower()}_contiguous\"'\n    assert doc(m.round_trip_tensor) == (\n        'round_trip_tensor(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float64, \"[?, ?, ?]\"])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"]'\n    )\n    assert doc(m.round_trip_tensor_noconvert) == (\n        'round_trip_tensor_noconvert(tensor: typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"])'\n        ' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\"]'\n    )\n    assert doc(m.round_trip_view_tensor) == (\n        f'round_trip_view_tensor(arg0: typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\", \"flags.writeable\", {order_flag}])'\n        f' -> typing.Annotated[numpy.typing.NDArray[numpy.float64], \"[?, ?, ?]\", \"flags.writeable\", {order_flag}]'\n    )\n    m.round_trip_tensor(tensor_ref.tolist())\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.round_trip_tensor_noconvert(tensor_ref.tolist())\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.round_trip_view_tensor(tensor_ref.tolist())\n"
  },
  {
    "path": "tests/test_enum.cpp",
    "content": "/*\n    tests/test_enums.cpp -- enumerations\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(enums, m) {\n    // test_unscoped_enum\n    enum UnscopedEnum { EOne = 1, ETwo, EThree };\n    py::enum_<UnscopedEnum>(m, \"UnscopedEnum\", py::arithmetic(), \"An unscoped enumeration\")\n        .value(\"EOne\", EOne, \"Docstring for EOne\")\n        .value(\"ETwo\", ETwo, \"Docstring for ETwo\")\n        .value(\"EThree\", EThree, \"Docstring for EThree\")\n        .export_values();\n\n    // test_scoped_enum\n    enum class ScopedEnum { Two = 2, Three };\n    py::enum_<ScopedEnum>(m, \"ScopedEnum\", py::arithmetic())\n        .value(\"Two\", ScopedEnum::Two)\n        .value(\"Three\", ScopedEnum::Three);\n\n    m.def(\"test_scoped_enum\", [](ScopedEnum z) {\n        return \"ScopedEnum::\" + std::string(z == ScopedEnum::Two ? \"Two\" : \"Three\");\n    });\n\n    // test_binary_operators\n    enum Flags { Read = 4, Write = 2, Execute = 1 };\n    py::enum_<Flags>(m, \"Flags\", py::arithmetic())\n        .value(\"Read\", Flags::Read)\n        .value(\"Write\", Flags::Write)\n        .value(\"Execute\", Flags::Execute)\n        .export_values();\n\n    // test_implicit_conversion\n    class ClassWithUnscopedEnum {\n    public:\n        enum EMode { EFirstMode = 1, ESecondMode };\n\n        static EMode test_function(EMode mode) { return mode; }\n    };\n    py::class_<ClassWithUnscopedEnum> exenum_class(m, \"ClassWithUnscopedEnum\");\n    exenum_class.def_static(\"test_function\", &ClassWithUnscopedEnum::test_function);\n    py::enum_<ClassWithUnscopedEnum::EMode>(exenum_class, \"EMode\")\n        .value(\"EFirstMode\", ClassWithUnscopedEnum::EFirstMode)\n        .value(\"ESecondMode\", ClassWithUnscopedEnum::ESecondMode)\n        .export_values();\n\n    // test_enum_to_int\n    m.def(\"test_enum_to_int\", [](int) {});\n    m.def(\"test_enum_to_uint\", [](uint32_t) {});\n    m.def(\"test_enum_to_long_long\", [](long long) {});\n\n    // test_duplicate_enum_name\n    enum SimpleEnum { ONE, TWO, THREE };\n\n    m.def(\"register_bad_enum\", [m]() {\n        py::enum_<SimpleEnum>(m, \"SimpleEnum\")\n            .value(\"ONE\", SimpleEnum::ONE) // NOTE: all value function calls are called with the\n                                           // same first parameter value\n            .value(\"ONE\", SimpleEnum::TWO)\n            .value(\"ONE\", SimpleEnum::THREE)\n            .export_values();\n    });\n\n    // test_enum_scalar\n    enum UnscopedUCharEnum : unsigned char {};\n    enum class ScopedShortEnum : short {};\n    enum class ScopedLongEnum : long {};\n    enum UnscopedUInt64Enum : std::uint64_t {};\n    static_assert(\n        py::detail::all_of<\n            std::is_same<py::enum_<UnscopedUCharEnum>::Scalar, unsigned char>,\n            std::is_same<py::enum_<ScopedShortEnum>::Scalar, short>,\n            std::is_same<py::enum_<ScopedLongEnum>::Scalar, long>,\n            std::is_same<py::enum_<UnscopedUInt64Enum>::Scalar, std::uint64_t>>::value,\n        \"Error during the deduction of enum's scalar type with normal integer underlying\");\n\n    // test_enum_scalar_with_char_underlying\n    enum class ScopedCharEnum : char { Zero, Positive };\n    enum class ScopedWCharEnum : wchar_t { Zero, Positive };\n    enum class ScopedChar32Enum : char32_t { Zero, Positive };\n    enum class ScopedChar16Enum : char16_t { Zero, Positive };\n\n    // test the scalar of char type enums according to chapter 'Character types'\n    // from https://en.cppreference.com/w/cpp/language/types\n    static_assert(\n        py::detail::any_of<\n            std::is_same<py::enum_<ScopedCharEnum>::Scalar, signed char>,  // e.g. gcc on x86\n            std::is_same<py::enum_<ScopedCharEnum>::Scalar, unsigned char> // e.g. arm linux\n            >::value,\n        \"char should be cast to either signed char or unsigned char\");\n    static_assert(sizeof(py::enum_<ScopedWCharEnum>::Scalar) == 2\n                      || sizeof(py::enum_<ScopedWCharEnum>::Scalar) == 4,\n                  \"wchar_t should be either 16 bits (Windows) or 32 (everywhere else)\");\n    static_assert(\n        py::detail::all_of<\n            std::is_same<py::enum_<ScopedChar32Enum>::Scalar, std::uint_least32_t>,\n            std::is_same<py::enum_<ScopedChar16Enum>::Scalar, std::uint_least16_t>>::value,\n        \"char32_t, char16_t (and char8_t)'s size, signedness, and alignment is determined\");\n#if defined(PYBIND11_HAS_U8STRING)\n    enum class ScopedChar8Enum : char8_t { Zero, Positive };\n    static_assert(std::is_same<py::enum_<ScopedChar8Enum>::Scalar, unsigned char>::value);\n#endif\n\n    // test_char_underlying_enum\n    py::enum_<ScopedCharEnum>(m, \"ScopedCharEnum\")\n        .value(\"Zero\", ScopedCharEnum::Zero)\n        .value(\"Positive\", ScopedCharEnum::Positive);\n    py::enum_<ScopedWCharEnum>(m, \"ScopedWCharEnum\")\n        .value(\"Zero\", ScopedWCharEnum::Zero)\n        .value(\"Positive\", ScopedWCharEnum::Positive);\n    py::enum_<ScopedChar32Enum>(m, \"ScopedChar32Enum\")\n        .value(\"Zero\", ScopedChar32Enum::Zero)\n        .value(\"Positive\", ScopedChar32Enum::Positive);\n    py::enum_<ScopedChar16Enum>(m, \"ScopedChar16Enum\")\n        .value(\"Zero\", ScopedChar16Enum::Zero)\n        .value(\"Positive\", ScopedChar16Enum::Positive);\n\n    // test_bool_underlying_enum\n    enum class ScopedBoolEnum : bool { FALSE, TRUE };\n\n    // bool is unsigned (std::is_signed returns false) and 1-byte long, so represented with u8\n    static_assert(std::is_same<py::enum_<ScopedBoolEnum>::Scalar, std::uint8_t>::value, \"\");\n\n    py::enum_<ScopedBoolEnum>(m, \"ScopedBoolEnum\")\n        .value(\"FALSE\", ScopedBoolEnum::FALSE)\n        .value(\"TRUE\", ScopedBoolEnum::TRUE);\n\n#if defined(__MINGW32__)\n    m.attr(\"obj_cast_UnscopedEnum_ptr\") = \"MinGW: dangling pointer to an unnamed temporary may be \"\n                                          \"used [-Werror=dangling-pointer=]\";\n#else\n    m.def(\"obj_cast_UnscopedEnum_ptr\", [](const py::object &obj) {\n        // https://github.com/OpenImageIO/oiio/blob/30ea4ebdfab11aec291befbaff446f2a7d24835b/src/python/py_oiio.h#L300\n        if (py::isinstance<UnscopedEnum>(obj)) {\n            if (*obj.cast<UnscopedEnum *>() == UnscopedEnum::ETwo) {\n                return 2;\n            }\n            return 1;\n        }\n        return 0;\n    });\n#endif\n}\n"
  },
  {
    "path": "tests/test_enum.py",
    "content": "# ruff: noqa: SIM201 SIM300 SIM202\nfrom __future__ import annotations\n\nimport re\n\nimport pytest\n\nimport env\nfrom pybind11_tests import enums as m\n\n\n@pytest.mark.xfail(\n    env.GRAALPY and env.GRAALPY_VERSION < (24, 2), reason=\"Fixed in GraalPy 24.2\"\n)\ndef test_unscoped_enum():\n    assert str(m.UnscopedEnum.EOne) == \"UnscopedEnum.EOne\"\n    assert str(m.UnscopedEnum.ETwo) == \"UnscopedEnum.ETwo\"\n    assert str(m.EOne) == \"UnscopedEnum.EOne\"\n    assert repr(m.UnscopedEnum.EOne) == \"<UnscopedEnum.EOne: 1>\"\n    assert repr(m.UnscopedEnum.ETwo) == \"<UnscopedEnum.ETwo: 2>\"\n    assert repr(m.EOne) == \"<UnscopedEnum.EOne: 1>\"\n\n    # name property\n    assert m.UnscopedEnum.EOne.name == \"EOne\"\n    assert m.UnscopedEnum.EOne.value == 1\n    assert m.UnscopedEnum.ETwo.name == \"ETwo\"\n    assert m.UnscopedEnum.ETwo.value == 2\n    assert m.EOne is m.UnscopedEnum.EOne\n    # name, value readonly\n    with pytest.raises(AttributeError):\n        m.UnscopedEnum.EOne.name = \"\"\n    with pytest.raises(AttributeError):\n        m.UnscopedEnum.EOne.value = 10\n    # name, value returns a copy\n    # TODO: Neither the name nor value tests actually check against aliasing.\n    # Use a mutable type that has reference semantics.\n    nonaliased_name = m.UnscopedEnum.EOne.name\n    nonaliased_name = \"bar\"  # noqa: F841\n    assert m.UnscopedEnum.EOne.name == \"EOne\"\n    nonaliased_value = m.UnscopedEnum.EOne.value\n    nonaliased_value = 10  # noqa: F841\n    assert m.UnscopedEnum.EOne.value == 1\n\n    # __members__ property\n    assert m.UnscopedEnum.__members__ == {\n        \"EOne\": m.UnscopedEnum.EOne,\n        \"ETwo\": m.UnscopedEnum.ETwo,\n        \"EThree\": m.UnscopedEnum.EThree,\n    }\n    # __members__ readonly\n    with pytest.raises(AttributeError):\n        m.UnscopedEnum.__members__ = {}\n    # __members__ returns a copy\n    nonaliased_members = m.UnscopedEnum.__members__\n    nonaliased_members[\"bar\"] = \"baz\"\n    assert m.UnscopedEnum.__members__ == {\n        \"EOne\": m.UnscopedEnum.EOne,\n        \"ETwo\": m.UnscopedEnum.ETwo,\n        \"EThree\": m.UnscopedEnum.EThree,\n    }\n\n    for docstring_line in [\n        \"An unscoped enumeration\",\n        \"Members:\",\n        \"  EOne : Docstring for EOne\",\n        \"  ETwo : Docstring for ETwo\",\n        \"  EThree : Docstring for EThree\",\n    ]:\n        assert docstring_line in m.UnscopedEnum.__doc__\n\n    # Unscoped enums will accept ==/!= int comparisons\n    y = m.UnscopedEnum.ETwo\n    assert y == 2\n    assert 2 == y\n    assert y != 3\n    assert 3 != y\n    # Compare with None\n    assert y != None  # noqa: E711\n    assert not (y == None)  # noqa: E711\n    # Compare with an object\n    assert y != object()\n    assert not (y == object())\n    # Compare with string\n    assert y != \"2\"\n    assert \"2\" != y\n    assert not (\"2\" == y)\n    assert not (y == \"2\")\n\n    with pytest.raises(TypeError):\n        y < object()  # noqa: B015\n\n    with pytest.raises(TypeError):\n        y <= object()  # noqa: B015\n\n    with pytest.raises(TypeError):\n        y > object()  # noqa: B015\n\n    with pytest.raises(TypeError):\n        y >= object()  # noqa: B015\n\n    with pytest.raises(TypeError):\n        y | object()\n\n    with pytest.raises(TypeError):\n        y & object()\n\n    with pytest.raises(TypeError):\n        y ^ object()\n\n    assert int(m.UnscopedEnum.ETwo) == 2\n    assert str(m.UnscopedEnum(2)) == \"UnscopedEnum.ETwo\"\n\n    # order\n    assert m.UnscopedEnum.EOne < m.UnscopedEnum.ETwo\n    assert m.UnscopedEnum.EOne < 2\n    assert m.UnscopedEnum.ETwo > m.UnscopedEnum.EOne\n    assert m.UnscopedEnum.ETwo > 1\n    assert m.UnscopedEnum.ETwo <= 2\n    assert m.UnscopedEnum.ETwo >= 2\n    assert m.UnscopedEnum.EOne <= m.UnscopedEnum.ETwo\n    assert m.UnscopedEnum.EOne <= 2\n    assert m.UnscopedEnum.ETwo >= m.UnscopedEnum.EOne\n    assert m.UnscopedEnum.ETwo >= 1\n    assert not (m.UnscopedEnum.ETwo < m.UnscopedEnum.EOne)\n    assert not (2 < m.UnscopedEnum.EOne)\n\n    # arithmetic\n    assert m.UnscopedEnum.EOne & m.UnscopedEnum.EThree == m.UnscopedEnum.EOne\n    assert m.UnscopedEnum.EOne | m.UnscopedEnum.ETwo == m.UnscopedEnum.EThree\n    assert m.UnscopedEnum.EOne ^ m.UnscopedEnum.EThree == m.UnscopedEnum.ETwo\n\n\ndef test_scoped_enum():\n    assert m.test_scoped_enum(m.ScopedEnum.Three) == \"ScopedEnum::Three\"\n    z = m.ScopedEnum.Two\n    assert m.test_scoped_enum(z) == \"ScopedEnum::Two\"\n\n    # Scoped enums will *NOT* accept ==/!= int comparisons (Will always return False)\n    assert not z == 3\n    assert not 3 == z\n    assert z != 3\n    assert 3 != z\n    # Compare with None\n    assert z != None  # noqa: E711\n    assert not (z == None)  # noqa: E711\n    # Compare with an object\n    assert z != object()\n    assert not (z == object())\n    # Scoped enums will *NOT* accept >, <, >= and <= int comparisons (Will throw exceptions)\n    with pytest.raises(TypeError):\n        z > 3  # noqa: B015\n    with pytest.raises(TypeError):\n        z < 3  # noqa: B015\n    with pytest.raises(TypeError):\n        z >= 3  # noqa: B015\n    with pytest.raises(TypeError):\n        z <= 3  # noqa: B015\n\n    # order\n    assert m.ScopedEnum.Two < m.ScopedEnum.Three\n    assert m.ScopedEnum.Three > m.ScopedEnum.Two\n    assert m.ScopedEnum.Two <= m.ScopedEnum.Three\n    assert m.ScopedEnum.Two <= m.ScopedEnum.Two\n    assert m.ScopedEnum.Two >= m.ScopedEnum.Two\n    assert m.ScopedEnum.Three >= m.ScopedEnum.Two\n\n\ndef test_implicit_conversion():\n    assert str(m.ClassWithUnscopedEnum.EMode.EFirstMode) == \"EMode.EFirstMode\"\n    assert str(m.ClassWithUnscopedEnum.EFirstMode) == \"EMode.EFirstMode\"\n    assert repr(m.ClassWithUnscopedEnum.EMode.EFirstMode) == \"<EMode.EFirstMode: 1>\"\n    assert repr(m.ClassWithUnscopedEnum.EFirstMode) == \"<EMode.EFirstMode: 1>\"\n\n    f = m.ClassWithUnscopedEnum.test_function\n    first = m.ClassWithUnscopedEnum.EFirstMode\n    second = m.ClassWithUnscopedEnum.ESecondMode\n\n    assert f(first) == 1\n\n    assert f(first) == f(first)\n    assert not f(first) != f(first)\n\n    assert f(first) != f(second)\n    assert not f(first) == f(second)\n\n    assert f(first) == int(f(first))\n    assert not f(first) != int(f(first))\n\n    assert f(first) != int(f(second))\n    assert not f(first) == int(f(second))\n\n    # noinspection PyDictCreation\n    x = {f(first): 1, f(second): 2}\n    x[f(first)] = 3\n    x[f(second)] = 4\n    # Hashing test\n    assert repr(x) == \"{<EMode.EFirstMode: 1>: 3, <EMode.ESecondMode: 2>: 4}\"\n\n\n@pytest.mark.xfail(\n    env.GRAALPY and env.GRAALPY_VERSION < (24, 2), reason=\"Fixed in GraalPy 24.2\"\n)\ndef test_binary_operators():\n    assert int(m.Flags.Read) == 4\n    assert int(m.Flags.Write) == 2\n    assert int(m.Flags.Execute) == 1\n    assert int(m.Flags.Read | m.Flags.Write | m.Flags.Execute) == 7\n    assert int(m.Flags.Read | m.Flags.Write) == 6\n    assert int(m.Flags.Read | m.Flags.Execute) == 5\n    assert int(m.Flags.Write | m.Flags.Execute) == 3\n    assert int(m.Flags.Write | 1) == 3\n    assert ~m.Flags.Write == -3\n\n    state = m.Flags.Read | m.Flags.Write\n    assert (state & m.Flags.Read) != 0\n    assert (state & m.Flags.Write) != 0\n    assert (state & m.Flags.Execute) == 0\n    assert (state & 1) == 0\n\n    state2 = ~state\n    assert state2 == -7\n    assert int(state ^ state2) == -1\n\n\ndef test_enum_to_int():\n    m.test_enum_to_int(m.Flags.Read)\n    m.test_enum_to_int(m.ClassWithUnscopedEnum.EMode.EFirstMode)\n    m.test_enum_to_int(m.ScopedCharEnum.Positive)\n    m.test_enum_to_int(m.ScopedBoolEnum.TRUE)\n    m.test_enum_to_uint(m.Flags.Read)\n    m.test_enum_to_uint(m.ClassWithUnscopedEnum.EMode.EFirstMode)\n    m.test_enum_to_uint(m.ScopedCharEnum.Positive)\n    m.test_enum_to_uint(m.ScopedBoolEnum.TRUE)\n    m.test_enum_to_long_long(m.Flags.Read)\n    m.test_enum_to_long_long(m.ClassWithUnscopedEnum.EMode.EFirstMode)\n    m.test_enum_to_long_long(m.ScopedCharEnum.Positive)\n    m.test_enum_to_long_long(m.ScopedBoolEnum.TRUE)\n\n\ndef test_duplicate_enum_name():\n    with pytest.raises(ValueError) as excinfo:\n        m.register_bad_enum()\n    assert str(excinfo.value) == 'SimpleEnum: element \"ONE\" already exists!'\n\n\ndef test_char_underlying_enum():  # Issue #1331/PR #1334:\n    assert type(m.ScopedCharEnum.Positive.__int__()) is int\n    assert int(m.ScopedChar16Enum.Zero) == 0\n    assert hash(m.ScopedChar32Enum.Positive) == 1\n    assert type(m.ScopedCharEnum.Positive.__getstate__()) is int\n    assert m.ScopedWCharEnum(1) == m.ScopedWCharEnum.Positive\n    with pytest.raises(TypeError):\n        # Even if the underlying type is char, only an int can be used to construct the enum:\n        m.ScopedCharEnum(\"0\")\n\n\ndef test_bool_underlying_enum():\n    assert type(m.ScopedBoolEnum.TRUE.__int__()) is int\n    assert int(m.ScopedBoolEnum.FALSE) == 0\n    assert hash(m.ScopedBoolEnum.TRUE) == 1\n    assert type(m.ScopedBoolEnum.TRUE.__getstate__()) is int\n    assert m.ScopedBoolEnum(1) == m.ScopedBoolEnum.TRUE\n    # Enum could construct with a bool\n    # (bool is a strict subclass of int, and False will be converted to 0)\n    assert m.ScopedBoolEnum(False) == m.ScopedBoolEnum.FALSE\n\n\ndef test_docstring_signatures():\n    for enum_type in [m.ScopedEnum, m.UnscopedEnum]:\n        for attr in enum_type.__dict__.values():\n            # Issue #2623/PR #2637: Add argument names to enum_ methods\n            assert \"arg0\" not in (attr.__doc__ or \"\")\n\n\ndef test_str_signature():\n    for enum_type in [m.ScopedEnum, m.UnscopedEnum]:\n        assert enum_type.__str__.__doc__.startswith(\"__str__\")\n\n\ndef test_generated_dunder_methods_pos_only():\n    for enum_type in [m.ScopedEnum, m.UnscopedEnum]:\n        for binary_op in [\n            \"__eq__\",\n            \"__ne__\",\n            \"__ge__\",\n            \"__gt__\",\n            \"__lt__\",\n            \"__le__\",\n            \"__and__\",\n            \"__rand__\",\n            # \"__or__\",  # fail with some compilers (__doc__ = \"Return self|value.\")\n            # \"__ror__\",  # fail with some compilers (__doc__ = \"Return value|self.\")\n            \"__xor__\",\n            \"__rxor__\",\n            \"__rxor__\",\n        ]:\n            method = getattr(enum_type, binary_op, None)\n            if method is not None:\n                # 1) The docs must start with the name of the op.\n                assert (\n                    re.match(\n                        rf\"^{binary_op}\\(\",\n                        method.__doc__,\n                    )\n                    is not None\n                )\n                # 2) The docs must contain the op's signature. This is a separate check\n                # and not anchored at the start because the op may be overloaded.\n                assert (\n                    re.search(\n                        rf\"{binary_op}\\(self: [\\w\\.]+, other: [\\w\\.]+, /\\)\",\n                        method.__doc__,\n                    )\n                    is not None\n                )\n        for unary_op in [\n            \"__int__\",\n            \"__index__\",\n            \"__hash__\",\n            \"__str__\",\n            \"__repr__\",\n        ]:\n            method = getattr(enum_type, unary_op, None)\n            if method is not None:\n                assert (\n                    re.match(\n                        rf\"^{unary_op}\\(self: [\\w\\.]+, /\\)\",\n                        method.__doc__,\n                    )\n                    is not None\n                )\n        assert (\n            re.match(\n                r\"^__getstate__\\(self: [\\w\\.]+, /\\)\",\n                enum_type.__getstate__.__doc__,\n            )\n            is not None\n        )\n        assert (\n            re.match(\n                r\"^__setstate__\\(self: [\\w\\.]+, state: [\\w\\. \\|]+, /\\)\",\n                enum_type.__setstate__.__doc__,\n            )\n            is not None\n        )\n\n\n@pytest.mark.skipif(\n    isinstance(m.obj_cast_UnscopedEnum_ptr, str), reason=m.obj_cast_UnscopedEnum_ptr\n)\ndef test_obj_cast_unscoped_enum_ptr():\n    assert m.obj_cast_UnscopedEnum_ptr(m.UnscopedEnum.ETwo) == 2\n    assert m.obj_cast_UnscopedEnum_ptr(m.UnscopedEnum.EOne) == 1\n    assert m.obj_cast_UnscopedEnum_ptr(None) == 0\n"
  },
  {
    "path": "tests/test_eval.cpp",
    "content": "/*\n    tests/test_eval.cpp -- Usage of eval() and eval_file()\n\n    Copyright (c) 2016 Klemens D. Morgenstern\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/eval.h>\n\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\nTEST_SUBMODULE(eval_, m) {\n    // test_evals\n\n    auto global = py::dict(py::module_::import(\"__main__\").attr(\"__dict__\"));\n\n    m.def(\"test_eval_statements\", [global]() {\n        auto local = py::dict();\n        local[\"call_test\"] = py::cpp_function([&]() -> int { return 42; });\n\n        // Regular string literal\n        py::exec(\"message = 'Hello World!'\\n\"\n                 \"x = call_test()\",\n                 global,\n                 local);\n\n        // Multi-line raw string literal\n        py::exec(R\"(\n            if x == 42:\n                print(message)\n            else:\n                raise RuntimeError\n            )\",\n                 global,\n                 local);\n        auto x = local[\"x\"].cast<int>();\n\n        return x == 42;\n    });\n\n    m.def(\"test_eval\", [global]() {\n        auto local = py::dict();\n        local[\"x\"] = py::int_(42);\n        auto x = py::eval(\"x\", global, local);\n        return x.cast<int>() == 42;\n    });\n\n    m.def(\"test_eval_single_statement\", []() {\n        auto local = py::dict();\n        local[\"call_test\"] = py::cpp_function([&]() -> int { return 42; });\n\n        auto result = py::eval<py::eval_single_statement>(\"x = call_test()\", py::dict(), local);\n        auto x = local[\"x\"].cast<int>();\n        return result.is_none() && x == 42;\n    });\n\n    m.def(\"test_eval_file\", [global](py::str filename) {\n        auto local = py::dict();\n        local[\"y\"] = py::int_(43);\n\n        int val_out = 0;\n        local[\"call_test2\"] = py::cpp_function([&](int value) { val_out = value; });\n\n        auto result = py::eval_file(std::move(filename), global, local);\n        return val_out == 43 && result.is_none();\n    });\n\n    m.def(\"test_eval_failure\", []() {\n        try {\n            py::eval(\"nonsense code ...\");\n        } catch (py::error_already_set &) {\n            return true;\n        }\n        return false;\n    });\n\n    m.def(\"test_eval_file_failure\", []() {\n        try {\n            py::eval_file(\"non-existing file\");\n        } catch (std::exception &) {\n            return true;\n        }\n        return false;\n    });\n\n    // test_eval_empty_globals\n    m.def(\"eval_empty_globals\", [](py::object global) {\n        if (global.is_none()) {\n            global = py::dict();\n        }\n        auto int_class = py::eval(\"isinstance(42, int)\", global);\n        return global;\n    });\n\n    // test_eval_closure\n    m.def(\"test_eval_closure\", []() {\n        py::dict global;\n        global[\"closure_value\"] = 42;\n        py::dict local;\n        local[\"closure_value\"] = 0;\n        py::exec(R\"(\n            local_value = closure_value\n\n            def func_global():\n                return closure_value\n\n            def func_local():\n                return local_value\n            )\",\n                 global,\n                 local);\n        return std::make_pair(global, local);\n    });\n}\n"
  },
  {
    "path": "tests/test_eval.py",
    "content": "from __future__ import annotations\n\nimport os\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import eval_ as m\n\n\ndef test_evals(capture):\n    with capture:\n        assert m.test_eval_statements()\n    assert capture == \"Hello World!\"\n\n    assert m.test_eval()\n    assert m.test_eval_single_statement()\n\n    assert m.test_eval_failure()\n\n\n@pytest.mark.xfail(\"env.PYPY or env.GRAALPY\", raises=RuntimeError)\ndef test_eval_file():\n    filename = os.path.join(os.path.dirname(__file__), \"test_eval_call.py\")\n    assert m.test_eval_file(filename)\n\n    assert m.test_eval_file_failure()\n\n\ndef test_eval_empty_globals():\n    assert \"__builtins__\" in m.eval_empty_globals(None)\n\n    g = {}\n    assert \"__builtins__\" in m.eval_empty_globals(g)\n    assert \"__builtins__\" in g\n\n\ndef test_eval_closure():\n    global_, local = m.test_eval_closure()\n\n    assert global_[\"closure_value\"] == 42\n    assert local[\"closure_value\"] == 0\n\n    assert \"local_value\" not in global_\n    assert local[\"local_value\"] == 0\n\n    assert \"func_global\" not in global_\n    assert local[\"func_global\"]() == 42\n\n    assert \"func_local\" not in global_\n    with pytest.raises(NameError):\n        local[\"func_local\"]()\n"
  },
  {
    "path": "tests/test_eval_call.py",
    "content": "# This file is called from 'test_eval.py'\nfrom __future__ import annotations\n\nif \"call_test2\" in locals():\n    call_test2(y)  # noqa: F821 undefined name\n"
  },
  {
    "path": "tests/test_exceptions.cpp",
    "content": "/*\n    tests/test_custom-exceptions.cpp -- exception translation\n\n    Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n#include <pybind11/gil_safe_call_once.h>\n\n#include \"test_exceptions.h\"\n\n#include \"local_bindings.h\"\n#include \"pybind11_tests.h\"\n\n#include <exception>\n#include <stdexcept>\n#include <utility>\n\n// A type that should be raised as an exception in Python\nclass MyException : public std::exception {\npublic:\n    explicit MyException(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\nclass MyExceptionUseDeprecatedOperatorCall : public MyException {\n    using MyException::MyException;\n};\n\n// A type that should be translated to a standard Python exception\nclass MyException2 : public std::exception {\npublic:\n    explicit MyException2(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\n// A type that is not derived from std::exception (and is thus unknown)\nclass MyException3 {\npublic:\n    explicit MyException3(const char *m) : message{m} {}\n    virtual const char *what() const noexcept { return message.c_str(); }\n    // Rule of 5 BEGIN: to preempt compiler warnings.\n    MyException3(const MyException3 &) = default;\n    MyException3(MyException3 &&) = default;\n    MyException3 &operator=(const MyException3 &) = default;\n    MyException3 &operator=(MyException3 &&) = default;\n    virtual ~MyException3() = default;\n    // Rule of 5 END.\nprivate:\n    std::string message = \"\";\n};\n\n// A type that should be translated to MyException\n// and delegated to its exception translator\nclass MyException4 : public std::exception {\npublic:\n    explicit MyException4(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\n// Like the above, but declared via the helper function\nclass MyException5 : public std::logic_error {\npublic:\n    explicit MyException5(const std::string &what) : std::logic_error(what) {}\n};\n\n// Inherits from MyException5\nclass MyException5_1 : public MyException5 {\n    using MyException5::MyException5;\n};\n\n// Exception that will be caught via the module local translator.\nclass MyException6 : public std::exception {\npublic:\n    explicit MyException6(const char *m) : message{m} {}\n    const char *what() const noexcept override { return message.c_str(); }\n\nprivate:\n    std::string message = \"\";\n};\n\nstruct PythonCallInDestructor {\n    explicit PythonCallInDestructor(const py::dict &d) : d(d) {}\n    ~PythonCallInDestructor() { d[\"good\"] = true; }\n\n    py::dict d;\n};\n\nstruct PythonAlreadySetInDestructor {\n    explicit PythonAlreadySetInDestructor(const py::str &s) : s(s) {}\n    ~PythonAlreadySetInDestructor() {\n        py::dict foo;\n        try {\n            // Assign to a py::object to force read access of nonexistent dict entry\n            py::object o = foo[\"bar\"];\n        } catch (py::error_already_set &ex) {\n            ex.discard_as_unraisable(s);\n        }\n    }\n\n    py::str s;\n};\n\nstruct CustomData {\n    explicit CustomData(const std::string &a) : a(a) {}\n    std::string a;\n};\n\nstruct MyException7 {\n    explicit MyException7(const CustomData &message) : message(message) {}\n    CustomData message;\n};\n\nTEST_SUBMODULE(exceptions, m) {\n    m.def(\"throw_std_exception\",\n          []() { throw std::runtime_error(\"This exception was intentionally thrown.\"); });\n\n    // PLEASE KEEP IN SYNC with docs/advanced/exceptions.rst\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> ex_storage;\n    ex_storage.call_once_and_store_result(\n        [&]() { return py::exception<MyException>(m, \"MyException\"); });\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyException &e) {\n            // Set MyException as the active python error\n            py::set_error(ex_storage.get_stored(), e.what());\n        }\n    });\n\n    // Same as above, but using the deprecated `py::exception<>::operator()`\n    // We want to be sure it still works, until it's removed.\n    static const auto *const exd = new py::exception<MyExceptionUseDeprecatedOperatorCall>(\n        m, \"MyExceptionUseDeprecatedOperatorCall\");\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyExceptionUseDeprecatedOperatorCall &e) {\n#if defined(__INTEL_COMPILER) || defined(__NVCOMPILER)\n            // It is not worth the trouble dealing with warning suppressions for these compilers.\n            // Falling back to the recommended approach to keep the test code simple.\n            py::set_error(*exd, e.what());\n#else\n            PYBIND11_WARNING_PUSH\n            PYBIND11_WARNING_DISABLE_CLANG(\"-Wdeprecated-declarations\")\n            PYBIND11_WARNING_DISABLE_GCC(\"-Wdeprecated-declarations\")\n            PYBIND11_WARNING_DISABLE_MSVC(4996)\n            (*exd)(e.what());\n            PYBIND11_WARNING_POP\n#endif\n        }\n    });\n\n    // register new translator for MyException2\n    // no need to store anything here because this type will\n    // never by visible from Python\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyException2 &e) {\n            // Translate this exception to a standard RuntimeError\n            py::set_error(PyExc_RuntimeError, e.what());\n        }\n    });\n\n    // register new translator for MyException4\n    // which will catch it and delegate to the previously registered\n    // translator for MyException by throwing a new exception\n    py::register_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyException4 &e) {\n            throw MyException(e.what());\n        }\n    });\n\n    // A simple exception translation:\n    auto ex5 = py::register_exception<MyException5>(m, \"MyException5\");\n    // A slightly more complicated one that declares MyException5_1 as a subclass of MyException5\n    py::register_exception<MyException5_1>(m, \"MyException5_1\", ex5.ptr());\n\n    // py::register_local_exception<LocalSimpleException>(m, \"LocalSimpleException\")\n\n    py::register_local_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyException6 &e) {\n            py::set_error(PyExc_RuntimeError, e.what());\n        }\n    });\n\n    m.def(\"throws1\",\n          []() { throw MyException(\"this error should go to py::exception<MyException>\"); });\n    m.def(\"throws1d\", []() {\n        throw MyExceptionUseDeprecatedOperatorCall(\n            \"this error should go to py::exception<MyExceptionUseDeprecatedOperatorCall>\");\n    });\n    m.def(\"throws2\",\n          []() { throw MyException2(\"this error should go to a standard Python exception\"); });\n    m.def(\"throws3\", []() { throw MyException3(\"this error cannot be translated\"); });\n    m.def(\"throws4\", []() { throw MyException4(\"this error is rethrown\"); });\n    m.def(\"throws5\",\n          []() { throw MyException5(\"this is a helper-defined translated exception\"); });\n    m.def(\"throws5_1\", []() { throw MyException5_1(\"MyException5 subclass\"); });\n    m.def(\"throws6\", []() { throw MyException6(\"MyException6 only handled in this module\"); });\n    m.def(\"throws_logic_error\", []() {\n        throw std::logic_error(\"this error should fall through to the standard handler\");\n    });\n    m.def(\"throws_overflow_error\", []() { throw std::overflow_error(\"\"); });\n    m.def(\"throws_local_error\", []() { throw LocalException(\"never caught\"); });\n    m.def(\"throws_local_simple_error\", []() { throw LocalSimpleException(\"this mod\"); });\n    m.def(\"exception_matches\", []() {\n        py::dict foo;\n        try {\n            // Assign to a py::object to force read access of nonexistent dict entry\n            py::object o = foo[\"bar\"];\n        } catch (py::error_already_set &ex) {\n            if (!ex.matches(PyExc_KeyError)) {\n                throw;\n            }\n            return true;\n        }\n        return false;\n    });\n    m.def(\"exception_matches_base\", []() {\n        py::dict foo;\n        try {\n            // Assign to a py::object to force read access of nonexistent dict entry\n            py::object o = foo[\"bar\"];\n        } catch (py::error_already_set &ex) {\n            if (!ex.matches(PyExc_Exception)) {\n                throw;\n            }\n            return true;\n        }\n        return false;\n    });\n    m.def(\"modulenotfound_exception_matches_base\", []() {\n        try {\n            // On Python >= 3.6, this raises a ModuleNotFoundError, a subclass of ImportError\n            py::module_::import(\"nonexistent\");\n        } catch (py::error_already_set &ex) {\n            if (!ex.matches(PyExc_ImportError)) {\n                throw;\n            }\n            return true;\n        }\n        return false;\n    });\n\n    m.def(\"throw_already_set\", [](bool err) {\n        if (err) {\n            py::set_error(PyExc_ValueError, \"foo\");\n        }\n        try {\n            throw py::error_already_set();\n        } catch (const std::runtime_error &e) {\n            if ((err && e.what() != std::string(\"ValueError: foo\"))\n                || (!err\n                    && e.what()\n                           != std::string(\"Internal error: pybind11::error_already_set called \"\n                                          \"while Python error indicator not set.\"))) {\n                PyErr_Clear();\n                throw std::runtime_error(\"error message mismatch\");\n            }\n        }\n        PyErr_Clear();\n        if (err) {\n            py::set_error(PyExc_ValueError, \"foo\");\n        }\n        throw py::error_already_set();\n    });\n\n    m.def(\"python_call_in_destructor\", [](const py::dict &d) {\n        bool retval = false;\n        try {\n            PythonCallInDestructor set_dict_in_destructor(d);\n            py::set_error(PyExc_ValueError, \"foo\");\n            throw py::error_already_set();\n        } catch (const py::error_already_set &) {\n            retval = true;\n        }\n        return retval;\n    });\n\n    m.def(\"python_alreadyset_in_destructor\", [](const py::str &s) {\n        PythonAlreadySetInDestructor alreadyset_in_destructor(s);\n        return true;\n    });\n\n    // test_nested_throws\n    m.def(\"try_catch\",\n          [m](const py::object &exc_type, const py::function &f, const py::args &args) {\n              try {\n                  f(*args);\n              } catch (py::error_already_set &ex) {\n                  if (ex.matches(exc_type)) {\n                      py::print(ex.what());\n                  } else {\n                      // Simply `throw;` also works and is better, but using `throw ex;`\n                      // here to cover that situation (as observed in the wild).\n                      throw ex; // Invokes the copy ctor.\n                  }\n              }\n          });\n\n    // Test repr that cannot be displayed\n    m.def(\"simple_bool_passthrough\", [](bool x) { return x; });\n\n    m.def(\"throw_should_be_translated_to_key_error\", []() { throw shared_exception(); });\n\n    m.def(\"raise_from\", []() {\n        py::set_error(PyExc_ValueError, \"inner\");\n        py::raise_from(PyExc_ValueError, \"outer\");\n        throw py::error_already_set();\n    });\n\n    m.def(\"raise_from_already_set\", []() {\n        try {\n            py::set_error(PyExc_ValueError, \"inner\");\n            throw py::error_already_set();\n        } catch (py::error_already_set &e) {\n            py::raise_from(e, PyExc_ValueError, \"outer\");\n            throw py::error_already_set();\n        }\n    });\n\n    m.def(\"throw_nested_exception\", []() {\n        try {\n            throw std::runtime_error(\"Inner Exception\");\n        } catch (const std::runtime_error &) {\n            std::throw_with_nested(std::runtime_error(\"Outer Exception\"));\n        }\n    });\n\n    m.def(\"error_already_set_what\", [](const py::object &exc_type, const py::object &exc_value) {\n        py::set_error(exc_type, exc_value);\n        std::string what = py::error_already_set().what();\n        bool py_err_set_after_what = (PyErr_Occurred() != nullptr);\n        PyErr_Clear();\n        return py::make_tuple(std::move(what), py_err_set_after_what);\n    });\n\n    m.def(\"test_cross_module_interleaved_error_already_set\", []() {\n        auto cm = py::module_::import(\"cross_module_interleaved_error_already_set\");\n        auto interleaved_error_already_set\n            = reinterpret_cast<void (*)()>(PyLong_AsVoidPtr(cm.attr(\"funcaddr\").ptr()));\n        interleaved_error_already_set();\n    });\n\n    m.def(\"test_error_already_set_double_restore\", [](bool dry_run) {\n        py::set_error(PyExc_ValueError, \"Random error.\");\n        py::error_already_set e;\n        e.restore();\n        PyErr_Clear();\n        if (!dry_run) {\n            e.restore();\n        }\n    });\n\n    // https://github.com/pybind/pybind11/issues/4075\n    m.def(\"test_pypy_oserror_normalization\", []() {\n        try {\n            py::module_::import(\"io\").attr(\"open\")(\"this_filename_must_not_exist\", \"r\");\n        } catch (const py::error_already_set &e) {\n            return py::str(e.what()); // str must be built before e goes out of scope.\n        }\n        return py::str(\"UNEXPECTED\");\n    });\n\n    m.def(\"test_fn_cast_int\", [](const py::function &fn) {\n        // function returns None instead of int, should give a useful error message\n        fn().cast<int>();\n    });\n\n    // m.def(\"pass_exception_void\", [](const py::exception<void>&) {}); // Does not compile.\n    m.def(\"return_exception_void\", []() { return py::exception<void>(); });\n\n    m.def(\"throws7\", []() {\n        auto data = CustomData(\"abc\");\n        throw MyException7(data);\n    });\n\n    py::class_<CustomData>(m, \"CustomData\", py::module_local())\n        .def(py::init<const std::string &>())\n        .def_readwrite(\"a\", &CustomData::a);\n\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object>\n        PythonMyException7_storage;\n    PythonMyException7_storage.call_once_and_store_result([&]() {\n        auto mod = py::module_::import(\"custom_exceptions\");\n        py::object obj = mod.attr(\"PythonMyException7\");\n        return obj;\n    });\n\n    py::register_local_exception_translator([](std::exception_ptr p) {\n        try {\n            if (p) {\n                std::rethrow_exception(p);\n            }\n        } catch (const MyException7 &e) {\n            auto exc_type = PythonMyException7_storage.get_stored();\n            py::object exc_inst = exc_type(e.message);\n            PyErr_SetObject(PyExc_Exception, exc_inst.ptr());\n        }\n    });\n}\n"
  },
  {
    "path": "tests/test_exceptions.h",
    "content": "#pragma once\n#include \"pybind11_tests.h\"\n\n#include <stdexcept>\n\n// shared exceptions for cross_module_tests\n\nclass PYBIND11_EXPORT_EXCEPTION shared_exception : public pybind11::builtin_exception {\npublic:\n    using builtin_exception::builtin_exception;\n    explicit shared_exception() : shared_exception(\"\") {}\n    void set_error() const override { py::set_error(PyExc_RuntimeError, what()); }\n};\n"
  },
  {
    "path": "tests/test_exceptions.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\nfrom custom_exceptions import PythonMyException7\n\nimport env\nimport pybind11_cross_module_tests as cm\nimport pybind11_tests\nfrom pybind11_tests import exceptions as m\n\n\ndef test_std_exception(msg):\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throw_std_exception()\n    assert msg(excinfo.value) == \"This exception was intentionally thrown.\"\n\n\ndef test_error_already_set(msg):\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throw_already_set(False)\n    assert (\n        msg(excinfo.value)\n        == \"Internal error: pybind11::error_already_set called while Python error indicator not set.\"\n    )\n\n    with pytest.raises(ValueError) as excinfo:\n        m.throw_already_set(True)\n    assert msg(excinfo.value) == \"foo\"\n\n\ndef test_raise_from(msg):\n    with pytest.raises(ValueError) as excinfo:\n        m.raise_from()\n    assert msg(excinfo.value) == \"outer\"\n    assert msg(excinfo.value.__cause__) == \"inner\"\n\n\ndef test_raise_from_already_set(msg):\n    with pytest.raises(ValueError) as excinfo:\n        m.raise_from_already_set()\n    assert msg(excinfo.value) == \"outer\"\n    assert msg(excinfo.value.__cause__) == \"inner\"\n\n\ndef test_cross_module_exceptions(msg):\n    with pytest.raises(RuntimeError) as excinfo:\n        cm.raise_runtime_error()\n    assert str(excinfo.value) == \"My runtime error\"\n\n    with pytest.raises(ValueError) as excinfo:\n        cm.raise_value_error()\n    assert str(excinfo.value) == \"My value error\"\n\n    with pytest.raises(ValueError) as excinfo:\n        cm.throw_pybind_value_error()\n    assert str(excinfo.value) == \"pybind11 value error\"\n\n    with pytest.raises(TypeError) as excinfo:\n        cm.throw_pybind_type_error()\n    assert str(excinfo.value) == \"pybind11 type error\"\n\n    with pytest.raises(StopIteration) as excinfo:\n        cm.throw_stop_iteration()\n\n    with pytest.raises(cm.LocalSimpleException) as excinfo:\n        cm.throw_local_simple_error()\n    assert msg(excinfo.value) == \"external mod\"\n\n    with pytest.raises(KeyError) as excinfo:\n        cm.throw_local_error()\n    # KeyError is a repr of the key, so it has an extra set of quotes\n    assert str(excinfo.value) == \"'just local'\"\n\n\n# TODO: FIXME\n@pytest.mark.xfail(\n    \"(env.MACOS and env.PYPY) or env.ANDROID or env.FREEBSD\",\n    raises=RuntimeError,\n    reason=\"See Issue #2847, PR #2999, PR #4324, PR #5925\",\n    strict=not env.PYPY,  # PR 5569\n)\ndef test_cross_module_exception_translator():\n    with pytest.raises(KeyError):\n        # translator registered in cross_module_tests\n        m.throw_should_be_translated_to_key_error()\n\n\ndef test_python_call_in_catch():\n    d = {}\n    assert m.python_call_in_destructor(d) is True\n    assert d[\"good\"] is True\n\n\ndef ignore_pytest_unraisable_warning(f):\n    unraisable = \"PytestUnraisableExceptionWarning\"\n    if hasattr(pytest, unraisable):  # Python >= 3.8 and pytest >= 6\n        dec = pytest.mark.filterwarnings(f\"ignore::pytest.{unraisable}\")\n        return dec(f)\n    return f\n\n\n# TODO: find out why this fails on PyPy, https://foss.heptapod.net/pypy/pypy/-/issues/3583\n@pytest.mark.xfail(env.PYPY, reason=\"Failure on PyPy 3.8 (7.3.7)\", strict=False)\n@ignore_pytest_unraisable_warning\ndef test_python_alreadyset_in_destructor(monkeypatch, capsys):\n    triggered = False\n\n    # Don't take `sys.unraisablehook`, as that's overwritten by pytest\n    default_hook = sys.__unraisablehook__\n\n    def hook(unraisable_hook_args):\n        exc_type, exc_value, exc_tb, err_msg, obj = unraisable_hook_args\n        if obj == \"already_set demo\":\n            nonlocal triggered\n            triggered = True\n        default_hook(unraisable_hook_args)\n        return\n\n    # Use monkeypatch so pytest can apply and remove the patch as appropriate\n    monkeypatch.setattr(sys, \"unraisablehook\", hook)\n\n    assert m.python_alreadyset_in_destructor(\"already_set demo\") is True\n    assert triggered is True\n\n    _, captured_stderr = capsys.readouterr()\n    assert captured_stderr.startswith(\"Exception ignored in: 'already_set demo'\")\n    assert captured_stderr.rstrip().endswith(\"KeyError: 'bar'\")\n\n\ndef test_exception_matches():\n    assert m.exception_matches()\n    assert m.exception_matches_base()\n    assert m.modulenotfound_exception_matches_base()\n\n\ndef test_custom(msg):\n    # Can we catch a MyException?\n    with pytest.raises(m.MyException) as excinfo:\n        m.throws1()\n    assert msg(excinfo.value) == \"this error should go to py::exception<MyException>\"\n\n    # Can we catch a MyExceptionUseDeprecatedOperatorCall?\n    with pytest.raises(m.MyExceptionUseDeprecatedOperatorCall) as excinfo:\n        m.throws1d()\n    assert (\n        msg(excinfo.value)\n        == \"this error should go to py::exception<MyExceptionUseDeprecatedOperatorCall>\"\n    )\n\n    # Can we translate to standard Python exceptions?\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throws2()\n    assert msg(excinfo.value) == \"this error should go to a standard Python exception\"\n\n    # Can we handle unknown exceptions?\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throws3()\n    assert msg(excinfo.value) == \"Caught an unknown exception!\"\n\n    # Can we delegate to another handler by rethrowing?\n    with pytest.raises(m.MyException) as excinfo:\n        m.throws4()\n    assert msg(excinfo.value) == \"this error is rethrown\"\n\n    # Can we fall-through to the default handler?\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throws_logic_error()\n    assert (\n        msg(excinfo.value) == \"this error should fall through to the standard handler\"\n    )\n\n    # OverFlow error translation.\n    with pytest.raises(OverflowError) as excinfo:\n        m.throws_overflow_error()\n\n    # Can we handle a helper-declared exception?\n    with pytest.raises(m.MyException5) as excinfo:\n        m.throws5()\n    assert msg(excinfo.value) == \"this is a helper-defined translated exception\"\n\n    # Exception subclassing:\n    with pytest.raises(m.MyException5) as excinfo:\n        m.throws5_1()\n    assert msg(excinfo.value) == \"MyException5 subclass\"\n    assert isinstance(excinfo.value, m.MyException5_1)\n\n    with pytest.raises(m.MyException5_1) as excinfo:\n        m.throws5_1()\n    assert msg(excinfo.value) == \"MyException5 subclass\"\n\n    with pytest.raises(m.MyException5) as excinfo:  # noqa: PT012\n        try:\n            m.throws5()\n        except m.MyException5_1 as err:\n            raise RuntimeError(\"Exception error: caught child from parent\") from err\n    assert msg(excinfo.value) == \"this is a helper-defined translated exception\"\n\n    with pytest.raises(PythonMyException7) as excinfo:\n        m.throws7()\n    assert msg(excinfo.value) == \"[PythonMyException7]: abc\"\n\n\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should get fixed on GraalPy side\")\ndef test_nested_throws(capture):\n    \"\"\"Tests nested (e.g. C++ -> Python -> C++) exception handling\"\"\"\n\n    def throw_myex():\n        raise m.MyException(\"nested error\")\n\n    def throw_myex5():\n        raise m.MyException5(\"nested error 5\")\n\n    # In the comments below, the exception is caught in the first step, thrown in the last step\n\n    # C++ -> Python\n    with capture:\n        m.try_catch(m.MyException5, throw_myex5)\n    assert str(capture).startswith(\"MyException5: nested error 5\")\n\n    # Python -> C++ -> Python\n    with pytest.raises(m.MyException) as excinfo:\n        m.try_catch(m.MyException5, throw_myex)\n    assert str(excinfo.value) == \"nested error\"\n\n    def pycatch(exctype, f, *args):  # noqa: ARG001\n        try:\n            f(*args)\n        except m.MyException as e:\n            print(e)\n\n    # C++ -> Python -> C++ -> Python\n    with capture:\n        m.try_catch(\n            m.MyException5,\n            pycatch,\n            m.MyException,\n            m.try_catch,\n            m.MyException,\n            throw_myex5,\n        )\n    assert str(capture).startswith(\"MyException5: nested error 5\")\n\n    # C++ -> Python -> C++\n    with capture:\n        m.try_catch(m.MyException, pycatch, m.MyException5, m.throws4)\n    assert capture == \"this error is rethrown\"\n\n    # Python -> C++ -> Python -> C++\n    with pytest.raises(m.MyException5) as excinfo:\n        m.try_catch(m.MyException, pycatch, m.MyException, m.throws5)\n    assert str(excinfo.value) == \"this is a helper-defined translated exception\"\n\n\n# TODO: Investigate this crash, see pybind/pybind11#5062 for background\n@pytest.mark.skipif(\n    sys.platform.startswith(\"win32\") and \"Clang\" in pybind11_tests.compiler_info,\n    reason=\"Started segfaulting February 2024\",\n)\ndef test_throw_nested_exception():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throw_nested_exception()\n    assert str(excinfo.value) == \"Outer Exception\"\n    assert str(excinfo.value.__cause__) == \"Inner Exception\"\n\n\n# This can often happen if you wrap a pybind11 class in a Python wrapper\ndef test_invalid_repr():\n    class MyRepr:\n        def __repr__(self):\n            raise AttributeError(\"Example error\")\n\n    with pytest.raises(TypeError):\n        m.simple_bool_passthrough(MyRepr())\n\n\ndef test_local_translator(msg):\n    \"\"\"Tests that a local translator works and that the local translator from\n    the cross module is not applied\"\"\"\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throws6()\n    assert msg(excinfo.value) == \"MyException6 only handled in this module\"\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.throws_local_error()\n    assert not isinstance(excinfo.value, KeyError)\n    assert msg(excinfo.value) == \"never caught\"\n\n    with pytest.raises(Exception) as excinfo:\n        m.throws_local_simple_error()\n    assert not isinstance(excinfo.value, cm.LocalSimpleException)\n    assert msg(excinfo.value) == \"this mod\"\n\n\ndef test_error_already_set_message_with_unicode_surrogate():  # Issue #4288\n    assert m.error_already_set_what(RuntimeError, \"\\ud927\") == (\n        \"RuntimeError: \\\\ud927\",\n        False,\n    )\n\n\ndef test_error_already_set_message_with_malformed_utf8():\n    assert m.error_already_set_what(RuntimeError, b\"\\x80\") == (\n        \"RuntimeError: b'\\\\x80'\",\n        False,\n    )\n\n\nclass FlakyException(Exception):\n    def __init__(self, failure_point):\n        if failure_point == \"failure_point_init\":\n            raise ValueError(\"triggered_failure_point_init\")\n        self.failure_point = failure_point\n\n    def __str__(self):\n        if self.failure_point == \"failure_point_str\":\n            raise ValueError(\"triggered_failure_point_str\")\n        return \"FlakyException.__str__\"\n\n\n@pytest.mark.parametrize(\n    (\"exc_type\", \"exc_value\", \"expected_what\"),\n    [\n        (ValueError, \"plain_str\", \"ValueError: plain_str\"),\n        (ValueError, (\"tuple_elem\",), \"ValueError: tuple_elem\"),\n        (FlakyException, (\"happy\",), \"FlakyException: FlakyException.__str__\"),\n    ],\n)\ndef test_error_already_set_what_with_happy_exceptions(\n    exc_type, exc_value, expected_what\n):\n    what, py_err_set_after_what = m.error_already_set_what(exc_type, exc_value)\n    assert not py_err_set_after_what\n    assert what == expected_what\n\n\ndef _test_flaky_exception_failure_point_init_before_py_3_12():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.error_already_set_what(FlakyException, (\"failure_point_init\",))\n    lines = str(excinfo.value).splitlines()\n    # PyErr_NormalizeException replaces the original FlakyException with ValueError:\n    assert lines[:3] == [\n        \"pybind11::error_already_set: MISMATCH of original and normalized active exception types:\"\n        \" ORIGINAL FlakyException REPLACED BY ValueError: triggered_failure_point_init\",\n        \"\",\n        \"At:\",\n    ]\n    # Checking the first two lines of the traceback as formatted in error_string():\n    assert \"test_exceptions.py(\" in lines[3]\n    assert lines[3].endswith(\"): __init__\")\n    assert lines[4].endswith(\n        \"): _test_flaky_exception_failure_point_init_before_py_3_12\"\n    )\n\n\ndef _test_flaky_exception_failure_point_init_py_3_12():\n    # Behavior change in Python 3.12: https://github.com/python/cpython/issues/102594\n    what, py_err_set_after_what = m.error_already_set_what(\n        FlakyException, (\"failure_point_init\",)\n    )\n    assert not py_err_set_after_what\n    lines = what.splitlines()\n    assert lines[0].endswith(\"ValueError[WITH __notes__]: triggered_failure_point_init\")\n    assert lines[1] == \"__notes__ (len=1):\"\n    assert \"Normalization failed:\" in lines[2]\n    assert \"FlakyException\" in lines[2]\n\n\n@pytest.mark.skipif(\n    \"env.PYPY and sys.version_info[:2] < (3, 12)\",\n    reason=\"PyErr_NormalizeException Segmentation fault\",\n)\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should be fixed on GraalPy side\")\ndef test_flaky_exception_failure_point_init():\n    if sys.version_info[:2] < (3, 12):\n        _test_flaky_exception_failure_point_init_before_py_3_12()\n    else:\n        _test_flaky_exception_failure_point_init_py_3_12()\n\n\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should be fixed on GraalPy side\")\ndef test_flaky_exception_failure_point_str():\n    what, py_err_set_after_what = m.error_already_set_what(\n        FlakyException, (\"failure_point_str\",)\n    )\n    assert not py_err_set_after_what\n    lines = what.splitlines()\n    n = 3 if env.PYPY and len(lines) == 3 else 5\n    assert (\n        lines[:n]\n        == [\n            \"FlakyException: <MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>\",\n            \"\",\n            \"MESSAGE UNAVAILABLE DUE TO EXCEPTION: ValueError: triggered_failure_point_str\",\n            \"\",\n            \"At:\",\n        ][:n]\n    )\n\n\ndef test_cross_module_interleaved_error_already_set():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.test_cross_module_interleaved_error_already_set()\n    assert str(excinfo.value) in (\n        \"2nd error.\",  # Almost all platforms.\n        \"RuntimeError: 2nd error.\",  # Some PyPy builds (seen under macOS).\n    )\n\n\ndef test_error_already_set_double_restore():\n    m.test_error_already_set_double_restore(True)  # dry_run\n    with pytest.raises(RuntimeError) as excinfo:\n        m.test_error_already_set_double_restore(False)\n    assert str(excinfo.value) == (\n        \"Internal error: pybind11::detail::error_fetch_and_normalize::restore()\"\n        \" called a second time. ORIGINAL ERROR: ValueError: Random error.\"\n    )\n\n\ndef test_pypy_oserror_normalization():\n    # https://github.com/pybind/pybind11/issues/4075\n    what = m.test_pypy_oserror_normalization()\n    assert \"this_filename_must_not_exist\" in what\n\n\ndef test_fn_cast_int_exception():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.test_fn_cast_int(lambda: None)\n\n    assert str(excinfo.value).startswith(\n        \"Unable to cast Python instance of type <class 'NoneType'> to C++ type\"\n    )\n\n\ndef test_return_exception_void():\n    with pytest.raises(TypeError) as excinfo:\n        m.return_exception_void()\n    assert \"Exception\" in str(excinfo.value)\n"
  },
  {
    "path": "tests/test_factory_constructors.cpp",
    "content": "/*\n    tests/test_factory_constructors.cpp -- tests construction from a factory function\n                                           via py::init_factory()\n\n    Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <cmath>\n#include <new>\n#include <utility>\n\n// Classes for testing python construction via C++ factory function:\n// Not publicly constructible, copyable, or movable:\nclass TestFactory1 {\n    friend class TestFactoryHelper;\n    TestFactory1() : value(\"(empty)\") { print_default_created(this); }\n    explicit TestFactory1(int v) : value(std::to_string(v)) { print_created(this, value); }\n    explicit TestFactory1(std::string v) : value(std::move(v)) { print_created(this, value); }\n\npublic:\n    std::string value;\n    TestFactory1(TestFactory1 &&) = delete;\n    TestFactory1(const TestFactory1 &) = delete;\n    TestFactory1 &operator=(TestFactory1 &&) = delete;\n    TestFactory1 &operator=(const TestFactory1 &) = delete;\n    ~TestFactory1() { print_destroyed(this); }\n};\n// Non-public construction, but moveable:\nclass TestFactory2 {\n    friend class TestFactoryHelper;\n    TestFactory2() : value(\"(empty2)\") { print_default_created(this); }\n    explicit TestFactory2(int v) : value(std::to_string(v)) { print_created(this, value); }\n    explicit TestFactory2(std::string v) : value(std::move(v)) { print_created(this, value); }\n\npublic:\n    TestFactory2(TestFactory2 &&m) noexcept : value{std::move(m.value)} {\n        print_move_created(this);\n    }\n    TestFactory2 &operator=(TestFactory2 &&m) noexcept {\n        value = std::move(m.value);\n        print_move_assigned(this);\n        return *this;\n    }\n    std::string value;\n    ~TestFactory2() { print_destroyed(this); }\n};\n// Mixed direct/factory construction:\nclass TestFactory3 {\nprotected:\n    friend class TestFactoryHelper;\n    TestFactory3() : value(\"(empty3)\") { print_default_created(this); }\n    explicit TestFactory3(int v) : value(std::to_string(v)) { print_created(this, value); }\n\npublic:\n    explicit TestFactory3(std::string v) : value(std::move(v)) { print_created(this, value); }\n    TestFactory3(TestFactory3 &&m) noexcept : value{std::move(m.value)} {\n        print_move_created(this);\n    }\n    TestFactory3 &operator=(TestFactory3 &&m) noexcept {\n        value = std::move(m.value);\n        print_move_assigned(this);\n        return *this;\n    }\n    std::string value;\n    virtual ~TestFactory3() { print_destroyed(this); }\n};\n// Inheritance test\nclass TestFactory4 : public TestFactory3 {\npublic:\n    TestFactory4() { print_default_created(this); }\n    explicit TestFactory4(int v) : TestFactory3(v) { print_created(this, v); }\n    ~TestFactory4() override { print_destroyed(this); }\n};\n// Another class for an invalid downcast test\nclass TestFactory5 : public TestFactory3 {\npublic:\n    explicit TestFactory5(int i) : TestFactory3(i) { print_created(this, i); }\n    ~TestFactory5() override { print_destroyed(this); }\n};\n\nclass TestFactory6 {\nprotected:\n    int value;\n    bool alias = false;\n\npublic:\n    explicit TestFactory6(int i) : value{i} { print_created(this, i); }\n    TestFactory6(TestFactory6 &&f) noexcept {\n        print_move_created(this);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = f.value;\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        alias = f.alias;\n    }\n    TestFactory6(const TestFactory6 &f) {\n        print_copy_created(this);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = f.value;\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        alias = f.alias;\n    }\n    virtual ~TestFactory6() { print_destroyed(this); }\n    virtual int get() { return value; }\n    bool has_alias() const { return alias; }\n};\nclass PyTF6 : public TestFactory6 {\npublic:\n    // Special constructor that allows the factory to construct a PyTF6 from a TestFactory6 only\n    // when an alias is needed:\n    explicit PyTF6(TestFactory6 &&base) : TestFactory6(std::move(base)) {\n        alias = true;\n        print_created(this, \"move\", value);\n    }\n    explicit PyTF6(int i) : TestFactory6(i) {\n        alias = true;\n        print_created(this, i);\n    }\n    PyTF6(PyTF6 &&f) noexcept : TestFactory6(std::move(f)) { print_move_created(this); }\n    PyTF6(const PyTF6 &f) : TestFactory6(f) { print_copy_created(this); }\n    explicit PyTF6(std::string s) : TestFactory6((int) s.size()) {\n        alias = true;\n        print_created(this, s);\n    }\n    ~PyTF6() override { print_destroyed(this); }\n    int get() override { PYBIND11_OVERRIDE(int, TestFactory6, get, /*no args*/); }\n};\n\nclass TestFactory7 {\nprotected:\n    int value;\n    bool alias = false;\n\npublic:\n    explicit TestFactory7(int i) : value{i} { print_created(this, i); }\n    TestFactory7(TestFactory7 &&f) noexcept {\n        print_move_created(this);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = f.value;\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        alias = f.alias;\n    }\n    TestFactory7(const TestFactory7 &f) {\n        print_copy_created(this);\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        value = f.value;\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        alias = f.alias;\n    }\n    virtual ~TestFactory7() { print_destroyed(this); }\n    virtual int get() { return value; }\n    bool has_alias() const { return alias; }\n};\nclass PyTF7 : public TestFactory7 {\npublic:\n    explicit PyTF7(int i) : TestFactory7(i) {\n        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n        alias = true;\n        print_created(this, i);\n    }\n    PyTF7(PyTF7 &&f) noexcept : TestFactory7(std::move(f)) { print_move_created(this); }\n    PyTF7(const PyTF7 &f) : TestFactory7(f) { print_copy_created(this); }\n    ~PyTF7() override { print_destroyed(this); }\n    int get() override { PYBIND11_OVERRIDE(int, TestFactory7, get, /*no args*/); }\n};\n\nclass TestFactoryHelper {\npublic:\n    // Non-movable, non-copyable type:\n    // Return via pointer:\n    static TestFactory1 *construct1() { return new TestFactory1(); }\n    // Holder:\n    static std::unique_ptr<TestFactory1> construct1(int a) {\n        return std::unique_ptr<TestFactory1>(new TestFactory1(a));\n    }\n    // pointer again\n    static TestFactory1 *construct1_string(std::string a) {\n        return new TestFactory1(std::move(a));\n    }\n\n    // Moveable type:\n    // pointer:\n    static TestFactory2 *construct2() { return new TestFactory2(); }\n    // holder:\n    static std::unique_ptr<TestFactory2> construct2(int a) {\n        return std::unique_ptr<TestFactory2>(new TestFactory2(a));\n    }\n    // by value moving:\n    static TestFactory2 construct2(std::string a) { return TestFactory2(std::move(a)); }\n\n    // shared_ptr holder type:\n    // pointer:\n    static TestFactory3 *construct3() { return new TestFactory3(); }\n    // holder:\n    static std::shared_ptr<TestFactory3> construct3(int a) {\n        return std::shared_ptr<TestFactory3>(new TestFactory3(a));\n    }\n};\n\nTEST_SUBMODULE(factory_constructors, m) {\n\n    // Define various trivial types to allow simpler overload resolution:\n    py::module_ m_tag = m.def_submodule(\"tag\");\n#define MAKE_TAG_TYPE(Name)                                                                       \\\n    struct Name##_tag {};                                                                         \\\n    py::class_<Name##_tag>(m_tag, #Name \"_tag\").def(py::init<>());                                \\\n    m_tag.attr(#Name) = py::cast(Name##_tag{})\n    MAKE_TAG_TYPE(pointer);\n    MAKE_TAG_TYPE(unique_ptr);\n    MAKE_TAG_TYPE(move);\n    MAKE_TAG_TYPE(shared_ptr);\n    MAKE_TAG_TYPE(derived);\n    MAKE_TAG_TYPE(TF4);\n    MAKE_TAG_TYPE(TF5);\n    MAKE_TAG_TYPE(null_ptr);\n    MAKE_TAG_TYPE(null_unique_ptr);\n    MAKE_TAG_TYPE(null_shared_ptr);\n    MAKE_TAG_TYPE(base);\n    MAKE_TAG_TYPE(invalid_base);\n    MAKE_TAG_TYPE(alias);\n    MAKE_TAG_TYPE(unaliasable);\n    MAKE_TAG_TYPE(mixed);\n\n    // test_init_factory_basic, test_bad_type\n    py::class_<TestFactory1>(m, \"TestFactory1\")\n        .def(py::init([](unique_ptr_tag, int v) { return TestFactoryHelper::construct1(v); }))\n        .def(py::init(&TestFactoryHelper::construct1_string)) // raw function pointer\n        .def(py::init([](pointer_tag) { return TestFactoryHelper::construct1(); }))\n        .def(py::init(\n            [](py::handle, int v, py::handle) { return TestFactoryHelper::construct1(v); }))\n        .def_readwrite(\"value\", &TestFactory1::value);\n    py::class_<TestFactory2>(m, \"TestFactory2\")\n        .def(py::init([](pointer_tag, int v) { return TestFactoryHelper::construct2(v); }))\n        .def(py::init([](unique_ptr_tag, std::string v) {\n            return TestFactoryHelper::construct2(std::move(v));\n        }))\n        .def(py::init([](move_tag) { return TestFactoryHelper::construct2(); }))\n        .def_readwrite(\"value\", &TestFactory2::value);\n\n    // Stateful & reused:\n    int c = 1;\n    auto c4a = [c](pointer_tag, TF4_tag, int a) {\n        (void) c;\n        return new TestFactory4(a);\n    };\n\n    // test_init_factory_basic, test_init_factory_casting\n    py::class_<TestFactory3, std::shared_ptr<TestFactory3>> pyTestFactory3(m, \"TestFactory3\");\n    pyTestFactory3\n        .def(py::init([](pointer_tag, int v) { return TestFactoryHelper::construct3(v); }))\n        .def(py::init([](shared_ptr_tag) { return TestFactoryHelper::construct3(); }));\n    ignoreOldStyleInitWarnings([&pyTestFactory3]() {\n        pyTestFactory3.def(\"__init__\", [](TestFactory3 &self, std::string v) {\n            new (&self) TestFactory3(std::move(v));\n        }); // placement-new ctor\n    });\n    pyTestFactory3\n        // factories returning a derived type:\n        .def(py::init(c4a)) // derived ptr\n        .def(py::init([](pointer_tag, TF5_tag, int a) { return new TestFactory5(a); }))\n        // derived shared ptr:\n        .def(py::init(\n            [](shared_ptr_tag, TF4_tag, int a) { return std::make_shared<TestFactory4>(a); }))\n        .def(py::init(\n            [](shared_ptr_tag, TF5_tag, int a) { return std::make_shared<TestFactory5>(a); }))\n\n        // Returns nullptr:\n        .def(py::init([](null_ptr_tag) { return (TestFactory3 *) nullptr; }))\n        .def(py::init([](null_unique_ptr_tag) { return std::unique_ptr<TestFactory3>(); }))\n        .def(py::init([](null_shared_ptr_tag) { return std::shared_ptr<TestFactory3>(); }))\n\n        .def_readwrite(\"value\", &TestFactory3::value);\n\n    // test_init_factory_casting\n    py::class_<TestFactory4, TestFactory3, std::shared_ptr<TestFactory4>>(m, \"TestFactory4\")\n        .def(py::init(c4a)) // pointer\n        ;\n\n    // Doesn't need to be registered, but registering makes getting ConstructorStats easier:\n    py::class_<TestFactory5, TestFactory3, std::shared_ptr<TestFactory5>>(m, \"TestFactory5\");\n\n    // test_init_factory_alias\n    // Alias testing\n    py::class_<TestFactory6, PyTF6>(m, \"TestFactory6\")\n        .def(py::init([](base_tag, int i) { return TestFactory6(i); }))\n        .def(py::init([](alias_tag, int i) { return PyTF6(i); }))\n        .def(py::init([](alias_tag, std::string s) { return PyTF6(std::move(s)); }))\n        .def(py::init([](alias_tag, pointer_tag, int i) { return new PyTF6(i); }))\n        .def(py::init([](base_tag, pointer_tag, int i) { return new TestFactory6(i); }))\n        .def(py::init(\n            [](base_tag, alias_tag, pointer_tag, int i) { return (TestFactory6 *) new PyTF6(i); }))\n\n        .def(\"get\", &TestFactory6::get)\n        .def(\"has_alias\", &TestFactory6::has_alias)\n\n        .def_static(\n            \"get_cstats\", &ConstructorStats::get<TestFactory6>, py::return_value_policy::reference)\n        .def_static(\n            \"get_alias_cstats\", &ConstructorStats::get<PyTF6>, py::return_value_policy::reference);\n\n    // test_init_factory_dual\n    // Separate alias constructor testing\n    py::class_<TestFactory7, PyTF7, std::shared_ptr<TestFactory7>>(m, \"TestFactory7\")\n        .def(py::init([](int i) { return TestFactory7(i); }, [](int i) { return PyTF7(i); }))\n        .def(py::init([](pointer_tag, int i) { return new TestFactory7(i); },\n                      [](pointer_tag, int i) { return new PyTF7(i); }))\n        .def(py::init([](mixed_tag, int i) { return new TestFactory7(i); },\n                      [](mixed_tag, int i) { return PyTF7(i); }))\n        .def(py::init([](mixed_tag, const std::string &s) { return TestFactory7((int) s.size()); },\n                      [](mixed_tag, const std::string &s) { return new PyTF7((int) s.size()); }))\n        .def(py::init([](base_tag, pointer_tag, int i) { return new TestFactory7(i); },\n                      [](base_tag, pointer_tag, int i) { return (TestFactory7 *) new PyTF7(i); }))\n        .def(py::init([](alias_tag, pointer_tag, int i) { return new PyTF7(i); },\n                      [](alias_tag, pointer_tag, int i) { return new PyTF7(10 * i); }))\n        .def(py::init(\n            [](shared_ptr_tag, base_tag, int i) { return std::make_shared<TestFactory7>(i); },\n            [](shared_ptr_tag, base_tag, int i) {\n                auto *p = new PyTF7(i);\n                return std::shared_ptr<TestFactory7>(p);\n            }))\n        .def(py::init([](shared_ptr_tag,\n                         invalid_base_tag,\n                         int i) { return std::make_shared<TestFactory7>(i); },\n                      [](shared_ptr_tag, invalid_base_tag, int i) {\n                          return std::make_shared<TestFactory7>(i);\n                      })) // <-- invalid alias factory\n\n        .def(\"get\", &TestFactory7::get)\n        .def(\"has_alias\", &TestFactory7::has_alias)\n\n        .def_static(\n            \"get_cstats\", &ConstructorStats::get<TestFactory7>, py::return_value_policy::reference)\n        .def_static(\n            \"get_alias_cstats\", &ConstructorStats::get<PyTF7>, py::return_value_policy::reference);\n\n    // test_placement_new_alternative\n    // Class with a custom new operator but *without* a placement new operator (issue #948)\n    class NoPlacementNew {\n    public:\n        explicit NoPlacementNew(int i) : i(i) {}\n        static void *operator new(std::size_t s) {\n            auto *p = ::operator new(s);\n            py::print(\"operator new called, returning\", reinterpret_cast<uintptr_t>(p));\n            return p;\n        }\n        static void operator delete(void *p) {\n            py::print(\"operator delete called on\", reinterpret_cast<uintptr_t>(p));\n            ::operator delete(p);\n        }\n        int i;\n    };\n    // As of 2.2, `py::init<args>` no longer requires placement new\n    py::class_<NoPlacementNew>(m, \"NoPlacementNew\")\n        .def(py::init<int>())\n        .def(py::init([]() { return new NoPlacementNew(100); }))\n        .def_readwrite(\"i\", &NoPlacementNew::i);\n\n    // test_reallocations\n    // Class that has verbose operator_new/operator_delete calls\n    struct NoisyAlloc {\n        NoisyAlloc(const NoisyAlloc &) = default;\n        explicit NoisyAlloc(int i) { py::print(py::str(\"NoisyAlloc(int {})\").format(i)); }\n        explicit NoisyAlloc(double d) { py::print(py::str(\"NoisyAlloc(double {})\").format(d)); }\n        ~NoisyAlloc() { py::print(\"~NoisyAlloc()\"); }\n\n        static void *operator new(size_t s) {\n            py::print(\"noisy new\");\n            return ::operator new(s);\n        }\n        static void *operator new(size_t, void *p) {\n            py::print(\"noisy placement new\");\n            return p;\n        }\n        static void operator delete(void *p) noexcept {\n            py::print(\"noisy delete\");\n            ::operator delete(p);\n        }\n        static void operator delete(void *p, size_t) {\n            py::print(\"noisy delete size\");\n            ::operator delete(p);\n        }\n        static void operator delete(void *, void *) { py::print(\"noisy placement delete\"); }\n    };\n\n    py::class_<NoisyAlloc> pyNoisyAlloc(m, \"NoisyAlloc\");\n    // Since these overloads have the same number of arguments, the dispatcher will try each of\n    // them until the arguments convert.  Thus we can get a pre-allocation here when passing a\n    // single non-integer:\n    ignoreOldStyleInitWarnings([&pyNoisyAlloc]() {\n        pyNoisyAlloc.def(\"__init__\", [](NoisyAlloc *a, int i) {\n            new (a) NoisyAlloc(i);\n        }); // Regular constructor, runs first, requires preallocation\n    });\n\n    pyNoisyAlloc.def(py::init([](double d) { return new NoisyAlloc(d); }));\n\n    // The two-argument version: first the factory pointer overload.\n    pyNoisyAlloc.def(py::init([](int i, int) { return new NoisyAlloc(i); }));\n    // Return-by-value:\n    pyNoisyAlloc.def(py::init([](double d, int) { return NoisyAlloc(d); }));\n    // Old-style placement new init; requires preallocation\n    ignoreOldStyleInitWarnings([&pyNoisyAlloc]() {\n        pyNoisyAlloc.def(\"__init__\", [](NoisyAlloc &a, int i, double) { new (&a) NoisyAlloc(i); });\n    });\n    // Requires deallocation of previous overload preallocated value:\n    pyNoisyAlloc.def(py::init([](double d, double) { return new NoisyAlloc(d); }));\n    // Regular again: requires yet another preallocation\n    ignoreOldStyleInitWarnings([&pyNoisyAlloc]() {\n        pyNoisyAlloc.def(\n            \"__init__\", [](NoisyAlloc &a, int i, const std::string &) { new (&a) NoisyAlloc(i); });\n    });\n\n    // static_assert testing (the following def's should all fail with appropriate compilation\n    // errors):\n#if 0\n    struct BadF1Base {};\n    struct BadF1 : BadF1Base {};\n    struct PyBadF1 : BadF1 {};\n    py::class_<BadF1, PyBadF1, std::shared_ptr<BadF1>> bf1(m, \"BadF1\");\n    // wrapped factory function must return a compatible pointer, holder, or value\n    bf1.def(py::init([]() { return 3; }));\n    // incompatible factory function pointer return type\n    bf1.def(py::init([]() { static int three = 3; return &three; }));\n    // incompatible factory function std::shared_ptr<T> return type: cannot convert shared_ptr<T> to holder\n    // (non-polymorphic base)\n    bf1.def(py::init([]() { return std::shared_ptr<BadF1Base>(new BadF1()); }));\n#endif\n}\n"
  },
  {
    "path": "tests/test_factory_constructors.py",
    "content": "from __future__ import annotations\n\nimport re\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import factory_constructors as m\nfrom pybind11_tests.factory_constructors import tag\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_init_factory_basic():\n    \"\"\"Tests py::init_factory() wrapper around various ways of returning the object\"\"\"\n\n    cstats = [\n        ConstructorStats.get(c)\n        for c in [m.TestFactory1, m.TestFactory2, m.TestFactory3]\n    ]\n    cstats[0].alive()  # force gc\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    x1 = m.TestFactory1(tag.unique_ptr, 3)\n    assert x1.value == \"3\"\n    y1 = m.TestFactory1(tag.pointer)\n    assert y1.value == \"(empty)\"\n    z1 = m.TestFactory1(\"hi!\")\n    assert z1.value == \"hi!\"\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 3\n\n    x2 = m.TestFactory2(tag.move)\n    assert x2.value == \"(empty2)\"\n    y2 = m.TestFactory2(tag.pointer, 7)\n    assert y2.value == \"7\"\n    z2 = m.TestFactory2(tag.unique_ptr, \"hi again\")\n    assert z2.value == \"hi again\"\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 6\n\n    x3 = m.TestFactory3(tag.shared_ptr)\n    assert x3.value == \"(empty3)\"\n    y3 = m.TestFactory3(tag.pointer, 42)\n    assert y3.value == \"42\"\n    z3 = m.TestFactory3(\"bye\")\n    assert z3.value == \"bye\"\n\n    for null_ptr_kind in [tag.null_ptr, tag.null_unique_ptr, tag.null_shared_ptr]:\n        with pytest.raises(TypeError) as excinfo:\n            m.TestFactory3(null_ptr_kind)\n        assert (\n            str(excinfo.value) == \"pybind11::init(): factory function returned nullptr\"\n        )\n\n    assert [i.alive() for i in cstats] == [3, 3, 3]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 9\n\n    del x1, y2, y3, z3\n    assert [i.alive() for i in cstats] == [2, 2, 1]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 5\n    del x2, x3, y1, z1, z2\n    assert [i.alive() for i in cstats] == [0, 0, 0]\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    assert [i.values() for i in cstats] == [\n        [\"3\", \"hi!\"],\n        [\"7\", \"hi again\"],\n        [\"42\", \"bye\"],\n    ]\n    assert [i.default_constructions for i in cstats] == [1, 1, 1]\n\n\ndef test_init_factory_signature(msg):\n    with pytest.raises(TypeError) as excinfo:\n        m.TestFactory1(\"invalid\", \"constructor\", \"arguments\")\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        __init__(): incompatible constructor arguments. The following argument types are supported:\n            1. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: typing.SupportsInt | typing.SupportsIndex)\n            2. m.factory_constructors.TestFactory1(arg0: str)\n            3. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.pointer_tag)\n            4. m.factory_constructors.TestFactory1(arg0: object, arg1: typing.SupportsInt | typing.SupportsIndex, arg2: object)\n\n        Invoked with: 'invalid', 'constructor', 'arguments'\n    \"\"\"\n    )\n\n    assert (\n        msg(m.TestFactory1.__init__.__doc__)\n        == \"\"\"\n        __init__(*args, **kwargs)\n        Overloaded function.\n\n        1. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: typing.SupportsInt | typing.SupportsIndex) -> None\n\n        2. __init__(self: m.factory_constructors.TestFactory1, arg0: str) -> None\n\n        3. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.pointer_tag) -> None\n\n        4. __init__(self: m.factory_constructors.TestFactory1, arg0: object, arg1: typing.SupportsInt | typing.SupportsIndex, arg2: object) -> None\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_init_factory_casting():\n    \"\"\"Tests py::init_factory() wrapper with various upcasting and downcasting returns\"\"\"\n\n    cstats = [\n        ConstructorStats.get(c)\n        for c in [m.TestFactory3, m.TestFactory4, m.TestFactory5]\n    ]\n    cstats[0].alive()  # force gc\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    # Construction from derived references:\n    a = m.TestFactory3(tag.pointer, tag.TF4, 4)\n    assert a.value == \"4\"\n    b = m.TestFactory3(tag.shared_ptr, tag.TF4, 5)\n    assert b.value == \"5\"\n    c = m.TestFactory3(tag.pointer, tag.TF5, 6)\n    assert c.value == \"6\"\n    d = m.TestFactory3(tag.shared_ptr, tag.TF5, 7)\n    assert d.value == \"7\"\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 4\n\n    # Shared a lambda with TF3:\n    e = m.TestFactory4(tag.pointer, tag.TF4, 8)\n    assert e.value == \"8\"\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 5\n    assert [i.alive() for i in cstats] == [5, 3, 2]\n\n    del a\n    assert [i.alive() for i in cstats] == [4, 2, 2]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 4\n\n    del b, c, e\n    assert [i.alive() for i in cstats] == [1, 0, 1]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 1\n\n    del d\n    assert [i.alive() for i in cstats] == [0, 0, 0]\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    assert [i.values() for i in cstats] == [\n        [\"4\", \"5\", \"6\", \"7\", \"8\"],\n        [\"4\", \"5\", \"8\"],\n        [\"6\", \"7\"],\n    ]\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_init_factory_alias():\n    \"\"\"Tests py::init_factory() wrapper with value conversions and alias types\"\"\"\n\n    cstats = [m.TestFactory6.get_cstats(), m.TestFactory6.get_alias_cstats()]\n    cstats[0].alive()  # force gc\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    a = m.TestFactory6(tag.base, 1)\n    assert a.get() == 1\n    assert not a.has_alias()\n    b = m.TestFactory6(tag.alias, \"hi there\")\n    assert b.get() == 8\n    assert b.has_alias()\n    c = m.TestFactory6(tag.alias, 3)\n    assert c.get() == 3\n    assert c.has_alias()\n    d = m.TestFactory6(tag.alias, tag.pointer, 4)\n    assert d.get() == 4\n    assert d.has_alias()\n    e = m.TestFactory6(tag.base, tag.pointer, 5)\n    assert e.get() == 5\n    assert not e.has_alias()\n    f = m.TestFactory6(tag.base, tag.alias, tag.pointer, 6)\n    assert f.get() == 6\n    assert f.has_alias()\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 6\n    assert [i.alive() for i in cstats] == [6, 4]\n\n    del a, b, e\n    assert [i.alive() for i in cstats] == [3, 3]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 3\n    del f, c, d\n    assert [i.alive() for i in cstats] == [0, 0]\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    class MyTest(m.TestFactory6):\n        def __init__(self, *args):\n            m.TestFactory6.__init__(self, *args)\n\n        def get(self):\n            return -5 + m.TestFactory6.get(self)\n\n    # Return Class by value, moved into new alias:\n    z = MyTest(tag.base, 123)\n    assert z.get() == 118\n    assert z.has_alias()\n\n    # Return alias by value, moved into new alias:\n    y = MyTest(tag.alias, \"why hello!\")\n    assert y.get() == 5\n    assert y.has_alias()\n\n    # Return Class by pointer, moved into new alias then original destroyed:\n    x = MyTest(tag.base, tag.pointer, 47)\n    assert x.get() == 42\n    assert x.has_alias()\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 3\n    assert [i.alive() for i in cstats] == [3, 3]\n    del x, y, z\n    assert [i.alive() for i in cstats] == [0, 0]\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    assert [i.values() for i in cstats] == [\n        [\"1\", \"8\", \"3\", \"4\", \"5\", \"6\", \"123\", \"10\", \"47\"],\n        [\"hi there\", \"3\", \"4\", \"6\", \"move\", \"123\", \"why hello!\", \"move\", \"47\"],\n    ]\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_init_factory_dual():\n    \"\"\"Tests init factory functions with dual main/alias factory functions\"\"\"\n    from pybind11_tests.factory_constructors import TestFactory7\n\n    cstats = [TestFactory7.get_cstats(), TestFactory7.get_alias_cstats()]\n    cstats[0].alive()  # force gc\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    class PythFactory7(TestFactory7):\n        def get(self):\n            return 100 + TestFactory7.get(self)\n\n    a1 = TestFactory7(1)\n    a2 = PythFactory7(2)\n    assert a1.get() == 1\n    assert a2.get() == 102\n    assert not a1.has_alias()\n    assert a2.has_alias()\n\n    b1 = TestFactory7(tag.pointer, 3)\n    b2 = PythFactory7(tag.pointer, 4)\n    assert b1.get() == 3\n    assert b2.get() == 104\n    assert not b1.has_alias()\n    assert b2.has_alias()\n\n    c1 = TestFactory7(tag.mixed, 5)\n    c2 = PythFactory7(tag.mixed, 6)\n    assert c1.get() == 5\n    assert c2.get() == 106\n    assert not c1.has_alias()\n    assert c2.has_alias()\n\n    d1 = TestFactory7(tag.base, tag.pointer, 7)\n    d2 = PythFactory7(tag.base, tag.pointer, 8)\n    assert d1.get() == 7\n    assert d2.get() == 108\n    assert not d1.has_alias()\n    assert d2.has_alias()\n\n    # Both return an alias; the second multiplies the value by 10:\n    e1 = TestFactory7(tag.alias, tag.pointer, 9)\n    e2 = PythFactory7(tag.alias, tag.pointer, 10)\n    assert e1.get() == 9\n    assert e2.get() == 200\n    assert e1.has_alias()\n    assert e2.has_alias()\n\n    f1 = TestFactory7(tag.shared_ptr, tag.base, 11)\n    f2 = PythFactory7(tag.shared_ptr, tag.base, 12)\n    assert f1.get() == 11\n    assert f2.get() == 112\n    assert not f1.has_alias()\n    assert f2.has_alias()\n\n    g1 = TestFactory7(tag.shared_ptr, tag.invalid_base, 13)\n    assert g1.get() == 13\n    assert not g1.has_alias()\n    with pytest.raises(TypeError) as excinfo:\n        PythFactory7(tag.shared_ptr, tag.invalid_base, 14)\n    assert (\n        str(excinfo.value)\n        == \"pybind11::init(): construction failed: returned holder-wrapped instance is not an \"\n        \"alias instance\"\n    )\n\n    assert [i.alive() for i in cstats] == [13, 7]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 13\n\n    del a1, a2, b1, d1, e1, e2\n    assert [i.alive() for i in cstats] == [7, 4]\n    assert ConstructorStats.detail_reg_inst() == n_inst + 7\n    del b2, c1, c2, d2, f1, f2, g1\n    assert [i.alive() for i in cstats] == [0, 0]\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n    assert [i.values() for i in cstats] == [\n        [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"100\", \"11\", \"12\", \"13\", \"14\"],\n        [\"2\", \"4\", \"6\", \"8\", \"9\", \"100\", \"12\"],\n    ]\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_no_placement_new(capture):\n    \"\"\"Prior to 2.2, `py::init<...>` relied on the type supporting placement\n    new; this tests a class without placement new support.\"\"\"\n    with capture:\n        a = m.NoPlacementNew(123)\n\n    found = re.search(r\"^operator new called, returning (\\d+)\\n$\", str(capture))\n    assert found\n    assert a.i == 123\n    with capture:\n        del a\n        pytest.gc_collect()\n    assert capture == \"operator delete called on \" + found.group(1)\n\n    with capture:\n        b = m.NoPlacementNew()\n\n    found = re.search(r\"^operator new called, returning (\\d+)\\n$\", str(capture))\n    assert found\n    assert b.i == 100\n    with capture:\n        del b\n        pytest.gc_collect()\n    assert capture == \"operator delete called on \" + found.group(1)\n\n\ndef test_multiple_inheritance():\n    class MITest(m.TestFactory1, m.TestFactory2):\n        def __init__(self):\n            m.TestFactory1.__init__(self, tag.unique_ptr, 33)\n            m.TestFactory2.__init__(self, tag.move)\n\n    a = MITest()\n    assert m.TestFactory1.value.fget(a) == \"33\"\n    assert m.TestFactory2.value.fget(a) == \"(empty2)\"\n\n\ndef create_and_destroy(*args):\n    a = m.NoisyAlloc(*args)\n    print(\"---\")\n    del a\n    pytest.gc_collect()\n\n\ndef strip_comments(s):\n    return re.sub(r\"\\s+#.*\", \"\", s)\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_a(capture, msg):\n    \"\"\"When the constructor is overloaded, previous overloads can require a preallocated value.\n    This test makes sure that such preallocated values only happen when they might be necessary,\n    and that they are deallocated properly.\"\"\"\n\n    pytest.gc_collect()\n\n    with capture:\n        create_and_destroy(1)\n    assert (\n        msg(capture)\n        == \"\"\"\n        noisy new\n        noisy placement new\n        NoisyAlloc(int 1)\n        ---\n        ~NoisyAlloc()\n        noisy delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_b(capture, msg):\n    with capture:\n        create_and_destroy(1.5)\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        noisy new               # allocation required to attempt first overload\n        noisy delete            # have to dealloc before considering factory init overload\n        noisy new               # pointer factory calling \"new\", part 1: allocation\n        NoisyAlloc(double 1.5)  # ... part two, invoking constructor\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_c(capture, msg):\n    with capture:\n        create_and_destroy(2, 3)\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        noisy new          # pointer factory calling \"new\", allocation\n        NoisyAlloc(int 2)  # constructor\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_d(capture, msg):\n    with capture:\n        create_and_destroy(2.5, 3)\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        NoisyAlloc(double 2.5)  # construction (local func variable: operator_new not called)\n        noisy new               # return-by-value \"new\" part 1: allocation\n        ~NoisyAlloc()           # moved-away local func variable destruction\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_e(capture, msg):\n    with capture:\n        create_and_destroy(3.5, 4.5)\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        noisy new          # preallocation needed before invoking factory pointer overload\n        noisy delete       # deallocation of preallocated storage\n        noisy new          # Factory pointer allocation\n        NoisyAlloc(double 3.5)  # factory pointer construction\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_f(capture, msg):\n    with capture:\n        create_and_destroy(4, 0.5)\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        noisy new          # preallocation needed before invoking placement-new overload\n        noisy placement new     # Placement new\n        NoisyAlloc(int 4)  # construction\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_reallocation_g(capture, msg):\n    with capture:\n        create_and_destroy(5, \"hi\")\n    assert msg(capture) == strip_comments(\n        \"\"\"\n        noisy new            # preallocation needed before invoking first placement new\n        noisy delete         # delete before considering new-style constructor\n        noisy new            # preallocation for second placement new\n        noisy placement new  # Placement new in the second placement new overload\n        NoisyAlloc(int 5)    # construction\n        ---\n        ~NoisyAlloc()  # Destructor\n        noisy delete   # operator delete\n    \"\"\"\n    )\n\n\ndef test_invalid_self():\n    \"\"\"Tests invocation of the pybind-registered base class with an invalid `self` argument.\"\"\"\n\n    class NotPybindDerived:\n        pass\n\n    # Attempts to initialize with an invalid type passed as `self`:\n    class BrokenTF1(m.TestFactory1):\n        def __init__(self, bad):\n            if bad == 1:\n                a = m.TestFactory2(tag.pointer, 1)\n                m.TestFactory1.__init__(a, tag.pointer)\n            elif bad == 2:\n                a = NotPybindDerived()\n                m.TestFactory1.__init__(a, tag.pointer)\n\n    # Same as above, but for a class with an alias:\n    class BrokenTF6(m.TestFactory6):\n        def __init__(self, bad):\n            if bad == 0:\n                m.TestFactory6.__init__()\n            elif bad == 1:\n                a = m.TestFactory2(tag.pointer, 1)\n                m.TestFactory6.__init__(a, tag.base, 1)\n            elif bad == 2:\n                a = m.TestFactory2(tag.pointer, 1)\n                m.TestFactory6.__init__(a, tag.alias, 1)\n            elif bad == 3:\n                m.TestFactory6.__init__(\n                    NotPybindDerived.__new__(NotPybindDerived), tag.base, 1\n                )\n            elif bad == 4:\n                m.TestFactory6.__init__(\n                    NotPybindDerived.__new__(NotPybindDerived), tag.alias, 1\n                )\n\n    for arg in (1, 2):\n        with pytest.raises(TypeError) as excinfo:\n            BrokenTF1(arg)\n        assert (\n            str(excinfo.value)\n            == \"__init__(self, ...) called with invalid or missing `self` argument\"\n        )\n\n    for arg in (0, 1, 2, 3, 4):\n        with pytest.raises(TypeError) as excinfo:\n            BrokenTF6(arg)\n        assert (\n            str(excinfo.value)\n            == \"__init__(self, ...) called with invalid or missing `self` argument\"\n        )\n"
  },
  {
    "path": "tests/test_gil_scoped.cpp",
    "content": "/*\n    tests/test_gil_scoped.cpp -- acquire and release gil\n\n    Copyright (c) 2017 Borja Zarco (Google LLC) <bzarco@google.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/functional.h>\n\n#include \"pybind11_tests.h\"\n\n#include <string>\n#include <thread>\n\n#define CROSS_MODULE(Function)                                                                    \\\n    auto cm = py::module_::import(\"cross_module_gil_utils\");                                      \\\n    auto target = reinterpret_cast<void (*)()>(PyLong_AsVoidPtr(cm.attr(Function).ptr()));\n\nclass VirtClass {\npublic:\n    virtual ~VirtClass() = default;\n    VirtClass() = default;\n    VirtClass(const VirtClass &) = delete;\n    virtual void virtual_func() {}\n    virtual void pure_virtual_func() = 0;\n};\n\nclass PyVirtClass : public VirtClass {\n    void virtual_func() override { PYBIND11_OVERRIDE(void, VirtClass, virtual_func, ); }\n    void pure_virtual_func() override {\n        PYBIND11_OVERRIDE_PURE(void, VirtClass, pure_virtual_func, );\n    }\n};\n\nTEST_SUBMODULE(gil_scoped, m) {\n    m.attr(\"defined_THREAD_SANITIZER\") =\n#if defined(THREAD_SANITIZER)\n        true;\n#else\n        false;\n#endif\n\n    m.def(\"intentional_deadlock\",\n          []() { std::thread([]() { py::gil_scoped_acquire gil_acquired; }).join(); });\n\n    py::class_<VirtClass, PyVirtClass>(m, \"VirtClass\")\n        .def(py::init<>())\n        .def(\"virtual_func\", &VirtClass::virtual_func)\n        .def(\"pure_virtual_func\", &VirtClass::pure_virtual_func);\n\n    m.def(\"test_callback_py_obj\", [](py::object &func) { func(); });\n    m.def(\"test_callback_std_func\", [](const std::function<void()> &func) { func(); });\n    m.def(\"test_callback_virtual_func\", [](VirtClass &virt) { virt.virtual_func(); });\n    m.def(\"test_callback_pure_virtual_func\", [](VirtClass &virt) { virt.pure_virtual_func(); });\n    m.def(\"test_cross_module_gil_released\", []() {\n        CROSS_MODULE(\"gil_acquire_funcaddr\")\n        py::gil_scoped_release gil_release;\n        target();\n    });\n    m.def(\"test_cross_module_gil_acquired\", []() {\n        CROSS_MODULE(\"gil_acquire_funcaddr\")\n        py::gil_scoped_acquire gil_acquire;\n        target();\n    });\n    m.def(\"test_cross_module_gil_inner_custom_released\", []() {\n        CROSS_MODULE(\"gil_acquire_inner_custom_funcaddr\")\n        py::gil_scoped_release gil_release;\n        target();\n    });\n    m.def(\"test_cross_module_gil_inner_custom_acquired\", []() {\n        CROSS_MODULE(\"gil_acquire_inner_custom_funcaddr\")\n        py::gil_scoped_acquire gil_acquire;\n        target();\n    });\n    m.def(\"test_cross_module_gil_inner_pybind11_released\", []() {\n        CROSS_MODULE(\"gil_acquire_inner_pybind11_funcaddr\")\n        py::gil_scoped_release gil_release;\n        target();\n    });\n    m.def(\"test_cross_module_gil_inner_pybind11_acquired\", []() {\n        CROSS_MODULE(\"gil_acquire_inner_pybind11_funcaddr\")\n        py::gil_scoped_acquire gil_acquire;\n        target();\n    });\n    m.def(\"test_cross_module_gil_nested_custom_released\", []() {\n        CROSS_MODULE(\"gil_acquire_nested_custom_funcaddr\")\n        py::gil_scoped_release gil_release;\n        target();\n    });\n    m.def(\"test_cross_module_gil_nested_custom_acquired\", []() {\n        CROSS_MODULE(\"gil_acquire_nested_custom_funcaddr\")\n        py::gil_scoped_acquire gil_acquire;\n        target();\n    });\n    m.def(\"test_cross_module_gil_nested_pybind11_released\", []() {\n        CROSS_MODULE(\"gil_acquire_nested_pybind11_funcaddr\")\n        py::gil_scoped_release gil_release;\n        target();\n    });\n    m.def(\"test_cross_module_gil_nested_pybind11_acquired\", []() {\n        CROSS_MODULE(\"gil_acquire_nested_pybind11_funcaddr\")\n        py::gil_scoped_acquire gil_acquire;\n        target();\n    });\n    m.def(\"test_release_acquire\", [](const py::object &obj) {\n        py::gil_scoped_release gil_released;\n        py::gil_scoped_acquire gil_acquired;\n        return py::str(obj);\n    });\n    m.def(\"test_nested_acquire\", [](const py::object &obj) {\n        py::gil_scoped_release gil_released;\n        py::gil_scoped_acquire gil_acquired_outer;\n        py::gil_scoped_acquire gil_acquired_inner;\n        return py::str(obj);\n    });\n    m.def(\"test_multi_acquire_release_cross_module\", [](unsigned bits) {\n        py::set internals_ids;\n        internals_ids.add(PYBIND11_INTERNALS_ID);\n        {\n            py::gil_scoped_release gil_released;\n            auto thread_f = [bits, &internals_ids]() {\n                py::gil_scoped_acquire gil_acquired;\n                auto cm = py::module_::import(\"cross_module_gil_utils\");\n                auto target = reinterpret_cast<std::string (*)(unsigned)>(\n                    PyLong_AsVoidPtr(cm.attr(\"gil_multi_acquire_release_funcaddr\").ptr()));\n                std::string cm_internals_id = target(bits >> 3);\n                internals_ids.add(cm_internals_id);\n            };\n            if ((bits & 0x1u) != 0u) {\n                thread_f();\n            }\n            if ((bits & 0x2u) != 0u) {\n                std::thread non_python_thread(thread_f);\n                non_python_thread.join();\n            }\n            if ((bits & 0x4u) != 0u) {\n                thread_f();\n            }\n        }\n        return internals_ids;\n    });\n}\n"
  },
  {
    "path": "tests/test_gil_scoped.py",
    "content": "from __future__ import annotations\n\nimport multiprocessing\nimport sys\nimport sysconfig\nimport threading\nimport time\n\nimport pytest\n\nimport env\nfrom pybind11_tests import gil_scoped as m\n\n# Test collection seems to hold the gil\n# These tests have rare flakes in nogil; since they\n# are testing the gil, they are skipped at the moment.\nskipif_not_free_threaded = pytest.mark.skipif(\n    sysconfig.get_config_var(\"Py_GIL_DISABLED\"),\n    reason=\"Flaky without the GIL\",\n)\n\n\nclass ExtendedVirtClass(m.VirtClass):\n    def virtual_func(self):\n        pass\n\n    def pure_virtual_func(self):\n        pass\n\n\ndef test_callback_py_obj():\n    m.test_callback_py_obj(lambda: None)\n\n\ndef test_callback_std_func():\n    m.test_callback_std_func(lambda: None)\n\n\ndef test_callback_virtual_func():\n    extended = ExtendedVirtClass()\n    m.test_callback_virtual_func(extended)\n\n\ndef test_callback_pure_virtual_func():\n    extended = ExtendedVirtClass()\n    m.test_callback_pure_virtual_func(extended)\n\n\ndef test_cross_module_gil_released():\n    \"\"\"Makes sure that the GIL can be acquired by another module from a GIL-released state.\"\"\"\n    m.test_cross_module_gil_released()  # Should not raise a SIGSEGV\n\n\ndef test_cross_module_gil_acquired():\n    \"\"\"Makes sure that the GIL can be acquired by another module from a GIL-acquired state.\"\"\"\n    m.test_cross_module_gil_acquired()  # Should not raise a SIGSEGV\n\n\ndef test_cross_module_gil_inner_custom_released():\n    \"\"\"Makes sure that the GIL can be acquired/released by another module\n    from a GIL-released state using custom locking logic.\"\"\"\n    m.test_cross_module_gil_inner_custom_released()\n\n\ndef test_cross_module_gil_inner_custom_acquired():\n    \"\"\"Makes sure that the GIL can be acquired/acquired by another module\n    from a GIL-acquired state using custom locking logic.\"\"\"\n    m.test_cross_module_gil_inner_custom_acquired()\n\n\ndef test_cross_module_gil_inner_pybind11_released():\n    \"\"\"Makes sure that the GIL can be acquired/released by another module\n    from a GIL-released state using pybind11 locking logic.\"\"\"\n    m.test_cross_module_gil_inner_pybind11_released()\n\n\ndef test_cross_module_gil_inner_pybind11_acquired():\n    \"\"\"Makes sure that the GIL can be acquired/acquired by another module\n    from a GIL-acquired state using pybind11 locking logic.\"\"\"\n    m.test_cross_module_gil_inner_pybind11_acquired()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_cross_module_gil_nested_custom_released():\n    \"\"\"Makes sure that the GIL can be nested acquired/released by another module\n    from a GIL-released state using custom locking logic.\"\"\"\n    m.test_cross_module_gil_nested_custom_released()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_cross_module_gil_nested_custom_acquired():\n    \"\"\"Makes sure that the GIL can be nested acquired/acquired by another module\n    from a GIL-acquired state using custom locking logic.\"\"\"\n    m.test_cross_module_gil_nested_custom_acquired()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_cross_module_gil_nested_pybind11_released():\n    \"\"\"Makes sure that the GIL can be nested acquired/released by another module\n    from a GIL-released state using pybind11 locking logic.\"\"\"\n    m.test_cross_module_gil_nested_pybind11_released()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_cross_module_gil_nested_pybind11_acquired():\n    \"\"\"Makes sure that the GIL can be nested acquired/acquired by another module\n    from a GIL-acquired state using pybind11 locking logic.\"\"\"\n    m.test_cross_module_gil_nested_pybind11_acquired()\n\n\ndef test_release_acquire():\n    assert m.test_release_acquire(0xAB) == \"171\"\n\n\ndef test_nested_acquire():\n    assert m.test_nested_acquire(0xAB) == \"171\"\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.skipif(\n    env.GRAALPY and sys.platform == \"darwin\",\n    reason=\"Transiently crashes on GraalPy on OS X\",\n)\ndef test_multi_acquire_release_cross_module():\n    for bits in range(16 * 8):\n        internals_ids = m.test_multi_acquire_release_cross_module(bits)\n        assert len(internals_ids) == 2 if bits % 8 else 1\n\n\n# Intentionally putting human review in the loop here, to guard against accidents.\nVARS_BEFORE_ALL_BASIC_TESTS = dict(vars())  # Make a copy of the dict (critical).\nALL_BASIC_TESTS = (\n    test_callback_py_obj,\n    test_callback_std_func,\n    test_callback_virtual_func,\n    test_callback_pure_virtual_func,\n    test_cross_module_gil_released,\n    test_cross_module_gil_acquired,\n    test_cross_module_gil_inner_custom_released,\n    test_cross_module_gil_inner_custom_acquired,\n    test_cross_module_gil_inner_pybind11_released,\n    test_cross_module_gil_inner_pybind11_acquired,\n    test_cross_module_gil_nested_custom_released,\n    test_cross_module_gil_nested_custom_acquired,\n    test_cross_module_gil_nested_pybind11_released,\n    test_cross_module_gil_nested_pybind11_acquired,\n    test_release_acquire,\n    test_nested_acquire,\n    test_multi_acquire_release_cross_module,\n)\n\n\ndef test_all_basic_tests_completeness():\n    num_found = 0\n    for key, value in VARS_BEFORE_ALL_BASIC_TESTS.items():\n        if not key.startswith(\"test_\"):\n            continue\n        assert value in ALL_BASIC_TESTS\n        num_found += 1\n    assert len(ALL_BASIC_TESTS) == num_found\n\n\ndef _intentional_deadlock():\n    m.intentional_deadlock()\n\n\nALL_BASIC_TESTS_PLUS_INTENTIONAL_DEADLOCK = (*ALL_BASIC_TESTS, _intentional_deadlock)\n\n\ndef _run_in_process(target, *args, **kwargs):\n    if env.ANDROID or env.IOS or sys.platform.startswith(\"emscripten\"):\n        pytest.skip(\"Requires subprocess support\")\n\n    test_fn = target if len(args) == 0 else args[0]\n    # Do not need to wait much, 10s should be more than enough.\n    timeout = 0.1 if test_fn is _intentional_deadlock else 10\n    process = multiprocessing.Process(target=target, args=args, kwargs=kwargs)\n    process.daemon = True\n    try:\n        t_start = time.time()\n        process.start()\n        if timeout >= 100:  # For debugging.\n            print(\n                \"\\nprocess.pid STARTED\", process.pid, (sys.argv, target, args, kwargs)\n            )\n            print(f\"COPY-PASTE-THIS: gdb {sys.argv[0]} -p {process.pid}\", flush=True)\n        process.join(timeout=timeout)\n        if timeout >= 100:\n            print(\"\\nprocess.pid JOINED\", process.pid, flush=True)\n        t_delta = time.time() - t_start\n        if process.exitcode == 66 and m.defined_THREAD_SANITIZER:  # Issue #2754\n            # WOULD-BE-NICE-TO-HAVE: Check that the message below is actually in the output.\n            # Maybe this could work:\n            # https://gist.github.com/alexeygrigorev/01ce847f2e721b513b42ea4a6c96905e\n            pytest.skip(\n                \"ThreadSanitizer: starting new threads after multi-threaded fork is not supported.\"\n            )\n        elif test_fn is _intentional_deadlock:\n            assert process.exitcode is None\n            return 0\n\n        if process.exitcode is None:\n            assert t_delta > 0.9 * timeout\n            msg = \"DEADLOCK, most likely, exactly what this test is meant to detect.\"\n            soabi = sysconfig.get_config_var(\"SOABI\")\n            if env.WIN and env.PYPY:\n                pytest.xfail(f\"[TEST-GIL-SCOPED] {soabi} PyPy: \" + msg)\n            if env.MACOS:\n                if not env.sys_is_gil_enabled():\n                    pytest.xfail(f\"[TEST-GIL-SCOPED] {soabi} with GIL disabled: \" + msg)\n                if env.PY_GIL_DISABLED:\n                    pytest.xfail(f\"[TEST-GIL-SCOPED] {soabi}: \" + msg)\n            raise RuntimeError(msg)\n        return process.exitcode\n    finally:\n        if process.is_alive():\n            process.terminate()\n\n\ndef _run_in_threads(test_fn, num_threads, parallel):\n    threads = []\n    for _ in range(num_threads):\n        thread = threading.Thread(target=test_fn)\n        thread.daemon = True\n        thread.start()\n        if parallel:\n            threads.append(thread)\n        else:\n            thread.join()\n    for thread in threads:\n        thread.join()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.parametrize(\"test_fn\", ALL_BASIC_TESTS_PLUS_INTENTIONAL_DEADLOCK)\n@pytest.mark.skipif(\n    \"env.GRAALPY\",\n    reason=\"GraalPy transiently complains about unfinished threads at process exit\",\n)\ndef test_run_in_process_one_thread(test_fn):\n    \"\"\"Makes sure there is no GIL deadlock when running in a thread.\n\n    It runs in a separate process to be able to stop and assert if it deadlocks.\n    \"\"\"\n    assert _run_in_process(_run_in_threads, test_fn, num_threads=1, parallel=False) == 0\n\n\n@skipif_not_free_threaded\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.parametrize(\"test_fn\", ALL_BASIC_TESTS_PLUS_INTENTIONAL_DEADLOCK)\n@pytest.mark.skipif(\n    \"env.GRAALPY\",\n    reason=\"GraalPy transiently complains about unfinished threads at process exit\",\n)\ndef test_run_in_process_multiple_threads_parallel(test_fn):\n    \"\"\"Makes sure there is no GIL deadlock when running in a thread multiple times in parallel.\n\n    It runs in a separate process to be able to stop and assert if it deadlocks.\n    \"\"\"\n    assert _run_in_process(_run_in_threads, test_fn, num_threads=8, parallel=True) == 0\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.parametrize(\"test_fn\", ALL_BASIC_TESTS_PLUS_INTENTIONAL_DEADLOCK)\n@pytest.mark.skipif(\n    \"env.GRAALPY\",\n    reason=\"GraalPy transiently complains about unfinished threads at process exit\",\n)\ndef test_run_in_process_multiple_threads_sequential(test_fn):\n    \"\"\"Makes sure there is no GIL deadlock when running in a thread multiple times sequentially.\n\n    It runs in a separate process to be able to stop and assert if it deadlocks.\n    \"\"\"\n    assert _run_in_process(_run_in_threads, test_fn, num_threads=8, parallel=False) == 0\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.parametrize(\n    \"test_fn\",\n    [\n        *ALL_BASIC_TESTS,\n        pytest.param(_intentional_deadlock, marks=skipif_not_free_threaded),\n    ],\n)\n@pytest.mark.skipif(\n    \"env.GRAALPY\",\n    reason=\"GraalPy transiently complains about unfinished threads at process exit\",\n)\ndef test_run_in_process_direct(test_fn):\n    \"\"\"Makes sure there is no GIL deadlock when using processes.\n\n    This test is for completion, but it was never an issue.\n    \"\"\"\n    assert _run_in_process(test_fn) == 0\n"
  },
  {
    "path": "tests/test_iostream.cpp",
    "content": "/*\n    tests/test_iostream.cpp -- Usage of scoped_output_redirect\n\n    Copyright (c) 2017 Henry F. Schreiner\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/iostream.h>\n\n#include \"pybind11_tests.h\"\n\n#include <atomic>\n#include <iostream>\n#include <mutex>\n#include <string>\n#include <thread>\n\nvoid noisy_function(const std::string &msg, bool flush) {\n\n    std::cout << msg;\n    if (flush) {\n        std::cout << std::flush;\n    }\n}\n\nvoid noisy_funct_dual(const std::string &msg, const std::string &emsg) {\n    std::cout << msg;\n    std::cerr << emsg;\n}\n\n// object to manage C++ thread\n// simply repeatedly write to std::cerr until stopped\n// redirect is called at some point to test the safety of scoped_estream_redirect\nstruct TestThread {\n    TestThread() : stop_{false} {\n        auto thread_f = [this] {\n            static std::mutex cout_mutex;\n            while (!stop_) {\n                {\n                    // #HelpAppreciated: Work on iostream.h thread safety.\n                    // Without this lock, the clang ThreadSanitizer (tsan) reliably reports a\n                    // data race, and this test is predictably flakey on Windows.\n                    // For more background see the discussion under\n                    // https://github.com/pybind/pybind11/pull/2982 and\n                    // https://github.com/pybind/pybind11/pull/2995.\n                    const std::lock_guard<std::mutex> lock(cout_mutex);\n                    std::cout << \"x\" << std::flush;\n                }\n                std::this_thread::sleep_for(std::chrono::microseconds(50));\n            }\n        };\n        t_ = new std::thread(std::move(thread_f));\n    }\n\n    ~TestThread() { delete t_; }\n\n    void stop() { stop_ = true; }\n\n    void join() const {\n        py::gil_scoped_release gil_lock;\n        t_->join();\n    }\n\n    void sleep() {\n        py::gil_scoped_release gil_lock;\n        std::this_thread::sleep_for(std::chrono::milliseconds(50));\n    }\n\n    std::thread *t_{nullptr};\n    std::atomic<bool> stop_;\n};\n\nTEST_SUBMODULE(iostream, m) {\n\n    add_ostream_redirect(m);\n\n    // test_evals\n\n    m.def(\"captured_output_default\", [](const std::string &msg) {\n        py::scoped_ostream_redirect redir;\n        std::cout << msg << std::flush;\n    });\n\n    m.def(\"captured_output\", [](const std::string &msg) {\n        py::scoped_ostream_redirect redir(std::cout, py::module_::import(\"sys\").attr(\"stdout\"));\n        std::cout << msg << std::flush;\n    });\n\n    m.def(\"guard_output\",\n          &noisy_function,\n          py::call_guard<py::scoped_ostream_redirect>(),\n          py::arg(\"msg\"),\n          py::arg(\"flush\") = true);\n\n    m.def(\"captured_err\", [](const std::string &msg) {\n        py::scoped_ostream_redirect redir(std::cerr, py::module_::import(\"sys\").attr(\"stderr\"));\n        std::cerr << msg << std::flush;\n    });\n\n    m.def(\"noisy_function\", &noisy_function, py::arg(\"msg\"), py::arg(\"flush\") = true);\n\n    m.def(\"dual_guard\",\n          &noisy_funct_dual,\n          py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>(),\n          py::arg(\"msg\"),\n          py::arg(\"emsg\"));\n\n    m.def(\"raw_output\", [](const std::string &msg) { std::cout << msg << std::flush; });\n\n    m.def(\"raw_err\", [](const std::string &msg) { std::cerr << msg << std::flush; });\n\n    m.def(\"captured_dual\", [](const std::string &msg, const std::string &emsg) {\n        py::scoped_ostream_redirect redirout(std::cout, py::module_::import(\"sys\").attr(\"stdout\"));\n        py::scoped_ostream_redirect redirerr(std::cerr, py::module_::import(\"sys\").attr(\"stderr\"));\n        std::cout << msg << std::flush;\n        std::cerr << emsg << std::flush;\n    });\n\n    py::class_<TestThread>(m, \"TestThread\")\n        .def(py::init<>())\n        .def(\"stop\", &TestThread::stop)\n        .def(\"join\", &TestThread::join)\n        .def(\"sleep\", &TestThread::sleep);\n}\n"
  },
  {
    "path": "tests/test_iostream.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom io import StringIO\n\nimport pytest\n\nimport env\nfrom pybind11_tests import iostream as m\n\nif env.WIN:\n    wv_build = sys.getwindowsversion().build\n    skip_if_ge = 26100\n    if wv_build >= skip_if_ge:\n        pytest.skip(\n            f\"Windows build {wv_build} >= {skip_if_ge}:\"\n            \" Skipping iostream capture (redirection regression needs investigation)\",\n            allow_module_level=True,\n        )\n\n\ndef test_captured(capsys):\n    msg = \"I've been redirected to Python, I hope!\"\n    m.captured_output(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n    m.captured_err(msg)\n    stdout, stderr = capsys.readouterr()\n    assert not stdout\n    assert stderr == msg\n\n\ndef test_captured_large_string(capsys):\n    # Make this bigger than the buffer used on the C++ side: 1024 chars\n    msg = \"I've been redirected to Python, I hope!\"\n    msg = msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_2byte_offset0(capsys):\n    msg = \"\\u07ff\"\n    msg = \"\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_2byte_offset1(capsys):\n    msg = \"\\u07ff\"\n    msg = \"1\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_3byte_offset0(capsys):\n    msg = \"\\uffff\"\n    msg = \"\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_3byte_offset1(capsys):\n    msg = \"\\uffff\"\n    msg = \"1\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_3byte_offset2(capsys):\n    msg = \"\\uffff\"\n    msg = \"12\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_4byte_offset0(capsys):\n    msg = \"\\U0010ffff\"\n    msg = \"\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_4byte_offset1(capsys):\n    msg = \"\\U0010ffff\"\n    msg = \"1\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_4byte_offset2(capsys):\n    msg = \"\\U0010ffff\"\n    msg = \"12\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_captured_utf8_4byte_offset3(capsys):\n    msg = \"\\U0010ffff\"\n    msg = \"123\" + msg * (1024 // len(msg) + 1)\n\n    m.captured_output_default(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_guard_capture(capsys):\n    msg = \"I've been redirected to Python, I hope!\"\n    m.guard_output(msg)\n    stdout, stderr = capsys.readouterr()\n    assert stdout == msg\n    assert not stderr\n\n\ndef test_series_captured(capture):\n    with capture:\n        m.captured_output(\"a\")\n        m.captured_output(\"b\")\n    assert capture == \"ab\"\n\n\ndef test_flush(capfd):\n    msg = \"(not flushed)\"\n    msg2 = \"(flushed)\"\n\n    with m.ostream_redirect():\n        m.noisy_function(msg, flush=False)\n        stdout, stderr = capfd.readouterr()\n        assert not stdout\n\n        m.noisy_function(msg2, flush=True)\n        stdout, stderr = capfd.readouterr()\n        assert stdout == msg + msg2\n\n        m.noisy_function(msg, flush=False)\n\n    stdout, stderr = capfd.readouterr()\n    assert stdout == msg\n\n\ndef test_not_captured(capfd):\n    msg = \"Something that should not show up in log\"\n    stream = StringIO()\n    with redirect_stdout(stream):\n        m.raw_output(msg)\n    stdout, stderr = capfd.readouterr()\n    assert stdout == msg\n    assert not stderr\n    assert not stream.getvalue()\n\n    stream = StringIO()\n    with redirect_stdout(stream):\n        m.captured_output(msg)\n    stdout, stderr = capfd.readouterr()\n    assert not stdout\n    assert not stderr\n    assert stream.getvalue() == msg\n\n\ndef test_err(capfd):\n    msg = \"Something that should not show up in log\"\n    stream = StringIO()\n    with redirect_stderr(stream):\n        m.raw_err(msg)\n    stdout, stderr = capfd.readouterr()\n    assert not stdout\n    assert stderr == msg\n    assert not stream.getvalue()\n\n    stream = StringIO()\n    with redirect_stderr(stream):\n        m.captured_err(msg)\n    stdout, stderr = capfd.readouterr()\n    assert not stdout\n    assert not stderr\n    assert stream.getvalue() == msg\n\n\ndef test_multi_captured(capfd):\n    stream = StringIO()\n    with redirect_stdout(stream):\n        m.captured_output(\"a\")\n        m.raw_output(\"b\")\n        m.captured_output(\"c\")\n        m.raw_output(\"d\")\n    stdout, stderr = capfd.readouterr()\n    assert stdout == \"bd\"\n    assert stream.getvalue() == \"ac\"\n\n\ndef test_dual(capsys):\n    m.captured_dual(\"a\", \"b\")\n    stdout, stderr = capsys.readouterr()\n    assert stdout == \"a\"\n    assert stderr == \"b\"\n\n\ndef test_redirect(capfd):\n    msg = \"Should not be in log!\"\n    stream = StringIO()\n    with redirect_stdout(stream):\n        m.raw_output(msg)\n    stdout, stderr = capfd.readouterr()\n    assert stdout == msg\n    assert not stream.getvalue()\n\n    stream = StringIO()\n    with redirect_stdout(stream), m.ostream_redirect():\n        m.raw_output(msg)\n    stdout, stderr = capfd.readouterr()\n    assert not stdout\n    assert stream.getvalue() == msg\n\n    stream = StringIO()\n    with redirect_stdout(stream):\n        m.raw_output(msg)\n    stdout, stderr = capfd.readouterr()\n    assert stdout == msg\n    assert not stream.getvalue()\n\n\ndef test_redirect_err(capfd):\n    msg = \"StdOut\"\n    msg2 = \"StdErr\"\n\n    stream = StringIO()\n    with redirect_stderr(stream), m.ostream_redirect(stdout=False):\n        m.raw_output(msg)\n        m.raw_err(msg2)\n    stdout, stderr = capfd.readouterr()\n    assert stdout == msg\n    assert not stderr\n    assert stream.getvalue() == msg2\n\n\ndef test_redirect_both(capfd):\n    msg = \"StdOut\"\n    msg2 = \"StdErr\"\n\n    stream = StringIO()\n    stream2 = StringIO()\n    with redirect_stdout(stream), redirect_stderr(stream2), m.ostream_redirect():\n        m.raw_output(msg)\n        m.raw_err(msg2)\n    stdout, stderr = capfd.readouterr()\n    assert not stdout\n    assert not stderr\n    assert stream.getvalue() == msg\n    assert stream2.getvalue() == msg2\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_threading():\n    with m.ostream_redirect(stdout=True, stderr=False):\n        # start some threads\n        threads = [m.TestThread() for _j in range(20)]\n\n        # give the threads some time to fail\n        threads[0].sleep()\n\n        # stop all the threads\n        for t in threads:\n            t.stop()\n\n        for t in threads:\n            t.join()\n\n        # if a thread segfaults, we don't get here\n        assert True\n"
  },
  {
    "path": "tests/test_kwargs_and_defaults.cpp",
    "content": "/*\n    tests/test_kwargs_and_defaults.cpp -- keyword arguments and default values\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\nTEST_SUBMODULE(kwargs_and_defaults, m) {\n    auto kw_func\n        = [](int x, int y) { return \"x=\" + std::to_string(x) + \", y=\" + std::to_string(y); };\n\n    // test_named_arguments\n    m.def(\"kw_func0\", kw_func);\n    m.def(\"kw_func1\", kw_func, py::arg(\"x\"), py::arg(\"y\"));\n    m.def(\"kw_func2\", kw_func, py::arg(\"x\") = 100, py::arg(\"y\") = 200);\n    m.def(\"kw_func3\", [](const char *) {}, py::arg(\"data\") = std::string(\"Hello world!\"));\n\n    /* A fancier default argument */\n    std::vector<int> list{{13, 17}};\n    m.def(\n        \"kw_func4\",\n        [](const std::vector<int> &entries) {\n            std::string ret = \"{\";\n            for (int i : entries) {\n                ret += std::to_string(i) + \" \";\n            }\n            ret.back() = '}';\n            return ret;\n        },\n        py::arg(\"myList\") = list);\n\n    m.def(\"kw_func_udl\", kw_func, \"x\"_a, \"y\"_a = 300);\n    m.def(\"kw_func_udl_z\", kw_func, \"x\"_a, \"y\"_a = 0);\n\n    // test line breaks in default argument representation\n    struct CustomRepr {\n        std::string repr_string;\n\n        explicit CustomRepr(const std::string &repr) : repr_string(repr) {}\n\n        std::string __repr__() const { return repr_string; }\n    };\n\n    py::class_<CustomRepr>(m, \"CustomRepr\")\n        .def(py::init<const std::string &>())\n        .def(\"__repr__\", &CustomRepr::__repr__);\n\n    m.def(\n        \"kw_lb_func0\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"  array([[A, B], [C, D]])  \"));\n    m.def(\n        \"kw_lb_func1\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"  array([[A, B],\\n[C, D]])  \"));\n    m.def(\n        \"kw_lb_func2\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"\\v\\n   array([[A, B], [C, D]])\"));\n    m.def(\n        \"kw_lb_func3\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"array([[A, B], [C, D]])   \\f\\n\"));\n    m.def(\n        \"kw_lb_func4\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"array([[A, B],\\n\\f\\n[C, D]])\"));\n    m.def(\n        \"kw_lb_func5\",\n        [](const CustomRepr &) {},\n        py::arg(\"custom\") = CustomRepr(\"array([[A, B],\\r  [C, D]])\"));\n    m.def(\"kw_lb_func6\", [](const CustomRepr &) {}, py::arg(\"custom\") = CustomRepr(\" \\v\\t \"));\n    m.def(\n        \"kw_lb_func7\",\n        [](const std::string &) {},\n        py::arg(\"str_arg\") = \"First line.\\n  Second line.\");\n    m.def(\"kw_lb_func8\", [](const CustomRepr &) {}, py::arg(\"custom\") = CustomRepr(\"\"));\n\n    // test_args_and_kwargs\n    m.def(\"args_function\", [](py::args args) -> py::tuple {\n        PYBIND11_WARNING_PUSH\n\n#ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING\n        PYBIND11_WARNING_DISABLE_CLANG(\"-Wreturn-std-move\")\n#endif\n        return args;\n        PYBIND11_WARNING_POP\n    });\n    m.def(\"args_kwargs_function\", [](const py::args &args, const py::kwargs &kwargs) {\n        return py::make_tuple(args, kwargs);\n    });\n\n    // test_mixed_args_and_kwargs\n    m.def(\"mixed_plus_args\",\n          [](int i, double j, const py::args &args) { return py::make_tuple(i, j, args); });\n    m.def(\"mixed_plus_kwargs\",\n          [](int i, double j, const py::kwargs &kwargs) { return py::make_tuple(i, j, kwargs); });\n    auto mixed_plus_both = [](int i, double j, const py::args &args, const py::kwargs &kwargs) {\n        return py::make_tuple(i, j, args, kwargs);\n    };\n    m.def(\"mixed_plus_args_kwargs\", mixed_plus_both);\n\n    m.def(\"mixed_plus_args_kwargs_defaults\",\n          mixed_plus_both,\n          py::arg(\"i\") = 1,\n          py::arg(\"j\") = 3.14159);\n\n    m.def(\n        \"args_kwonly\",\n        [](int i, double j, const py::args &args, int z) { return py::make_tuple(i, j, args, z); },\n        \"i\"_a,\n        \"j\"_a,\n        \"z\"_a);\n    m.def(\n        \"args_kwonly_kwargs\",\n        [](int i, double j, const py::args &args, int z, const py::kwargs &kwargs) {\n            return py::make_tuple(i, j, args, z, kwargs);\n        },\n        \"i\"_a,\n        \"j\"_a,\n        py::kw_only{},\n        \"z\"_a);\n    m.def(\n        \"args_kwonly_kwargs_defaults\",\n        [](int i, double j, const py::args &args, int z, const py::kwargs &kwargs) {\n            return py::make_tuple(i, j, args, z, kwargs);\n        },\n        \"i\"_a = 1,\n        \"j\"_a = 3.14159,\n        \"z\"_a = 42);\n    m.def(\n        \"args_kwonly_full_monty\",\n        [](int h, int i, double j, const py::args &args, int z, const py::kwargs &kwargs) {\n            return py::make_tuple(h, i, j, args, z, kwargs);\n        },\n        py::arg() = 1,\n        py::arg() = 2,\n        py::pos_only{},\n        \"j\"_a = 3.14159,\n        \"z\"_a = 42);\n\n// test_args_refcount\n// PyPy needs a garbage collection to get the reference count values to match CPython's behaviour\n// PyPy uses the top few bits for REFCNT_FROM_PYPY & REFCNT_FROM_PYPY_LIGHT, so truncate\n#ifdef PYPY_VERSION\n#    define GC_IF_NEEDED ConstructorStats::gc()\n#    define REFCNT(x) (int) Py_REFCNT(x)\n#else\n#    define GC_IF_NEEDED\n#    define REFCNT(x) Py_REFCNT(x)\n#endif\n    m.def(\"arg_refcount_h\", [](py::handle h) {\n        GC_IF_NEEDED;\n        return h.ref_count();\n    });\n    m.def(\"arg_refcount_h\", [](py::handle h, py::handle, py::handle) {\n        GC_IF_NEEDED;\n        return h.ref_count();\n    });\n    m.def(\"arg_refcount_o\", [](const py::object &o) {\n        GC_IF_NEEDED;\n        return o.ref_count();\n    });\n    m.def(\"args_refcount\", [](py::args a) {\n        GC_IF_NEEDED;\n        py::tuple t(a.size());\n        for (size_t i = 0; i < a.size(); i++) {\n            // Use raw Python API here to avoid an extra, intermediate incref on the tuple item:\n            t[i] = REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i)));\n        }\n        return t;\n    });\n    m.def(\"mixed_args_refcount\", [](const py::object &o, py::args a) {\n        GC_IF_NEEDED;\n        py::tuple t(a.size() + 1);\n        t[0] = o.ref_count();\n        for (size_t i = 0; i < a.size(); i++) {\n            // Use raw Python API here to avoid an extra, intermediate incref on the tuple item:\n            t[i + 1] = REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i)));\n        }\n        return t;\n    });\n\n    // pybind11 won't allow these to be bound: args and kwargs, if present, must be at the end.\n    // Uncomment these to test that the static_assert is indeed working:\n    //    m.def(\"bad_args1\", [](py::args, int) {});\n    //    m.def(\"bad_args2\", [](py::kwargs, int) {});\n    //    m.def(\"bad_args3\", [](py::kwargs, py::args) {});\n    //    m.def(\"bad_args4\", [](py::args, int, py::kwargs) {});\n    //    m.def(\"bad_args5\", [](py::args, py::kwargs, int) {});\n    //    m.def(\"bad_args6\", [](py::args, py::args) {});\n    //    m.def(\"bad_args7\", [](py::kwargs, py::kwargs) {});\n\n    // test_keyword_only_args\n    m.def(\n        \"kw_only_all\",\n        [](int i, int j) { return py::make_tuple(i, j); },\n        py::kw_only(),\n        py::arg(\"i\"),\n        py::arg(\"j\"));\n    m.def(\n        \"kw_only_some\",\n        [](int i, int j, int k) { return py::make_tuple(i, j, k); },\n        py::arg(),\n        py::kw_only(),\n        py::arg(\"j\"),\n        py::arg(\"k\"));\n    m.def(\n        \"kw_only_with_defaults\",\n        [](int i, int j, int k, int z) { return py::make_tuple(i, j, k, z); },\n        py::arg() = 3,\n        \"j\"_a = 4,\n        py::kw_only(),\n        \"k\"_a = 5,\n        \"z\"_a);\n    m.def(\n        \"kw_only_mixed\",\n        [](int i, int j) { return py::make_tuple(i, j); },\n        \"i\"_a,\n        py::kw_only(),\n        \"j\"_a);\n    m.def(\n        \"kw_only_plus_more\",\n        [](int i, int j, int k, const py::kwargs &kwargs) {\n            return py::make_tuple(i, j, k, kwargs);\n        },\n        py::arg() /* positional */,\n        py::arg(\"j\") = -1 /* both */,\n        py::kw_only(),\n        py::arg(\"k\") /* kw-only */);\n\n    m.def(\"register_invalid_kw_only\", [](py::module_ m) {\n        m.def(\n            \"bad_kw_only\",\n            [](int i, int j) { return py::make_tuple(i, j); },\n            py::kw_only(),\n            py::arg() /* invalid unnamed argument */,\n            \"j\"_a);\n    });\n\n    // test_positional_only_args\n    m.def(\n        \"pos_only_all\",\n        [](int i, int j) { return py::make_tuple(i, j); },\n        py::arg(\"i\"),\n        py::arg(\"j\"),\n        py::pos_only());\n    m.def(\n        \"pos_only_mix\",\n        [](int i, int j) { return py::make_tuple(i, j); },\n        py::arg(\"i\"),\n        py::pos_only(),\n        py::arg(\"j\"));\n    m.def(\n        \"pos_kw_only_mix\",\n        [](int i, int j, int k) { return py::make_tuple(i, j, k); },\n        py::arg(\"i\"),\n        py::pos_only(),\n        py::arg(\"j\"),\n        py::kw_only(),\n        py::arg(\"k\"));\n    m.def(\n        \"pos_only_def_mix\",\n        [](int i, int j, int k) { return py::make_tuple(i, j, k); },\n        py::arg(\"i\"),\n        py::arg(\"j\") = 2,\n        py::pos_only(),\n        py::arg(\"k\") = 3);\n\n    // These should fail to compile:\n#ifdef PYBIND11_NEVER_DEFINED_EVER\n    // argument annotations are required when using kw_only\n    m.def(\"bad_kw_only1\", [](int) {}, py::kw_only());\n    // can't specify both `py::kw_only` and a `py::args` argument\n    m.def(\"bad_kw_only2\", [](int i, py::args) {}, py::kw_only(), \"i\"_a);\n#endif\n\n    // test_function_signatures (along with most of the above)\n    struct KWClass {\n        void foo(int, float) {}\n    };\n    py::class_<KWClass>(m, \"KWClass\")\n        .def(\"foo0\", &KWClass::foo)\n        .def(\"foo1\", &KWClass::foo, \"x\"_a, \"y\"_a);\n\n    // Make sure a class (not an instance) can be used as a default argument.\n    // The return value doesn't matter, only that the module is importable.\n    m.def(\n        \"class_default_argument\",\n        [](py::object a) { return py::repr(std::move(a)); },\n        \"a\"_a = py::module_::import(\"decimal\").attr(\"Decimal\"));\n\n    // Initial implementation of kw_only was broken when used on a method/constructor before any\n    // other arguments\n    // https://github.com/pybind/pybind11/pull/3402#issuecomment-963341987\n\n    struct first_arg_kw_only {};\n    py::class_<first_arg_kw_only>(m, \"first_arg_kw_only\")\n        .def(py::init([](int) { return first_arg_kw_only(); }),\n             py::kw_only(), // This being before any args was broken\n             py::arg(\"i\") = 0)\n        .def(\n            \"method\",\n            [](first_arg_kw_only &, int, int) {},\n            py::kw_only(), // and likewise here\n            py::arg(\"i\") = 1,\n            py::arg(\"j\") = 2)\n        // Closely related: pos_only marker didn't show up properly when it was before any other\n        // arguments (although that is fairly useless in practice).\n        .def(\n            \"pos_only\",\n            [](first_arg_kw_only &, int, int) {},\n            py::pos_only{},\n            py::arg(\"i\"),\n            py::arg(\"j\"));\n\n    // Test support for args and kwargs subclasses\n    m.def(\"args_kwargs_subclass_function\",\n          [](const py::Args<std::string> &args, const py::KWArgs<std::string> &kwargs) {\n              return py::make_tuple(args, kwargs);\n          });\n}\n"
  },
  {
    "path": "tests/test_kwargs_and_defaults.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import kwargs_and_defaults as m\n\n\ndef test_function_signatures(doc):\n    assert (\n        doc(m.kw_func0)\n        == \"kw_func0(arg0: typing.SupportsInt | typing.SupportsIndex, arg1: typing.SupportsInt | typing.SupportsIndex) -> str\"\n    )\n    assert (\n        doc(m.kw_func1)\n        == \"kw_func1(x: typing.SupportsInt | typing.SupportsIndex, y: typing.SupportsInt | typing.SupportsIndex) -> str\"\n    )\n    assert (\n        doc(m.kw_func2)\n        == \"kw_func2(x: typing.SupportsInt | typing.SupportsIndex = 100, y: typing.SupportsInt | typing.SupportsIndex = 200) -> str\"\n    )\n    assert doc(m.kw_func3) == \"kw_func3(data: str = 'Hello world!') -> None\"\n    assert (\n        doc(m.kw_func4)\n        == \"kw_func4(myList: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = [13, 17]) -> str\"\n    )\n    assert (\n        doc(m.kw_func_udl)\n        == \"kw_func_udl(x: typing.SupportsInt | typing.SupportsIndex, y: typing.SupportsInt | typing.SupportsIndex = 300) -> str\"\n    )\n    assert (\n        doc(m.kw_func_udl_z)\n        == \"kw_func_udl_z(x: typing.SupportsInt | typing.SupportsIndex, y: typing.SupportsInt | typing.SupportsIndex = 0) -> str\"\n    )\n    assert doc(m.args_function) == \"args_function(*args) -> tuple\"\n    assert (\n        doc(m.args_kwargs_function)\n        == \"args_kwargs_function(*args, **kwargs) -> tuple[tuple, dict[str, typing.Any]]\"\n    )\n    assert (\n        doc(m.args_kwargs_subclass_function)\n        == \"args_kwargs_subclass_function(*args: str, **kwargs: str) -> tuple[tuple[str, ...], dict[str, str]]\"\n    )\n    assert (\n        doc(m.KWClass.foo0)\n        == \"foo0(self: m.kwargs_and_defaults.KWClass, arg0: typing.SupportsInt | typing.SupportsIndex, arg1: typing.SupportsFloat | typing.SupportsIndex) -> None\"\n    )\n    assert (\n        doc(m.KWClass.foo1)\n        == \"foo1(self: m.kwargs_and_defaults.KWClass, x: typing.SupportsInt | typing.SupportsIndex, y: typing.SupportsFloat | typing.SupportsIndex) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func0)\n        == \"kw_lb_func0(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func1)\n        == \"kw_lb_func1(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func2)\n        == \"kw_lb_func2(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func3)\n        == \"kw_lb_func3(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func4)\n        == \"kw_lb_func4(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func5)\n        == \"kw_lb_func5(custom: m.kwargs_and_defaults.CustomRepr = array([[A, B], [C, D]])) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func6)\n        == \"kw_lb_func6(custom: m.kwargs_and_defaults.CustomRepr = ) -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func7)\n        == \"kw_lb_func7(str_arg: str = 'First line.\\\\n  Second line.') -> None\"\n    )\n    assert (\n        doc(m.kw_lb_func8)\n        == \"kw_lb_func8(custom: m.kwargs_and_defaults.CustomRepr = ) -> None\"\n    )\n\n\ndef test_named_arguments():\n    assert m.kw_func0(5, 10) == \"x=5, y=10\"\n\n    assert m.kw_func1(5, 10) == \"x=5, y=10\"\n    assert m.kw_func1(5, y=10) == \"x=5, y=10\"\n    assert m.kw_func1(y=10, x=5) == \"x=5, y=10\"\n\n    assert m.kw_func2() == \"x=100, y=200\"\n    assert m.kw_func2(5) == \"x=5, y=200\"\n    assert m.kw_func2(x=5) == \"x=5, y=200\"\n    assert m.kw_func2(y=10) == \"x=100, y=10\"\n    assert m.kw_func2(5, 10) == \"x=5, y=10\"\n    assert m.kw_func2(x=5, y=10) == \"x=5, y=10\"\n\n    with pytest.raises(TypeError) as excinfo:\n        # noinspection PyArgumentList\n        m.kw_func2(x=5, y=10, z=12)\n    assert excinfo.match(\n        r\"(?s)^kw_func2\\(\\): incompatible.*Invoked with: kwargs: ((x=5|y=10|z=12)(, |$)){3}$\"\n    )\n\n    assert m.kw_func4() == \"{13 17}\"\n    assert m.kw_func4(myList=[1, 2, 3]) == \"{1 2 3}\"\n\n    assert m.kw_func_udl(x=5, y=10) == \"x=5, y=10\"\n    assert m.kw_func_udl_z(x=5) == \"x=5, y=0\"\n\n\ndef test_arg_and_kwargs():\n    args = \"arg1_value\", \"arg2_value\", 3\n    assert m.args_function(*args) == args\n\n    args = \"a1\", \"a2\"\n    kwargs = {\"arg3\": \"a3\", \"arg4\": 4}\n    assert m.args_kwargs_function(*args, **kwargs) == (args, kwargs)\n    assert m.args_kwargs_subclass_function(*args, **kwargs) == (args, kwargs)\n\n\ndef test_mixed_args_and_kwargs(msg):\n    mpa = m.mixed_plus_args\n    mpk = m.mixed_plus_kwargs\n    mpak = m.mixed_plus_args_kwargs\n    mpakd = m.mixed_plus_args_kwargs_defaults\n\n    assert mpa(1, 2.5, 4, 99.5, None) == (1, 2.5, (4, 99.5, None))\n    assert mpa(1, 2.5) == (1, 2.5, ())\n    with pytest.raises(TypeError) as excinfo:\n        assert mpa(1)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        mixed_plus_args(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: typing.SupportsInt | typing.SupportsIndex, arg1: typing.SupportsFloat | typing.SupportsIndex, *args) -> tuple[int, float, tuple]\n\n        Invoked with: 1\n    \"\"\"\n    )\n    with pytest.raises(TypeError) as excinfo:\n        assert mpa()\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        mixed_plus_args(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: typing.SupportsInt | typing.SupportsIndex, arg1: typing.SupportsFloat | typing.SupportsIndex, *args) -> tuple[int, float, tuple]\n\n        Invoked with:\n    \"\"\"\n    )\n\n    assert mpk(-2, 3.5, pi=3.14159, e=2.71828) == (\n        -2,\n        3.5,\n        {\"e\": 2.71828, \"pi\": 3.14159},\n    )\n    assert mpak(7, 7.7, 7.77, 7.777, 7.7777, minusseven=-7) == (\n        7,\n        7.7,\n        (7.77, 7.777, 7.7777),\n        {\"minusseven\": -7},\n    )\n    assert mpakd() == (1, 3.14159, (), {})\n    assert mpakd(3) == (3, 3.14159, (), {})\n    assert mpakd(j=2.71828) == (1, 2.71828, (), {})\n    assert mpakd(k=42) == (1, 3.14159, (), {\"k\": 42})\n    assert mpakd(1, 1, 2, 3, 5, 8, then=13, followedby=21) == (\n        1,\n        1,\n        (2, 3, 5, 8),\n        {\"then\": 13, \"followedby\": 21},\n    )\n    # Arguments specified both positionally and via kwargs should fail:\n    with pytest.raises(TypeError) as excinfo:\n        assert mpakd(1, i=1)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        mixed_plus_args_kwargs_defaults(): incompatible function arguments. The following argument types are supported:\n            1. (i: typing.SupportsInt | typing.SupportsIndex = 1, j: typing.SupportsFloat | typing.SupportsIndex = 3.14159, *args, **kwargs) -> tuple[int, float, tuple, dict[str, typing.Any]]\n\n        Invoked with: 1; kwargs: i=1\n    \"\"\"\n    )\n    with pytest.raises(TypeError) as excinfo:\n        assert mpakd(1, 2, j=1)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        mixed_plus_args_kwargs_defaults(): incompatible function arguments. The following argument types are supported:\n            1. (i: typing.SupportsInt | typing.SupportsIndex = 1, j: typing.SupportsFloat | typing.SupportsIndex = 3.14159, *args, **kwargs) -> tuple[int, float, tuple, dict[str, typing.Any]]\n\n        Invoked with: 1, 2; kwargs: j=1\n    \"\"\"\n    )\n\n    # Arguments after a py::args are automatically keyword-only (pybind 2.9+)\n    assert m.args_kwonly(2, 2.5, z=22) == (2, 2.5, (), 22)\n    assert m.args_kwonly(2, 2.5, \"a\", \"b\", \"c\", z=22) == (2, 2.5, (\"a\", \"b\", \"c\"), 22)\n    assert m.args_kwonly(z=22, i=4, j=16) == (4, 16, (), 22)\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.args_kwonly(2, 2.5, 22)  # missing z= keyword\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        args_kwonly(): incompatible function arguments. The following argument types are supported:\n            1. (i: typing.SupportsInt | typing.SupportsIndex, j: typing.SupportsFloat | typing.SupportsIndex, *args, z: typing.SupportsInt | typing.SupportsIndex) -> tuple[int, float, tuple, int]\n\n        Invoked with: 2, 2.5, 22\n    \"\"\"\n    )\n\n    assert m.args_kwonly_kwargs(i=1, k=4, j=10, z=-1, y=9) == (\n        1,\n        10,\n        (),\n        -1,\n        {\"k\": 4, \"y\": 9},\n    )\n    assert m.args_kwonly_kwargs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, z=11, y=12) == (\n        1,\n        2,\n        (3, 4, 5, 6, 7, 8, 9, 10),\n        11,\n        {\"y\": 12},\n    )\n    assert (\n        m.args_kwonly_kwargs.__doc__\n        == \"args_kwonly_kwargs(i: typing.SupportsInt | typing.SupportsIndex, j: typing.SupportsFloat | typing.SupportsIndex, *args, z: typing.SupportsInt | typing.SupportsIndex, **kwargs) -> tuple[int, float, tuple, int, dict[str, typing.Any]]\\n\"\n    )\n\n    assert (\n        m.args_kwonly_kwargs_defaults.__doc__\n        == \"args_kwonly_kwargs_defaults(i: typing.SupportsInt | typing.SupportsIndex = 1, j: typing.SupportsFloat | typing.SupportsIndex = 3.14159, *args, z: typing.SupportsInt | typing.SupportsIndex = 42, **kwargs) -> tuple[int, float, tuple, int, dict[str, typing.Any]]\\n\"\n    )\n    assert m.args_kwonly_kwargs_defaults() == (1, 3.14159, (), 42, {})\n    assert m.args_kwonly_kwargs_defaults(2) == (2, 3.14159, (), 42, {})\n    assert m.args_kwonly_kwargs_defaults(z=-99) == (1, 3.14159, (), -99, {})\n    assert m.args_kwonly_kwargs_defaults(5, 6, 7, 8) == (5, 6, (7, 8), 42, {})\n    assert m.args_kwonly_kwargs_defaults(5, 6, 7, m=8) == (5, 6, (7,), 42, {\"m\": 8})\n    assert m.args_kwonly_kwargs_defaults(5, 6, 7, m=8, z=9) == (5, 6, (7,), 9, {\"m\": 8})\n\n\ndef test_keyword_only_args(msg):\n    assert m.kw_only_all(i=1, j=2) == (1, 2)\n    assert m.kw_only_all(j=1, i=2) == (2, 1)\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.kw_only_all(i=1) == (1,)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.kw_only_all(1, 2) == (1, 2)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    assert m.kw_only_some(1, k=3, j=2) == (1, 2, 3)\n\n    assert m.kw_only_with_defaults(z=8) == (3, 4, 5, 8)\n    assert m.kw_only_with_defaults(2, z=8) == (2, 4, 5, 8)\n    assert m.kw_only_with_defaults(2, j=7, k=8, z=9) == (2, 7, 8, 9)\n    assert m.kw_only_with_defaults(2, 7, z=9, k=8) == (2, 7, 8, 9)\n\n    assert m.kw_only_mixed(1, j=2) == (1, 2)\n    assert m.kw_only_mixed(j=2, i=3) == (3, 2)\n    assert m.kw_only_mixed(i=2, j=3) == (2, 3)\n\n    assert m.kw_only_plus_more(4, 5, k=6, extra=7) == (4, 5, 6, {\"extra\": 7})\n    assert m.kw_only_plus_more(3, k=5, j=4, extra=6) == (3, 4, 5, {\"extra\": 6})\n    assert m.kw_only_plus_more(2, k=3, extra=4) == (2, -1, 3, {\"extra\": 4})\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.kw_only_mixed(i=1) == (1,)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.register_invalid_kw_only(m)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        arg(): cannot specify an unnamed argument after a kw_only() annotation or args() argument\n    \"\"\"\n    )\n\n    # https://github.com/pybind/pybind11/pull/3402#issuecomment-963341987\n    x = m.first_arg_kw_only(i=1)\n    x.method()\n    x.method(i=1, j=2)\n    assert (\n        m.first_arg_kw_only.__init__.__doc__\n        == \"__init__(self: pybind11_tests.kwargs_and_defaults.first_arg_kw_only, *, i: typing.SupportsInt | typing.SupportsIndex = 0) -> None\\n\"\n    )\n    assert (\n        m.first_arg_kw_only.method.__doc__\n        == \"method(self: pybind11_tests.kwargs_and_defaults.first_arg_kw_only, *, i: typing.SupportsInt | typing.SupportsIndex = 1, j: typing.SupportsInt | typing.SupportsIndex = 2) -> None\\n\"\n    )\n\n\ndef test_positional_only_args():\n    assert m.pos_only_all(1, 2) == (1, 2)\n    assert m.pos_only_all(2, 1) == (2, 1)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_only_all(i=1, j=2)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    assert m.pos_only_mix(1, 2) == (1, 2)\n    assert m.pos_only_mix(2, j=1) == (2, 1)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_only_mix(i=1, j=2)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    assert m.pos_kw_only_mix(1, 2, k=3) == (1, 2, 3)\n    assert m.pos_kw_only_mix(1, j=2, k=3) == (1, 2, 3)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_kw_only_mix(i=1, j=2, k=3)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_kw_only_mix(1, 2, 3)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_only_def_mix()\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    assert m.pos_only_def_mix(1) == (1, 2, 3)\n    assert m.pos_only_def_mix(1, 4) == (1, 4, 3)\n    assert m.pos_only_def_mix(1, 4, 7) == (1, 4, 7)\n    assert m.pos_only_def_mix(1, 4, k=7) == (1, 4, 7)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.pos_only_def_mix(1, j=4)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    # Mix it with args and kwargs:\n    assert (\n        m.args_kwonly_full_monty.__doc__\n        == \"args_kwonly_full_monty(arg0: typing.SupportsInt | typing.SupportsIndex = 1, arg1: typing.SupportsInt | typing.SupportsIndex = 2, /, j: typing.SupportsFloat | typing.SupportsIndex = 3.14159, *args, z: typing.SupportsInt | typing.SupportsIndex = 42, **kwargs) -> tuple[int, int, float, tuple, int, dict[str, typing.Any]]\\n\"\n    )\n    assert m.args_kwonly_full_monty() == (1, 2, 3.14159, (), 42, {})\n    assert m.args_kwonly_full_monty(8) == (8, 2, 3.14159, (), 42, {})\n    assert m.args_kwonly_full_monty(8, 9) == (8, 9, 3.14159, (), 42, {})\n    assert m.args_kwonly_full_monty(8, 9, 10) == (8, 9, 10.0, (), 42, {})\n    assert m.args_kwonly_full_monty(3, 4, 5, 6, 7, m=8, z=9) == (\n        3,\n        4,\n        5.0,\n        (\n            6,\n            7,\n        ),\n        9,\n        {\"m\": 8},\n    )\n    assert m.args_kwonly_full_monty(3, 4, 5, 6, 7, m=8, z=9) == (\n        3,\n        4,\n        5.0,\n        (\n            6,\n            7,\n        ),\n        9,\n        {\"m\": 8},\n    )\n    assert m.args_kwonly_full_monty(5, j=7, m=8, z=9) == (5, 2, 7.0, (), 9, {\"m\": 8})\n    assert m.args_kwonly_full_monty(i=5, j=7, m=8, z=9) == (\n        1,\n        2,\n        7.0,\n        (),\n        9,\n        {\"i\": 5, \"m\": 8},\n    )\n\n    # pos_only at the beginning of the argument list was \"broken\" in how it was displayed (though\n    # this is fairly useless in practice).  Related to:\n    # https://github.com/pybind/pybind11/pull/3402#issuecomment-963341987\n    assert (\n        m.first_arg_kw_only.pos_only.__doc__\n        == \"pos_only(self: pybind11_tests.kwargs_and_defaults.first_arg_kw_only, /, i: typing.SupportsInt | typing.SupportsIndex, j: typing.SupportsInt | typing.SupportsIndex) -> None\\n\"\n    )\n\n\ndef test_signatures():\n    assert (\n        m.kw_only_all.__doc__\n        == \"kw_only_all(*, i: typing.SupportsInt | typing.SupportsIndex, j: typing.SupportsInt | typing.SupportsIndex) -> tuple[int, int]\\n\"\n    )\n    assert (\n        m.kw_only_mixed.__doc__\n        == \"kw_only_mixed(i: typing.SupportsInt | typing.SupportsIndex, *, j: typing.SupportsInt | typing.SupportsIndex) -> tuple[int, int]\\n\"\n    )\n    assert (\n        m.pos_only_all.__doc__\n        == \"pos_only_all(i: typing.SupportsInt | typing.SupportsIndex, j: typing.SupportsInt | typing.SupportsIndex, /) -> tuple[int, int]\\n\"\n    )\n    assert (\n        m.pos_only_mix.__doc__\n        == \"pos_only_mix(i: typing.SupportsInt | typing.SupportsIndex, /, j: typing.SupportsInt | typing.SupportsIndex) -> tuple[int, int]\\n\"\n    )\n    assert (\n        m.pos_kw_only_mix.__doc__\n        == \"pos_kw_only_mix(i: typing.SupportsInt | typing.SupportsIndex, /, j: typing.SupportsInt | typing.SupportsIndex, *, k: typing.SupportsInt | typing.SupportsIndex) -> tuple[int, int, int]\\n\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Different refcounting mechanism\")\ndef test_args_refcount():\n    \"\"\"Issue/PR #1216 - py::args elements get double-inc_ref()ed when combined with regular\n    arguments\"\"\"\n    refcount = m.arg_refcount_h\n\n    myval = object()\n    expected = refcount(myval)\n    assert m.arg_refcount_h(myval) == expected\n    assert m.arg_refcount_o(myval) == expected + 1\n    assert m.arg_refcount_h(myval) == expected\n    assert refcount(myval) == expected\n\n    assert m.mixed_plus_args(1, 2.0, \"a\", myval) == (1, 2.0, (\"a\", myval))\n    assert refcount(myval) == expected\n\n    assert m.mixed_plus_kwargs(3, 4.0, a=1, b=myval) == (3, 4.0, {\"a\": 1, \"b\": myval})\n    assert refcount(myval) == expected\n\n    assert m.args_function(-1, myval) == (-1, myval)\n    assert refcount(myval) == expected\n\n    assert m.mixed_plus_args_kwargs(5, 6.0, myval, a=myval) == (\n        5,\n        6.0,\n        (myval,),\n        {\"a\": myval},\n    )\n    assert refcount(myval) == expected\n\n    assert m.args_kwargs_function(7, 8, myval, a=1, b=myval) == (\n        (7, 8, myval),\n        {\"a\": 1, \"b\": myval},\n    )\n    assert refcount(myval) == expected\n\n    assert m.args_kwargs_subclass_function(7, 8, myval, a=1, b=myval) == (\n        (7, 8, myval),\n        {\"a\": 1, \"b\": myval},\n    )\n    assert refcount(myval) == expected\n\n    exp3 = refcount(myval, myval, myval)\n    # if we have to create a new tuple internally, then it will hold an extra reference for each item in it.\n    assert m.args_refcount(myval, myval, myval) == (exp3 + 3, exp3 + 3, exp3 + 3)\n    assert refcount(myval) == expected\n\n    # This function takes the first arg as a `py::object` and the rest as a `py::args`.  Unlike the\n    # previous case, when we have both positional and `py::args` we need to construct a new tuple\n    # for the `py::args`; in the previous case, we could simply inc_ref and pass on Python's input\n    # tuple without having to inc_ref the individual elements, but here we can't, hence the extra\n    # refs.\n    exp3_3 = exp3 + 3\n    assert m.mixed_args_refcount(myval, myval, myval) == (exp3_3, exp3_3, exp3_3)\n\n    assert m.class_default_argument() == \"<class 'decimal.Decimal'>\"\n"
  },
  {
    "path": "tests/test_local_bindings.cpp",
    "content": "/*\n    tests/test_local_bindings.cpp -- tests the py::module_local class feature which makes a class\n                                     binding local to the module in which it is defined.\n\n    Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n#include <pybind11/stl_bind.h>\n\n#include \"local_bindings.h\"\n#include \"pybind11_tests.h\"\n\n#include <numeric>\n#include <utility>\n\nTEST_SUBMODULE(local_bindings, m) {\n    // test_load_external\n    m.def(\"load_external1\", [](ExternalType1 &e) { return e.i; });\n    m.def(\"load_external2\", [](ExternalType2 &e) { return e.i; });\n    m.def(\"load_external3\", [](ExternalType3 &e) { return e.i; });\n\n    struct SharedKeepAlive {\n        std::shared_ptr<int> contents;\n        int value() const { return contents ? *contents : -20251012; }\n        long use_count() const { return contents.use_count(); }\n    };\n    py::class_<SharedKeepAlive>(m, \"SharedKeepAlive\")\n        .def_property_readonly(\"value\", &SharedKeepAlive::value)\n        .def_property_readonly(\"use_count\", &SharedKeepAlive::use_count);\n    m.def(\"load_external2_shared\", [](const std::shared_ptr<ExternalType2> &p) {\n        return SharedKeepAlive{std::shared_ptr<int>(p, &p->i)};\n    });\n    m.def(\"load_external3_shared\", [](const std::shared_ptr<ExternalType3> &p) {\n        return SharedKeepAlive{std::shared_ptr<int>(p, &p->i)};\n    });\n    m.def(\"load_external1_unique\", [](std::unique_ptr<ExternalType1> p) { return p->i; });\n    m.def(\"load_external3_unique\", [](std::unique_ptr<ExternalType3> p) { return p->i; });\n\n    // Aspects of set_foreign_holder that are not covered:\n    // - loading a foreign instance into a custom holder should fail\n    // - we're only covering the case where the local module doesn't know\n    //   about the type; the paths where it does (e.g., if both global and\n    //   foreign-module-local bindings exist for the same type) should work\n    //   the same way (they use the same code so they very likely do)\n\n    // test_local_bindings\n    // Register a class with py::module_local:\n    bind_local<LocalType, -1>(m, \"LocalType\", py::module_local()).def(\"get3\", [](LocalType &t) {\n        return t.i + 3;\n    });\n\n    m.def(\"local_value\", [](LocalType &l) { return l.i; });\n\n    // test_nonlocal_failure\n    // The main pybind11 test module is loaded first, so this registration will succeed (the second\n    // one, in pybind11_cross_module_tests.cpp, is designed to fail):\n    bind_local<NonLocalType, 0>(m, \"NonLocalType\")\n        .def(py::init<int>())\n        .def(\"get\", [](LocalType &i) { return i.i; });\n\n    // test_duplicate_local\n    // py::module_local declarations should be visible across compilation units that get linked\n    // together; this tries to register a duplicate local.  It depends on a definition in\n    // test_class.cpp and should raise a runtime error from the duplicate definition attempt.  If\n    // test_class isn't available it *also* throws a runtime error (with \"test_class not enabled\"\n    // as value).\n    m.def(\"register_local_external\", [m]() {\n        auto main = py::module_::import(\"pybind11_tests\");\n        if (py::hasattr(main, \"class_\")) {\n            bind_local<LocalExternal, 7>(m, \"LocalExternal\", py::module_local());\n        } else {\n            throw std::runtime_error(\"test_class not enabled\");\n        }\n    });\n\n    // test_stl_bind_local\n    // stl_bind.h binders defaults to py::module_local if the types are local or converting:\n    py::bind_vector<LocalVec>(m, \"LocalVec\");\n    py::bind_map<LocalMap>(m, \"LocalMap\");\n    // and global if the type (or one of the types, for the map) is global:\n    py::bind_vector<NonLocalVec>(m, \"NonLocalVec\");\n    py::bind_map<NonLocalMap>(m, \"NonLocalMap\");\n\n    // test_stl_bind_global\n    // They can, however, be overridden to global using `py::module_local(false)`:\n    bind_local<NonLocal2, 10>(m, \"NonLocal2\");\n    py::bind_vector<LocalVec2>(m, \"LocalVec2\", py::module_local());\n    py::bind_map<NonLocalMap2>(m, \"NonLocalMap2\", py::module_local(false));\n\n    // test_mixed_local_global\n    // We try this both with the global type registered first and vice versa (the order shouldn't\n    // matter).\n    m.def(\"register_mixed_global\", [m]() {\n        bind_local<MixedGlobalLocal, 100>(m, \"MixedGlobalLocal\", py::module_local(false));\n    });\n    m.def(\"register_mixed_local\", [m]() {\n        bind_local<MixedLocalGlobal, 1000>(m, \"MixedLocalGlobal\", py::module_local());\n    });\n    m.def(\"get_mixed_gl\", [](int i) { return MixedGlobalLocal(i); });\n    m.def(\"get_mixed_lg\", [](int i) { return MixedLocalGlobal(i); });\n\n    // test_internal_locals_differ\n    m.def(\"local_cpp_types_addr\",\n          []() { return (uintptr_t) &py::detail::get_local_internals().registered_types_cpp; });\n\n    // test_stl_caster_vs_stl_bind\n    m.def(\"load_vector_via_caster\",\n          [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); });\n\n    // test_cross_module_calls\n    m.def(\"return_self\", [](LocalVec *v) { return v; });\n    m.def(\"return_copy\", [](const LocalVec &v) { return LocalVec(v); });\n\n    class Cat : public pets::Pet {\n    public:\n        explicit Cat(std::string name) : Pet(std::move(name)) {}\n    };\n    py::class_<pets::Pet>(m, \"Pet\", py::module_local()).def(\"get_name\", &pets::Pet::name);\n    // Binding for local extending class:\n    py::class_<Cat, pets::Pet>(m, \"Cat\").def(py::init<std::string>());\n    m.def(\"pet_name\", [](pets::Pet &p) { return p.name(); });\n\n    py::class_<MixGL>(m, \"MixGL\").def(py::init<int>());\n    m.def(\"get_gl_value\", [](MixGL &o) { return o.i + 10; });\n\n    py::class_<MixGL2>(m, \"MixGL2\").def(py::init<int>());\n}\n"
  },
  {
    "path": "tests/test_local_bindings.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom contextlib import suppress\n\nimport pytest\n\nfrom pybind11_tests import local_bindings as m\n\n\ndef test_load_external():\n    \"\"\"Load a `py::module_local` type that's only registered in an external module\"\"\"\n    import pybind11_cross_module_tests as cm\n\n    assert m.load_external1(cm.ExternalType1(11)) == 11\n    assert m.load_external2(cm.ExternalType2(22)) == 22\n    assert m.load_external3(cm.ExternalType3(33)) == 33\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.load_external2(cm.ExternalType1(21)) == 21\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        assert m.load_external1(cm.ExternalType2(12)) == 12\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    def test_shared(val, ctor, loader):\n        obj = ctor(val)\n        with suppress(AttributeError):  # non-cpython VMs don't have getrefcount\n            rc_before = sys.getrefcount(obj)\n        wrapper = loader(obj)\n        # wrapper holds a shared_ptr that keeps obj alive\n        assert wrapper.use_count == 1\n        assert wrapper.value == val\n        with suppress(AttributeError):\n            rc_after = sys.getrefcount(obj)\n            assert rc_after > rc_before\n\n    test_shared(220, cm.ExternalType2, m.load_external2_shared)\n    test_shared(330, cm.ExternalType3, m.load_external3_shared)\n\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        test_shared(320, cm.ExternalType2, m.load_external3_shared)\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        test_shared(230, cm.ExternalType3, m.load_external2_shared)\n\n    with pytest.raises(\n        RuntimeError, match=\"Foreign instance cannot be converted to std::unique_ptr\"\n    ):\n        m.load_external1_unique(cm.ExternalType1(2200))\n\n    with pytest.raises(\n        RuntimeError, match=\"Foreign instance cannot be converted to std::unique_ptr\"\n    ):\n        m.load_external3_unique(cm.ExternalType3(3300))\n\n\ndef test_local_bindings():\n    \"\"\"Tests that duplicate `py::module_local` class bindings work across modules\"\"\"\n\n    # Make sure we can load the second module with the conflicting (but local) definition:\n    import pybind11_cross_module_tests as cm\n\n    i1 = m.LocalType(5)\n    assert i1.get() == 4\n    assert i1.get3() == 8\n\n    i2 = cm.LocalType(10)\n    assert i2.get() == 11\n    assert i2.get2() == 12\n\n    assert not hasattr(i1, \"get2\")\n    assert not hasattr(i2, \"get3\")\n\n    # Loading within the local module\n    assert m.local_value(i1) == 5\n    assert cm.local_value(i2) == 10\n\n    # Cross-module loading works as well (on failure, the type loader looks for\n    # external module-local converters):\n    assert m.local_value(i2) == 10\n    assert cm.local_value(i1) == 5\n\n\ndef test_nonlocal_failure():\n    \"\"\"Tests that attempting to register a non-local type in multiple modules fails\"\"\"\n    import pybind11_cross_module_tests as cm\n\n    with pytest.raises(RuntimeError) as excinfo:\n        cm.register_nonlocal()\n    assert (\n        str(excinfo.value) == 'generic_type: type \"NonLocalType\" is already registered!'\n    )\n\n\ndef test_duplicate_local():\n    \"\"\"Tests expected failure when registering a class twice with py::local in the same module\"\"\"\n    with pytest.raises(RuntimeError) as excinfo:\n        m.register_local_external()\n    import pybind11_tests\n\n    assert str(excinfo.value) == (\n        'generic_type: type \"LocalExternal\" is already registered!'\n        if hasattr(pybind11_tests, \"class_\")\n        else \"test_class not enabled\"\n    )\n\n\ndef test_stl_bind_local():\n    import pybind11_cross_module_tests as cm\n\n    v1, v2 = m.LocalVec(), cm.LocalVec()\n    v1.append(m.LocalType(1))\n    v1.append(m.LocalType(2))\n    v2.append(cm.LocalType(1))\n    v2.append(cm.LocalType(2))\n\n    # Cross module value loading:\n    v1.append(cm.LocalType(3))\n    v2.append(m.LocalType(3))\n\n    assert [i.get() for i in v1] == [0, 1, 2]\n    assert [i.get() for i in v2] == [2, 3, 4]\n\n    v3, v4 = m.NonLocalVec(), cm.NonLocalVec2()\n    v3.append(m.NonLocalType(1))\n    v3.append(m.NonLocalType(2))\n    v4.append(m.NonLocal2(3))\n    v4.append(m.NonLocal2(4))\n\n    assert [i.get() for i in v3] == [1, 2]\n    assert [i.get() for i in v4] == [13, 14]\n\n    d1, d2 = m.LocalMap(), cm.LocalMap()\n    d1[\"a\"] = v1[0]\n    d1[\"b\"] = v1[1]\n    d2[\"c\"] = v2[0]\n    d2[\"d\"] = v2[1]\n    assert {i: d1[i].get() for i in d1} == {\"a\": 0, \"b\": 1}\n    assert {i: d2[i].get() for i in d2} == {\"c\": 2, \"d\": 3}\n\n\ndef test_stl_bind_global():\n    import pybind11_cross_module_tests as cm\n\n    with pytest.raises(RuntimeError) as excinfo:\n        cm.register_nonlocal_map()\n    assert (\n        str(excinfo.value) == 'generic_type: type \"NonLocalMap\" is already registered!'\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        cm.register_nonlocal_vec()\n    assert (\n        str(excinfo.value) == 'generic_type: type \"NonLocalVec\" is already registered!'\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        cm.register_nonlocal_map2()\n    assert (\n        str(excinfo.value) == 'generic_type: type \"NonLocalMap2\" is already registered!'\n    )\n\n\ndef test_mixed_local_global():\n    \"\"\"Local types take precedence over globally registered types: a module with a `module_local`\n    type can be registered even if the type is already registered globally.  With the module,\n    casting will go to the local type; outside the module casting goes to the global type.\n    \"\"\"\n    import pybind11_cross_module_tests as cm\n\n    m.register_mixed_global()\n    m.register_mixed_local()\n\n    a = []\n    a.append(m.MixedGlobalLocal(1))\n    a.append(m.MixedLocalGlobal(2))\n    a.append(m.get_mixed_gl(3))\n    a.append(m.get_mixed_lg(4))\n\n    assert [x.get() for x in a] == [101, 1002, 103, 1004]\n\n    cm.register_mixed_global_local()\n    cm.register_mixed_local_global()\n    a.append(m.MixedGlobalLocal(5))\n    a.append(m.MixedLocalGlobal(6))\n    a.append(cm.MixedGlobalLocal(7))\n    a.append(cm.MixedLocalGlobal(8))\n    a.append(m.get_mixed_gl(9))\n    a.append(m.get_mixed_lg(10))\n    a.append(cm.get_mixed_gl(11))\n    a.append(cm.get_mixed_lg(12))\n\n    assert [x.get() for x in a] == [\n        101,\n        1002,\n        103,\n        1004,\n        105,\n        1006,\n        207,\n        2008,\n        109,\n        1010,\n        211,\n        2012,\n    ]\n\n\ndef test_internal_locals_differ():\n    \"\"\"Makes sure the internal local type map differs across the two modules\"\"\"\n    import pybind11_cross_module_tests as cm\n\n    assert m.local_cpp_types_addr() != cm.local_cpp_types_addr()\n\n\ndef test_stl_caster_vs_stl_bind(msg):\n    \"\"\"One module uses a generic vector caster from `<pybind11/stl.h>` while the other\n    exports `std::vector<int>` via `py:bind_vector` and `py::module_local`\"\"\"\n    import pybind11_cross_module_tests as cm\n\n    v1 = cm.VectorInt([1, 2, 3])\n    assert m.load_vector_via_caster(v1) == 6\n    assert cm.load_vector_via_binding(v1) == 6\n\n    v2 = [1, 2, 3]\n    assert m.load_vector_via_caster(v2) == 6\n    with pytest.raises(TypeError) as excinfo:\n        cm.load_vector_via_binding(v2)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n    load_vector_via_binding(): incompatible function arguments. The following argument types are supported:\n        1. (arg0: pybind11_cross_module_tests.VectorInt) -> int\n\n    Invoked with: [1, 2, 3]\n    \"\"\"\n    )\n\n\ndef test_cross_module_calls():\n    import pybind11_cross_module_tests as cm\n\n    v1 = m.LocalVec()\n    v1.append(m.LocalType(1))\n    v2 = cm.LocalVec()\n    v2.append(cm.LocalType(2))\n\n    # Returning the self pointer should get picked up as returning an existing\n    # instance (even when that instance is of a foreign, non-local type).\n    assert m.return_self(v1) is v1\n    assert cm.return_self(v2) is v2\n    assert m.return_self(v2) is v2\n    assert cm.return_self(v1) is v1\n\n    assert m.LocalVec is not cm.LocalVec\n    # Returning a copy, on the other hand, always goes to the local type,\n    # regardless of where the source type came from.\n    assert type(m.return_copy(v1)) is m.LocalVec\n    assert type(m.return_copy(v2)) is m.LocalVec\n    assert type(cm.return_copy(v1)) is cm.LocalVec\n    assert type(cm.return_copy(v2)) is cm.LocalVec\n\n    # Test the example given in the documentation (which also tests inheritance casting):\n    mycat = m.Cat(\"Fluffy\")\n    mydog = cm.Dog(\"Rover\")\n    assert mycat.get_name() == \"Fluffy\"\n    assert mydog.name() == \"Rover\"\n    assert m.Cat.__base__.__name__ == \"Pet\"\n    assert cm.Dog.__base__.__name__ == \"Pet\"\n    assert m.Cat.__base__ is not cm.Dog.__base__\n    assert m.pet_name(mycat) == \"Fluffy\"\n    assert m.pet_name(mydog) == \"Rover\"\n    assert cm.pet_name(mycat) == \"Fluffy\"\n    assert cm.pet_name(mydog) == \"Rover\"\n\n    assert m.MixGL is not cm.MixGL\n    a = m.MixGL(1)\n    b = cm.MixGL(2)\n    assert m.get_gl_value(a) == 11\n    assert m.get_gl_value(b) == 12\n    assert cm.get_gl_value(a) == 101\n    assert cm.get_gl_value(b) == 102\n\n    c, d = m.MixGL2(3), cm.MixGL2(4)\n    with pytest.raises(TypeError) as excinfo:\n        m.get_gl_value(c)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.get_gl_value(d)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n"
  },
  {
    "path": "tests/test_methods_and_attributes.cpp",
    "content": "/*\n    tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access,\n    __str__, argument and return value conventions\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#if !defined(PYBIND11_OVERLOAD_CAST)\ntemplate <typename... Args>\nusing overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;\n#endif\n\nclass ExampleMandA {\npublic:\n    ExampleMandA() { print_default_created(this); }\n    explicit ExampleMandA(int value) : value(value) { print_created(this, value); }\n    ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }\n    explicit ExampleMandA(std::string &&) {}\n    ExampleMandA(ExampleMandA &&e) noexcept : value(e.value) { print_move_created(this); }\n    ~ExampleMandA() { print_destroyed(this); }\n\n    std::string toString() const { return \"ExampleMandA[value=\" + std::to_string(value) + \"]\"; }\n\n    void operator=(const ExampleMandA &e) {\n        print_copy_assigned(this);\n        value = e.value;\n    }\n    void operator=(ExampleMandA &&e) noexcept {\n        print_move_assigned(this);\n        value = e.value;\n    }\n\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    void add1(ExampleMandA other) { value += other.value; }         // passing by value\n    void add2(ExampleMandA &other) { value += other.value; }        // passing by reference\n    void add3(const ExampleMandA &other) { value += other.value; }  // passing by const reference\n    void add4(ExampleMandA *other) { value += other->value; }       // passing by pointer\n    void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer\n\n    void add6(int other) { value += other; }        // passing by value\n    void add7(int &other) { value += other; }       // passing by reference\n    void add8(const int &other) { value += other; } // passing by const reference\n    // NOLINTNEXTLINE(readability-non-const-parameter) Deliberately non-const for testing\n    void add9(int *other) { value += *other; }        // passing by pointer\n    void add10(const int *other) { value += *other; } // passing by const pointer\n\n    void consume_str(std::string &&) {}\n\n    ExampleMandA self1() { return *this; }              // return by value\n    ExampleMandA &self2() { return *this; }             // return by reference\n    const ExampleMandA &self3() const { return *this; } // return by const reference\n    ExampleMandA *self4() { return this; }              // return by pointer\n    const ExampleMandA *self5() const { return this; }  // return by const pointer\n\n    int internal1() const { return value; }        // return by value\n    int &internal2() { return value; }             // return by reference\n    const int &internal3() const { return value; } // return by const reference\n    int *internal4() { return &value; }            // return by pointer\n    const int *internal5() { return &value; }      // return by const pointer\n\n    py::str overloaded() { return \"()\"; }\n    py::str overloaded(int) { return \"(int)\"; }\n    py::str overloaded(int, float) { return \"(int, float)\"; }\n    py::str overloaded(float, int) { return \"(float, int)\"; }\n    py::str overloaded(int, int) { return \"(int, int)\"; }\n    py::str overloaded(float, float) { return \"(float, float)\"; }\n    py::str overloaded(int) const { return \"(int) const\"; }\n    py::str overloaded(int, float) const { return \"(int, float) const\"; }\n    py::str overloaded(float, int) const { return \"(float, int) const\"; }\n    py::str overloaded(int, int) const { return \"(int, int) const\"; }\n    py::str overloaded(float, float) const { return \"(float, float) const\"; }\n\n    static py::str overloaded(float) { return \"static float\"; }\n\n    int value = 0;\n};\n\nstruct TestProperties {\n    int value = 1;\n    static int static_value;\n\n    int get() const { return value; }\n    void set(int v) { value = v; }\n\n    static int static_get() { return static_value; }\n    static void static_set(int v) { static_value = v; }\n};\nint TestProperties::static_value = 1;\n\nstruct TestPropertiesOverride : TestProperties {\n    int value = 99;\n    static int static_value;\n};\nint TestPropertiesOverride::static_value = 99;\n\nstruct TestPropRVP {\n    UserType v1{1};\n    UserType v2{1};\n    static UserType sv1;\n    static UserType sv2;\n\n    const UserType &get1() const { return v1; }\n    const UserType &get2() const { return v2; }\n    UserType get_rvalue() const { return v2; }\n    void set1(int v) { v1.set(v); }\n    void set2(int v) { v2.set(v); }\n};\nUserType TestPropRVP::sv1(1);\nUserType TestPropRVP::sv2(1);\n\n// Test None-allowed py::arg argument policy\nclass NoneTester {\npublic:\n    int answer = 42;\n};\nint none1(const NoneTester &obj) { return obj.answer; }\nint none2(NoneTester *obj) { return obj ? obj->answer : -1; }\nint none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }\nint none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }\nint none5(const std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }\n\n// Issue #2778: implicit casting from None to object (not pointer)\nclass NoneCastTester {\npublic:\n    int answer = -1;\n    NoneCastTester() = default;\n    explicit NoneCastTester(int v) : answer(v) {}\n};\n\nstruct StrIssue {\n    int val = -1;\n\n    StrIssue() = default;\n    explicit StrIssue(int i) : val{i} {}\n};\n\n// Issues #854, #910: incompatible function args when member function/pointer is in unregistered\n// base class\nclass UnregisteredBase {\npublic:\n    void do_nothing() const {}\n    void increase_value() {\n        rw_value++;\n        ro_value += 0.25;\n    }\n    void set_int(int v) { rw_value = v; }\n    int get_int() const { return rw_value; }\n    double get_double() const { return ro_value; }\n    int rw_value = 42;\n    double ro_value = 1.25;\n};\nclass RegisteredDerived : public UnregisteredBase {\npublic:\n    using UnregisteredBase::UnregisteredBase;\n    double sum() const { return rw_value + ro_value; }\n};\n\n// Test explicit lvalue ref-qualification\nstruct RefQualified {\n    int value = 0;\n\n    void refQualified(int other) & { value += other; }\n    int constRefQualified(int other) const & { return value + other; }\n};\n\n// Test rvalue ref param\nstruct RValueRefParam {\n    std::size_t func1(std::string &&s) { return s.size(); }\n    std::size_t func2(std::string &&s) const { return s.size(); }\n    std::size_t func3(std::string &&s) & { return s.size(); }\n    std::size_t func4(std::string &&s) const & { return s.size(); }\n};\n\nnamespace pybind11_tests {\nnamespace exercise_is_setter {\n\nstruct FieldBase {\n    int int_value() const { return int_value_; }\n\n    FieldBase &SetIntValue(int int_value) {\n        int_value_ = int_value;\n        return *this;\n    }\n\nprivate:\n    int int_value_ = -99;\n};\n\nstruct Field : FieldBase {};\n\nvoid add_bindings(py::module &m) {\n    py::module sm = m.def_submodule(\"exercise_is_setter\");\n    // NOTE: FieldBase is not wrapped, therefore ...\n    py::class_<Field>(sm, \"Field\")\n        .def(py::init<>())\n        .def_property(\n            \"int_value\",\n            &Field::int_value,\n            &Field::SetIntValue // ... the `FieldBase &` return value here cannot be converted.\n        );\n}\n\n} // namespace exercise_is_setter\n} // namespace pybind11_tests\n\nTEST_SUBMODULE(methods_and_attributes, m) {\n    // test_methods_and_attributes\n    py::class_<ExampleMandA> emna(m, \"ExampleMandA\");\n    emna.def(py::init<>())\n        .def(py::init<int>())\n        .def(py::init<std::string &&>())\n        .def(py::init<const ExampleMandA &>())\n        .def(\"add1\", &ExampleMandA::add1)\n        .def(\"add2\", &ExampleMandA::add2)\n        .def(\"add3\", &ExampleMandA::add3)\n        .def(\"add4\", &ExampleMandA::add4)\n        .def(\"add5\", &ExampleMandA::add5)\n        .def(\"add6\", &ExampleMandA::add6)\n        .def(\"add7\", &ExampleMandA::add7)\n        .def(\"add8\", &ExampleMandA::add8)\n        .def(\"add9\", &ExampleMandA::add9)\n        .def(\"add10\", &ExampleMandA::add10)\n        .def(\"consume_str\", &ExampleMandA::consume_str)\n        .def(\"self1\", &ExampleMandA::self1)\n        .def(\"self2\", &ExampleMandA::self2)\n        .def(\"self3\", &ExampleMandA::self3)\n        .def(\"self4\", &ExampleMandA::self4)\n        .def(\"self5\", &ExampleMandA::self5)\n        .def(\"internal1\", &ExampleMandA::internal1)\n        .def(\"internal2\", &ExampleMandA::internal2)\n        .def(\"internal3\", &ExampleMandA::internal3)\n        .def(\"internal4\", &ExampleMandA::internal4)\n        .def(\"internal5\", &ExampleMandA::internal5)\n#if defined(PYBIND11_OVERLOAD_CAST)\n        .def(\"overloaded\", py::overload_cast<>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", py::overload_cast<int>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", py::overload_cast<int, int>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", py::overload_cast<int, float>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", py::overload_cast<float, int>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", py::overload_cast<float, float>(&ExampleMandA::overloaded))\n        .def(\"overloaded_float\", py::overload_cast<float, float>(&ExampleMandA::overloaded))\n        .def(\"overloaded_const\", py::overload_cast<int>(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\",\n             py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\",\n             py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\",\n             py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\",\n             py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))\n#else\n        // Use both the traditional static_cast method and the C++11 compatible overload_cast_\n        .def(\"overloaded\", overload_cast_<>()(&ExampleMandA::overloaded))\n        .def(\"overloaded\", overload_cast_<int>()(&ExampleMandA::overloaded))\n        .def(\"overloaded\", overload_cast_<int, int>()(&ExampleMandA::overloaded))\n        .def(\"overloaded\", static_cast<py::str (ExampleMandA::*)(int,    float)>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", static_cast<py::str (ExampleMandA::*)(float,  int)>(&ExampleMandA::overloaded))\n        .def(\"overloaded\", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))\n        .def(\"overloaded_float\", overload_cast_<float, float>()(&ExampleMandA::overloaded))\n        .def(\"overloaded_const\", overload_cast_<int         >()(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\", overload_cast_<int,   int>()(&ExampleMandA::overloaded, py::const_))\n        .def(\"overloaded_const\", static_cast<py::str (ExampleMandA::*)(int,   float) const>(&ExampleMandA::overloaded))\n        .def(\"overloaded_const\", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded))\n        .def(\"overloaded_const\", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))\n#endif\n        // test_no_mixed_overloads\n        // Raise error if trying to mix static/non-static overloads on the same name:\n        .def_static(\"add_mixed_overloads1\",\n                    []() {\n                        auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(\n                            py::module_::import(\"pybind11_tests.methods_and_attributes\")\n                                .attr(\"ExampleMandA\"));\n                        emna.def(\"overload_mixed1\",\n                                 static_cast<py::str (ExampleMandA::*)(int, int)>(\n                                     &ExampleMandA::overloaded))\n                            .def_static(\n                                \"overload_mixed1\",\n                                static_cast<py::str (*)(float)>(&ExampleMandA::overloaded));\n                    })\n        .def_static(\"add_mixed_overloads2\",\n                    []() {\n                        auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(\n                            py::module_::import(\"pybind11_tests.methods_and_attributes\")\n                                .attr(\"ExampleMandA\"));\n                        emna.def_static(\"overload_mixed2\",\n                                        static_cast<py::str (*)(float)>(&ExampleMandA::overloaded))\n                            .def(\"overload_mixed2\",\n                                 static_cast<py::str (ExampleMandA::*)(int, int)>(\n                                     &ExampleMandA::overloaded));\n                    })\n        .def(\"__str__\", &ExampleMandA::toString, py::pos_only())\n        .def_readwrite(\"value\", &ExampleMandA::value);\n\n    // test_copy_method\n    // Issue #443: can't call copied methods in Python 3\n    emna.attr(\"add2b\") = emna.attr(\"add2\");\n\n    // test_properties, test_static_properties, test_static_cls\n    py::class_<TestProperties>(m, \"TestProperties\")\n        .def(py::init<>())\n        .def_readonly(\"def_readonly\", &TestProperties::value)\n        .def_readwrite(\"def_readwrite\", &TestProperties::value)\n        .def_property(\"def_writeonly\", nullptr, [](TestProperties &s, int v) { s.value = v; })\n        .def_property(\"def_property_writeonly\", nullptr, &TestProperties::set)\n        .def_property_readonly(\"def_property_readonly\", &TestProperties::get)\n        .def_property(\"def_property\", &TestProperties::get, &TestProperties::set)\n        .def_property(\"def_property_impossible\", nullptr, nullptr)\n        .def_readonly_static(\"def_readonly_static\", &TestProperties::static_value)\n        .def_readwrite_static(\"def_readwrite_static\", &TestProperties::static_value)\n        .def_property_static(\"def_writeonly_static\",\n                             nullptr,\n                             [](const py::object &, int v) { TestProperties::static_value = v; })\n        .def_property_readonly_static(\n            \"def_property_readonly_static\",\n            [](const py::object &) { return TestProperties::static_get(); })\n        .def_property_static(\n            \"def_property_writeonly_static\",\n            nullptr,\n            [](const py::object &, int v) { return TestProperties::static_set(v); })\n        .def_property_static(\n            \"def_property_static\",\n            [](const py::object &) { return TestProperties::static_get(); },\n            [](const py::object &, int v) { TestProperties::static_set(v); })\n        .def_property_static(\n            \"static_cls\",\n            [](py::object cls) { return cls; },\n            [](const py::object &cls, const py::function &f) { f(cls); });\n\n    py::class_<TestPropertiesOverride, TestProperties>(m, \"TestPropertiesOverride\")\n        .def(py::init<>())\n        .def_readonly(\"def_readonly\", &TestPropertiesOverride::value)\n        .def_readonly_static(\"def_readonly_static\", &TestPropertiesOverride::static_value);\n\n    auto static_get1 = [](const py::object &) -> const UserType & { return TestPropRVP::sv1; };\n    auto static_get2 = [](const py::object &) -> const UserType & { return TestPropRVP::sv2; };\n    auto static_set1 = [](const py::object &, int v) { TestPropRVP::sv1.set(v); };\n    auto static_set2 = [](const py::object &, int v) { TestPropRVP::sv2.set(v); };\n    auto rvp_copy = py::return_value_policy::copy;\n\n    // test_property_return_value_policies\n    py::class_<TestPropRVP>(m, \"TestPropRVP\")\n        .def(py::init<>())\n        .def_property_readonly(\"ro_ref\", &TestPropRVP::get1)\n        .def_property_readonly(\"ro_copy\", &TestPropRVP::get2, rvp_copy)\n        .def_property_readonly(\"ro_func\", py::cpp_function(&TestPropRVP::get2, rvp_copy))\n        .def_property(\"rw_ref\", &TestPropRVP::get1, &TestPropRVP::set1)\n        .def_property(\"rw_copy\", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)\n        .def_property(\n            \"rw_func\", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)\n        .def_property_readonly_static(\"static_ro_ref\", static_get1)\n        .def_property_readonly_static(\"static_ro_copy\", static_get2, rvp_copy)\n        .def_property_readonly_static(\"static_ro_func\", py::cpp_function(static_get2, rvp_copy))\n        .def_property_static(\"static_rw_ref\", static_get1, static_set1)\n        .def_property_static(\"static_rw_copy\", static_get2, static_set2, rvp_copy)\n        .def_property_static(\n            \"static_rw_func\", py::cpp_function(static_get2, rvp_copy), static_set2)\n        // test_property_rvalue_policy\n        .def_property_readonly(\"rvalue\", &TestPropRVP::get_rvalue)\n        .def_property_readonly_static(\"static_rvalue\",\n                                      [](const py::object &) { return UserType(1); });\n\n    // test_metaclass_override\n    struct MetaclassOverride {};\n    py::class_<MetaclassOverride>(m, \"MetaclassOverride\", py::metaclass((PyObject *) &PyType_Type))\n        .def_property_readonly_static(\"readonly\", [](const py::object &) { return 1; });\n\n    // test_overload_ordering\n    m.def(\"overload_order\", [](const std::string &) { return 1; });\n    m.def(\"overload_order\", [](const std::string &) { return 2; });\n    m.def(\"overload_order\", [](int) { return 3; });\n    m.def(\"overload_order\", [](int) { return 4; }, py::prepend{});\n\n#if !defined(PYPY_VERSION)\n    // test_dynamic_attributes\n    class DynamicClass {\n    public:\n        DynamicClass() { print_default_created(this); }\n        DynamicClass(const DynamicClass &) = delete;\n        ~DynamicClass() { print_destroyed(this); }\n    };\n    py::class_<DynamicClass>(m, \"DynamicClass\", py::dynamic_attr()).def(py::init());\n\n    class CppDerivedDynamicClass : public DynamicClass {};\n    py::class_<CppDerivedDynamicClass, DynamicClass>(m, \"CppDerivedDynamicClass\").def(py::init());\n#endif\n\n    // test_bad_arg_default\n    // Issue/PR #648: bad arg default debugging output\n#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)\n    m.attr(\"detailed_error_messages_enabled\") = true;\n#else\n    m.attr(\"detailed_error_messages_enabled\") = false;\n#endif\n    m.def(\"bad_arg_def_named\", [] {\n        auto m = py::module_::import(\"pybind11_tests\");\n        m.def(\n            \"should_fail\",\n            [](int, UnregisteredType) {},\n            py::arg(),\n            py::arg(\"a\") = UnregisteredType());\n    });\n    m.def(\"bad_arg_def_unnamed\", [] {\n        auto m = py::module_::import(\"pybind11_tests\");\n        m.def(\n            \"should_fail\",\n            [](int, UnregisteredType) {},\n            py::arg(),\n            py::arg() = UnregisteredType());\n    });\n\n    // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.\n\n    // test_accepts_none\n    py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, \"NoneTester\").def(py::init<>());\n    m.def(\"no_none1\", &none1, py::arg{}.none(false));\n    m.def(\"no_none2\", &none2, py::arg{}.none(false));\n    m.def(\"no_none3\", &none3, py::arg{}.none(false));\n    m.def(\"no_none4\", &none4, py::arg{}.none(false));\n    m.def(\"no_none5\", &none5, py::arg{}.none(false));\n    m.def(\"ok_none1\", &none1);\n    m.def(\"ok_none2\", &none2, py::arg{}.none(true));\n    m.def(\"ok_none3\", &none3);\n    m.def(\"ok_none4\", &none4, py::arg{}.none(true));\n    m.def(\"ok_none5\", &none5);\n\n    m.def(\"no_none_kwarg\", &none2, \"a\"_a.none(false));\n    m.def(\"no_none_kwarg_kw_only\", &none2, py::kw_only(), \"a\"_a.none(false));\n\n    // test_casts_none\n    // Issue #2778: implicit casting from None to object (not pointer)\n    py::class_<NoneCastTester>(m, \"NoneCastTester\")\n        .def(py::init<>())\n        .def(py::init<int>())\n        .def(py::init([](py::none const &) { return NoneCastTester{}; }));\n    py::implicitly_convertible<py::none, NoneCastTester>();\n    m.def(\"ok_obj_or_none\", [](NoneCastTester const &foo) { return foo.answer; });\n\n    // test_str_issue\n    // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid\n    py::class_<StrIssue>(m, \"StrIssue\")\n        .def(py::init<int>())\n        .def(py::init<>())\n        .def(\"__str__\",\n             [](const StrIssue &si) { return \"StrIssue[\" + std::to_string(si.val) + \"]\"; });\n\n    // test_unregistered_base_implementations\n    //\n    // Issues #854/910: incompatible function args when member function/pointer is in unregistered\n    // base class The methods and member pointers below actually resolve to members/pointers in\n    // UnregisteredBase; before this test/fix they would be registered via lambda with a first\n    // argument of an unregistered type, and thus uncallable.\n    py::class_<RegisteredDerived>(m, \"RegisteredDerived\")\n        .def(py::init<>())\n        .def(\"do_nothing\", &RegisteredDerived::do_nothing)\n        .def(\"increase_value\", &RegisteredDerived::increase_value)\n        .def_readwrite(\"rw_value\", &RegisteredDerived::rw_value)\n        .def_readonly(\"ro_value\", &RegisteredDerived::ro_value)\n        // Uncommenting the next line should trigger a static_assert:\n        // .def_readwrite(\"fails\", &UserType::value)\n        // Uncommenting the next line should trigger a static_assert:\n        // .def_readonly(\"fails\", &UserType::value)\n        .def_property(\"rw_value_prop\", &RegisteredDerived::get_int, &RegisteredDerived::set_int)\n        .def_property_readonly(\"ro_value_prop\", &RegisteredDerived::get_double)\n        // This one is in the registered class:\n        .def(\"sum\", &RegisteredDerived::sum);\n\n    using Adapted\n        = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing));\n    static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, \"\");\n\n    // test_methods_and_attributes\n    py::class_<RefQualified>(m, \"RefQualified\")\n        .def(py::init<>())\n        .def_readonly(\"value\", &RefQualified::value)\n        .def(\"refQualified\", &RefQualified::refQualified)\n        .def(\"constRefQualified\", &RefQualified::constRefQualified);\n\n    py::class_<RValueRefParam>(m, \"RValueRefParam\")\n        .def(py::init<>())\n        .def(\"func1\", &RValueRefParam::func1)\n        .def(\"func2\", &RValueRefParam::func2)\n        .def(\"func3\", &RValueRefParam::func3)\n        .def(\"func4\", &RValueRefParam::func4);\n\n    pybind11_tests::exercise_is_setter::add_bindings(m);\n}\n"
  },
  {
    "path": "tests/test_methods_and_attributes.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import methods_and_attributes as m\n\nNO_GETTER_MSG = (\n    \"unreadable attribute\" if sys.version_info < (3, 11) else \"object has no getter\"\n)\nNO_SETTER_MSG = (\n    \"can't set attribute\" if sys.version_info < (3, 11) else \"object has no setter\"\n)\nNO_DELETER_MSG = (\n    \"can't delete attribute\" if sys.version_info < (3, 11) else \"object has no deleter\"\n)\n\n\ndef test_self_only_pos_only():\n    assert (\n        m.ExampleMandA.__str__.__doc__\n        == \"__str__(self: pybind11_tests.methods_and_attributes.ExampleMandA, /) -> str\\n\"\n    )\n\n\ndef test_methods_and_attributes():\n    instance1 = m.ExampleMandA()\n    instance2 = m.ExampleMandA(32)\n\n    instance1.add1(instance2)\n    instance1.add2(instance2)\n    instance1.add3(instance2)\n    instance1.add4(instance2)\n    instance1.add5(instance2)\n    instance1.add6(32)\n    instance1.add7(32)\n    instance1.add8(32)\n    instance1.add9(32)\n    instance1.add10(32)\n\n    assert str(instance1) == \"ExampleMandA[value=320]\"\n    assert str(instance2) == \"ExampleMandA[value=32]\"\n    assert str(instance1.self1()) == \"ExampleMandA[value=320]\"\n    assert str(instance1.self2()) == \"ExampleMandA[value=320]\"\n    assert str(instance1.self3()) == \"ExampleMandA[value=320]\"\n    assert str(instance1.self4()) == \"ExampleMandA[value=320]\"\n    assert str(instance1.self5()) == \"ExampleMandA[value=320]\"\n\n    assert instance1.internal1() == 320\n    assert instance1.internal2() == 320\n    assert instance1.internal3() == 320\n    assert instance1.internal4() == 320\n    assert instance1.internal5() == 320\n\n    assert instance1.overloaded() == \"()\"\n    assert instance1.overloaded(0) == \"(int)\"\n    assert instance1.overloaded(1, 1.0) == \"(int, float)\"\n    assert instance1.overloaded(2.0, 2) == \"(float, int)\"\n    assert instance1.overloaded(3, 3) == \"(int, int)\"\n    assert instance1.overloaded(4.0, 4.0) == \"(float, float)\"\n    assert instance1.overloaded_const(-3) == \"(int) const\"\n    assert instance1.overloaded_const(5, 5.0) == \"(int, float) const\"\n    assert instance1.overloaded_const(6.0, 6) == \"(float, int) const\"\n    assert instance1.overloaded_const(7, 7) == \"(int, int) const\"\n    assert instance1.overloaded_const(8.0, 8.0) == \"(float, float) const\"\n    assert instance1.overloaded_float(1, 1) == \"(float, float)\"\n    assert instance1.overloaded_float(1, 1.0) == \"(float, float)\"\n    assert instance1.overloaded_float(1.0, 1) == \"(float, float)\"\n    assert instance1.overloaded_float(1.0, 1.0) == \"(float, float)\"\n\n    assert instance1.value == 320\n    instance1.value = 100\n    assert str(instance1) == \"ExampleMandA[value=100]\"\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    cstats = ConstructorStats.get(m.ExampleMandA)\n    assert cstats.alive() == 2\n    del instance1, instance2\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"32\"]\n    assert cstats.default_constructions == 1\n    assert cstats.copy_constructions == 2\n    assert cstats.move_constructions >= 2\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n\ndef test_copy_method():\n    \"\"\"Issue #443: calling copied methods fails in Python 3\"\"\"\n\n    m.ExampleMandA.add2c = m.ExampleMandA.add2\n    m.ExampleMandA.add2d = m.ExampleMandA.add2b\n    a = m.ExampleMandA(123)\n    assert a.value == 123\n    a.add2(m.ExampleMandA(-100))\n    assert a.value == 23\n    a.add2b(m.ExampleMandA(20))\n    assert a.value == 43\n    a.add2c(m.ExampleMandA(6))\n    assert a.value == 49\n    a.add2d(m.ExampleMandA(-7))\n    assert a.value == 42\n\n\ndef test_properties():\n    instance = m.TestProperties()\n\n    assert instance.def_readonly == 1\n    with pytest.raises(AttributeError):\n        instance.def_readonly = 2\n\n    instance.def_readwrite = 2\n    assert instance.def_readwrite == 2\n\n    assert instance.def_property_readonly == 2\n    with pytest.raises(AttributeError):\n        instance.def_property_readonly = 3\n\n    instance.def_property = 3\n    assert instance.def_property == 3\n\n    with pytest.raises(AttributeError) as excinfo:\n        dummy = instance.def_property_writeonly  # unused var\n    assert NO_GETTER_MSG in str(excinfo.value)\n\n    instance.def_property_writeonly = 4\n    assert instance.def_property_readonly == 4\n\n    with pytest.raises(AttributeError) as excinfo:\n        dummy = instance.def_property_impossible  # noqa: F841 unused var\n    assert NO_GETTER_MSG in str(excinfo.value)\n\n    with pytest.raises(AttributeError) as excinfo:\n        instance.def_property_impossible = 5\n    assert NO_SETTER_MSG in str(excinfo.value)\n\n\ndef test_static_properties():\n    assert m.TestProperties.def_readonly_static == 1\n    with pytest.raises(AttributeError) as excinfo:\n        m.TestProperties.def_readonly_static = 2\n    assert NO_SETTER_MSG in str(excinfo.value)\n\n    m.TestProperties.def_readwrite_static = 2\n    assert m.TestProperties.def_readwrite_static == 2\n\n    with pytest.raises(AttributeError) as excinfo:\n        dummy = m.TestProperties.def_writeonly_static  # unused var\n    assert NO_GETTER_MSG in str(excinfo.value)\n\n    m.TestProperties.def_writeonly_static = 3\n    assert m.TestProperties.def_readonly_static == 3\n\n    assert m.TestProperties.def_property_readonly_static == 3\n    with pytest.raises(AttributeError) as excinfo:\n        m.TestProperties.def_property_readonly_static = 99\n    assert NO_SETTER_MSG in str(excinfo.value)\n\n    m.TestProperties.def_property_static = 4\n    assert m.TestProperties.def_property_static == 4\n\n    with pytest.raises(AttributeError) as excinfo:\n        dummy = m.TestProperties.def_property_writeonly_static\n    assert NO_GETTER_MSG in str(excinfo.value)\n\n    m.TestProperties.def_property_writeonly_static = 5\n    assert m.TestProperties.def_property_static == 5\n\n    # Static property read and write via instance\n    instance = m.TestProperties()\n\n    m.TestProperties.def_readwrite_static = 0\n    assert m.TestProperties.def_readwrite_static == 0\n    assert instance.def_readwrite_static == 0\n\n    instance.def_readwrite_static = 2\n    assert m.TestProperties.def_readwrite_static == 2\n    assert instance.def_readwrite_static == 2\n\n    with pytest.raises(AttributeError) as excinfo:\n        dummy = instance.def_property_writeonly_static  # noqa: F841 unused var\n    assert NO_GETTER_MSG in str(excinfo.value)\n\n    instance.def_property_writeonly_static = 4\n    assert instance.def_property_static == 4\n\n    # It should be possible to override properties in derived classes\n    assert m.TestPropertiesOverride().def_readonly == 99\n    assert m.TestPropertiesOverride.def_readonly_static == 99\n\n    # Only static attributes can be deleted\n    del m.TestPropertiesOverride.def_readonly_static\n    assert hasattr(m.TestPropertiesOverride, \"def_readonly_static\")\n    assert (\n        m.TestPropertiesOverride.def_readonly_static\n        is m.TestProperties.def_readonly_static\n    )\n    assert \"def_readonly_static\" not in m.TestPropertiesOverride.__dict__\n    properties_override = m.TestPropertiesOverride()\n    with pytest.raises(AttributeError) as excinfo:\n        del properties_override.def_readonly\n    assert NO_DELETER_MSG in str(excinfo.value)\n\n\ndef test_static_cls():\n    \"\"\"Static property getter and setters expect the type object as the their only argument\"\"\"\n\n    instance = m.TestProperties()\n    assert m.TestProperties.static_cls is m.TestProperties\n    assert instance.static_cls is m.TestProperties\n\n    def check_self(self):\n        assert self is m.TestProperties\n\n    m.TestProperties.static_cls = check_self\n    instance.static_cls = check_self\n\n\ndef test_metaclass_override():\n    \"\"\"Overriding pybind11's default metaclass changes the behavior of `static_property`\"\"\"\n\n    assert type(m.ExampleMandA).__name__ == \"pybind11_type\"\n    assert type(m.MetaclassOverride).__name__ == \"type\"\n\n    assert m.MetaclassOverride.readonly == 1\n    assert (\n        type(m.MetaclassOverride.__dict__[\"readonly\"]).__name__\n        == \"pybind11_static_property\"\n    )\n\n    # Regular `type` replaces the property instead of calling `__set__()`\n    m.MetaclassOverride.readonly = 2\n    assert m.MetaclassOverride.readonly == 2\n    assert isinstance(m.MetaclassOverride.__dict__[\"readonly\"], int)\n\n\ndef test_no_mixed_overloads():\n    from pybind11_tests import detailed_error_messages_enabled\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.ExampleMandA.add_mixed_overloads1()\n    assert (\n        str(excinfo.value)\n        == \"overloading a method with both static and instance methods is not supported; \"\n        + (\n            \"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more details\"\n            if not detailed_error_messages_enabled\n            else \"error while attempting to bind static method ExampleMandA.overload_mixed1\"\n            \"(arg0: typing.SupportsFloat | typing.SupportsIndex) -> str\"\n        )\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.ExampleMandA.add_mixed_overloads2()\n    assert (\n        str(excinfo.value)\n        == \"overloading a method with both static and instance methods is not supported; \"\n        + (\n            \"#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more details\"\n            if not detailed_error_messages_enabled\n            else \"error while attempting to bind instance method ExampleMandA.overload_mixed2\"\n            \"(self: pybind11_tests.methods_and_attributes.ExampleMandA, arg0: typing.SupportsInt | typing.SupportsIndex, arg1: typing.SupportsInt | typing.SupportsIndex)\"\n            \" -> str\"\n        )\n    )\n\n\n@pytest.mark.parametrize(\"access\", [\"ro\", \"rw\", \"static_ro\", \"static_rw\"])\ndef test_property_return_value_policies(access):\n    obj = m.TestPropRVP() if not access.startswith(\"static\") else m.TestPropRVP\n\n    ref = getattr(obj, access + \"_ref\")\n    assert ref.value == 1\n    ref.value = 2\n    assert getattr(obj, access + \"_ref\").value == 2\n    ref.value = 1  # restore original value for static properties\n\n    copy = getattr(obj, access + \"_copy\")\n    assert copy.value == 1\n    copy.value = 2\n    assert getattr(obj, access + \"_copy\").value == 1\n\n    copy = getattr(obj, access + \"_func\")\n    assert copy.value == 1\n    copy.value = 2\n    assert getattr(obj, access + \"_func\").value == 1\n\n\ndef test_property_rvalue_policy():\n    \"\"\"When returning an rvalue, the return value policy is automatically changed from\n    `reference(_internal)` to `move`. The following would not work otherwise.\"\"\"\n\n    instance = m.TestPropRVP()\n    o = instance.rvalue\n    assert o.value == 1\n\n    os = m.TestPropRVP.static_rvalue\n    assert os.value == 1\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2447\n@pytest.mark.xfail(\"env.PYPY\")\n@pytest.mark.skipif(\n    sys.version_info in ((3, 14, 0, \"beta\", 1), (3, 14, 0, \"beta\", 2)),\n    reason=\"3.14.0b1/2 managed dict bug: https://github.com/python/cpython/issues/133912\",\n)\ndef test_dynamic_attributes():\n    instance = m.DynamicClass()\n    assert not hasattr(instance, \"foo\")\n    assert \"foo\" not in dir(instance)\n\n    # Dynamically add attribute\n    instance.foo = 42\n    assert hasattr(instance, \"foo\")\n    assert instance.foo == 42\n    assert \"foo\" in dir(instance)\n\n    # __dict__ should be accessible and replaceable\n    assert \"foo\" in instance.__dict__\n    instance.__dict__ = {\"bar\": True}\n    assert not hasattr(instance, \"foo\")\n    assert hasattr(instance, \"bar\")\n\n    with pytest.raises(TypeError) as excinfo:\n        instance.__dict__ = []\n    assert str(excinfo.value) == \"__dict__ must be set to a dictionary, not a 'list'\"\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n    cstats = ConstructorStats.get(m.DynamicClass)\n    assert cstats.alive() == 1\n    del instance\n    pytest.gc_collect()\n    assert cstats.alive() == 0\n\n    # Derived classes should work as well\n    class PythonDerivedDynamicClass(m.DynamicClass):\n        pass\n\n    for cls in (m.CppDerivedDynamicClass, PythonDerivedDynamicClass):\n        derived = cls()\n        derived.foobar = 100\n        assert derived.foobar == 100\n\n        assert cstats.alive() == 1\n        del derived\n        pytest.gc_collect()\n        assert cstats.alive() == 0\n\n\n# https://foss.heptapod.net/pypy/pypy/-/issues/2447\n@pytest.mark.xfail(\"env.PYPY\")\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\n@pytest.mark.skipif(\n    sys.version_info in ((3, 14, 0, \"beta\", 1), (3, 14, 0, \"beta\", 2)),\n    reason=\"3.14.0b1/2 managed dict bug: https://github.com/python/cpython/issues/133912\",\n)\ndef test_cyclic_gc():\n    # One object references itself\n    instance = m.DynamicClass()\n    instance.circular_reference = instance\n\n    cstats = ConstructorStats.get(m.DynamicClass)\n    assert cstats.alive() == 1\n    del instance\n    pytest.gc_collect()\n    assert cstats.alive() == 0\n\n    # Two object reference each other\n    i1 = m.DynamicClass()\n    i2 = m.DynamicClass()\n    i1.cycle = i2\n    i2.cycle = i1\n\n    assert cstats.alive() == 2\n    del i1, i2\n    pytest.gc_collect()\n    assert cstats.alive() == 0\n\n\ndef test_bad_arg_default(msg):\n    from pybind11_tests import detailed_error_messages_enabled\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.bad_arg_def_named()\n    assert msg(excinfo.value) == (\n        \"arg(): could not convert default argument 'a: UnregisteredType' in function \"\n        \"'should_fail' into a Python object (type not registered yet?)\"\n        if detailed_error_messages_enabled\n        else \"arg(): could not convert default argument into a Python object (type not registered \"\n        \"yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information.\"\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.bad_arg_def_unnamed()\n    assert msg(excinfo.value) == (\n        \"arg(): could not convert default argument 'UnregisteredType' in function \"\n        \"'should_fail' into a Python object (type not registered yet?)\"\n        if detailed_error_messages_enabled\n        else \"arg(): could not convert default argument into a Python object (type not registered \"\n        \"yet?). #define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more information.\"\n    )\n\n\ndef test_accepts_none(msg):\n    a = m.NoneTester()\n    assert m.no_none1(a) == 42\n    assert m.no_none2(a) == 42\n    assert m.no_none3(a) == 42\n    assert m.no_none4(a) == 42\n    assert m.no_none5(a) == 42\n    assert m.ok_none1(a) == 42\n    assert m.ok_none2(a) == 42\n    assert m.ok_none3(a) == 42\n    assert m.ok_none4(a) == 42\n    assert m.ok_none5(a) == 42\n\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none1(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none2(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none3(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none4(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none5(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    # The first one still raises because you can't pass None as a lvalue reference arg:\n    with pytest.raises(TypeError) as excinfo:\n        assert m.ok_none1(None) == -1\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        ok_none1(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: m.methods_and_attributes.NoneTester) -> int\n\n        Invoked with: None\n    \"\"\"\n    )\n\n    # The rest take the argument as pointer or holder, and accept None:\n    assert m.ok_none2(None) == -1\n    assert m.ok_none3(None) == -1\n    assert m.ok_none4(None) == -1\n    assert m.ok_none5(None) == -1\n\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none_kwarg(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none_kwarg(a=None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none_kwarg_kw_only(None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    with pytest.raises(TypeError) as excinfo:\n        m.no_none_kwarg_kw_only(a=None)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n\ndef test_casts_none():\n    \"\"\"#2778: implicit casting from None to object (not pointer)\"\"\"\n    a = m.NoneCastTester()\n    assert m.ok_obj_or_none(a) == -1\n    a = m.NoneCastTester(4)\n    assert m.ok_obj_or_none(a) == 4\n    a = m.NoneCastTester(None)\n    assert m.ok_obj_or_none(a) == -1\n    assert m.ok_obj_or_none(None) == -1\n\n\ndef test_str_issue(msg):\n    \"\"\"#283: __str__ called on uninitialized instance when constructor arguments invalid\"\"\"\n\n    assert str(m.StrIssue(3)) == \"StrIssue[3]\"\n\n    with pytest.raises(TypeError) as excinfo:\n        str(m.StrIssue(\"no\", \"such\", \"constructor\"))\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        __init__(): incompatible constructor arguments. The following argument types are supported:\n            1. m.methods_and_attributes.StrIssue(arg0: typing.SupportsInt | typing.SupportsIndex)\n            2. m.methods_and_attributes.StrIssue()\n\n        Invoked with: 'no', 'such', 'constructor'\n    \"\"\"\n    )\n\n\ndef test_unregistered_base_implementations():\n    a = m.RegisteredDerived()\n    a.do_nothing()\n    assert a.rw_value == 42\n    assert a.ro_value == 1.25\n    a.rw_value += 5\n    assert a.sum() == 48.25\n    a.increase_value()\n    assert a.rw_value == 48\n    assert a.ro_value == 1.5\n    assert a.sum() == 49.5\n    assert a.rw_value_prop == 48\n    a.rw_value_prop += 1\n    assert a.rw_value_prop == 49\n    a.increase_value()\n    assert a.ro_value_prop == 1.75\n\n\ndef test_ref_qualified():\n    \"\"\"Tests that explicit lvalue ref-qualified methods can be called just like their\n    non ref-qualified counterparts.\"\"\"\n\n    r = m.RefQualified()\n    assert r.value == 0\n    r.refQualified(17)\n    assert r.value == 17\n    assert r.constRefQualified(23) == 40\n\n\ndef test_overload_ordering():\n    \"Check to see if the normal overload order (first defined) and prepend overload order works\"\n    assert m.overload_order(\"string\") == 1\n    assert m.overload_order(0) == 4\n\n    assert (\n        \"1. overload_order(arg0: typing.SupportsInt | typing.SupportsIndex) -> int\"\n        in m.overload_order.__doc__\n    )\n    assert \"2. overload_order(arg0: str) -> int\" in m.overload_order.__doc__\n    assert \"3. overload_order(arg0: str) -> int\" in m.overload_order.__doc__\n    assert (\n        \"4. overload_order(arg0: typing.SupportsInt | typing.SupportsIndex) -> int\"\n        in m.overload_order.__doc__\n    )\n\n    with pytest.raises(TypeError) as err:\n        m.overload_order(1.1)\n\n    assert \"1. (arg0: typing.SupportsInt | typing.SupportsIndex) -> int\" in str(\n        err.value\n    )\n    assert \"2. (arg0: str) -> int\" in str(err.value)\n    assert \"3. (arg0: str) -> int\" in str(err.value)\n    assert \"4. (arg0: typing.SupportsInt | typing.SupportsIndex) -> int\" in str(\n        err.value\n    )\n\n\ndef test_rvalue_ref_param():\n    r = m.RValueRefParam()\n    assert r.func1(\"123\") == 3\n    assert r.func2(\"1234\") == 4\n    assert r.func3(\"12345\") == 5\n    assert r.func4(\"123456\") == 6\n\n\ndef test_is_setter():\n    fld = m.exercise_is_setter.Field()\n    assert fld.int_value == -99\n    setter_return = fld.int_value = 100\n    assert isinstance(setter_return, int)\n    assert setter_return == 100\n    assert fld.int_value == 100\n"
  },
  {
    "path": "tests/test_modules.cpp",
    "content": "/*\n    tests/test_modules.cpp -- nested modules, importing modules, and\n                            internal references\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(modules, m) {\n    // test_nested_modules\n    // This is intentionally \"py::module\" to verify it still can be used in place of \"py::module_\"\n    py::module m_sub = m.def_submodule(\"subsubmodule\");\n    m_sub.def(\"submodule_func\", []() { return \"submodule_func()\"; });\n\n    // test_reference_internal\n    class A {\n    public:\n        explicit A(int v) : v(v) { print_created(this, v); }\n        ~A() { print_destroyed(this); }\n        A(const A &) { print_copy_created(this); }\n        A &operator=(const A &copy) {\n            print_copy_assigned(this);\n            v = copy.v;\n            return *this;\n        }\n        std::string toString() const { return \"A[\" + std::to_string(v) + \"]\"; }\n\n    private:\n        int v;\n    };\n    py::class_<A>(m_sub, \"A\").def(py::init<int>()).def(\"__repr__\", &A::toString);\n\n    class B {\n    public:\n        B() { print_default_created(this); }\n        ~B() { print_destroyed(this); }\n        B(const B &) { print_copy_created(this); }\n        B &operator=(const B &copy) {\n            print_copy_assigned(this);\n            a1 = copy.a1;\n            a2 = copy.a2;\n            return *this;\n        }\n        A &get_a1() { return a1; }\n        A &get_a2() { return a2; }\n\n        A a1{1};\n        A a2{2};\n    };\n    py::class_<B>(m_sub, \"B\")\n        .def(py::init<>())\n        .def(\"get_a1\",\n             &B::get_a1,\n             \"Return the internal A 1\",\n             py::return_value_policy::reference_internal)\n        .def(\"get_a2\",\n             &B::get_a2,\n             \"Return the internal A 2\",\n             py::return_value_policy::reference_internal)\n        .def_readwrite(\"a1\", &B::a1) // def_readonly uses an internal\n                                     // reference return policy by default\n        .def_readwrite(\"a2\", &B::a2);\n\n    // This is intentionally \"py::module\" to verify it still can be used in place of \"py::module_\"\n    m.attr(\"OD\") = py::module::import(\"collections\").attr(\"OrderedDict\");\n\n    // test_duplicate_registration\n    // Registering two things with the same name\n    m.def(\"duplicate_registration\", []() {\n        class Dupe1 {};\n        class Dupe2 {};\n        class Dupe3 {};\n        class DupeException {};\n\n        // Go ahead and leak, until we have a non-leaking py::module_ constructor\n        auto dm = py::module_::create_extension_module(\"dummy\", nullptr, new PyModuleDef);\n        auto failures = py::list();\n\n        py::class_<Dupe1>(dm, \"Dupe1\");\n        py::class_<Dupe2>(dm, \"Dupe2\");\n        dm.def(\"dupe1_factory\", []() { return Dupe1(); });\n        py::exception<DupeException>(dm, \"DupeException\");\n\n        try {\n            py::class_<Dupe1>(dm, \"Dupe1\");\n            failures.append(\"Dupe1 class\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n        try {\n            dm.def(\"Dupe1\", []() { return Dupe1(); });\n            failures.append(\"Dupe1 function\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n        try {\n            py::class_<Dupe3>(dm, \"dupe1_factory\");\n            failures.append(\"dupe1_factory\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n        try {\n            py::exception<Dupe3>(dm, \"Dupe2\");\n            failures.append(\"Dupe2\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n        try {\n            dm.def(\"DupeException\", []() { return 30; });\n            failures.append(\"DupeException1\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n        try {\n            py::class_<DupeException>(dm, \"DupeException\");\n            failures.append(\"DupeException2\");\n        } catch (std::runtime_error &) { // NOLINT(bugprone-empty-catch)\n        }\n\n        return failures;\n    });\n\n    m.def(\"def_submodule\", [](py::module_ m, const char *name) { return m.def_submodule(name); });\n}\n"
  },
  {
    "path": "tests/test_modules.py",
    "content": "from __future__ import annotations\n\nimport builtins\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import modules as m\nfrom pybind11_tests.modules import subsubmodule as ms\n\n\ndef test_nested_modules():\n    import pybind11_tests\n\n    assert pybind11_tests.__name__ == \"pybind11_tests\"\n    assert pybind11_tests.modules.__name__ == \"pybind11_tests.modules\"\n    assert (\n        pybind11_tests.modules.subsubmodule.__name__\n        == \"pybind11_tests.modules.subsubmodule\"\n    )\n    assert m.__name__ == \"pybind11_tests.modules\"\n    assert ms.__name__ == \"pybind11_tests.modules.subsubmodule\"\n    assert m.__file__ == ms.__file__\n\n    assert ms.submodule_func() == \"submodule_func()\"\n\n\ndef test_reference_internal():\n    b = ms.B()\n    assert str(b.get_a1()) == \"A[1]\"\n    assert str(b.a1) == \"A[1]\"\n    assert str(b.get_a2()) == \"A[2]\"\n    assert str(b.a2) == \"A[2]\"\n\n    b.a1 = ms.A(42)\n    b.a2 = ms.A(43)\n    assert str(b.get_a1()) == \"A[42]\"\n    assert str(b.a1) == \"A[42]\"\n    assert str(b.get_a2()) == \"A[43]\"\n    assert str(b.a2) == \"A[43]\"\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    astats, bstats = ConstructorStats.get(ms.A), ConstructorStats.get(ms.B)\n    assert astats.alive() == 2\n    assert bstats.alive() == 1\n    del b\n    assert astats.alive() == 0\n    assert bstats.alive() == 0\n    assert astats.values() == [\"1\", \"2\", \"42\", \"43\"]\n    assert bstats.values() == []\n    assert astats.default_constructions == 0\n    assert bstats.default_constructions == 1\n    assert astats.copy_constructions == 0\n    assert bstats.copy_constructions == 0\n    # assert astats.move_constructions >= 0  # Don't invoke any\n    # assert bstats.move_constructions >= 0  # Don't invoke any\n    assert astats.copy_assignments == 2\n    assert bstats.copy_assignments == 0\n    assert astats.move_assignments == 0\n    assert bstats.move_assignments == 0\n\n\ndef test_importing():\n    from collections import OrderedDict\n\n    from pybind11_tests.modules import OD\n\n    assert OD is OrderedDict\n\n\ndef test_reimport():\n    import sys\n\n    import pybind11_tests as x\n\n    del sys.modules[\"pybind11_tests\"]\n\n    # exercise pybind11::detail::get_cached_module()\n    import pybind11_tests as y\n\n    assert x is y\n\n\n@pytest.mark.xfail(\n    \"env.GRAALPY\",\n    reason=\"TODO should be fixed on GraalPy side (failure was introduced by pr #5782)\",\n)\ndef test_pydoc():\n    \"\"\"Pydoc needs to be able to provide help() for everything inside a pybind11 module\"\"\"\n    import pydoc\n\n    import pybind11_tests\n\n    assert pybind11_tests.__name__ == \"pybind11_tests\"\n    assert pybind11_tests.__doc__ == \"pybind11 test module\"\n    assert pydoc.text.docmodule(pybind11_tests)\n\n\ndef test_module_handle_type_name():\n    assert (\n        m.def_submodule.__doc__\n        == \"def_submodule(arg0: types.ModuleType, arg1: str) -> types.ModuleType\\n\"\n    )\n\n\ndef test_duplicate_registration():\n    \"\"\"Registering two things with the same name\"\"\"\n\n    assert m.duplicate_registration() == []\n\n\ndef test_builtin_key_type():\n    \"\"\"Test that all the keys in the builtin modules have type str.\n\n    Previous versions of pybind11 would add a unicode key in python 2.\n    \"\"\"\n    assert all(type(k) == str for k in dir(builtins))\n\n\n@pytest.mark.xfail(\"env.PYPY\", reason=\"PyModule_GetName()\")\ndef test_def_submodule_failures():\n    sm = m.def_submodule(m, b\"ScratchSubModuleName\")  # Using bytes to show it works.\n    assert sm.__name__ == m.__name__ + \".\" + \"ScratchSubModuleName\"\n    malformed_utf8 = b\"\\x80\"\n    if env.PYPY or env.GRAALPY:\n        # It is not worth the effort finding a trigger for a failure when running with PyPy.\n        pytest.skip(\"Sufficiently exercised on platforms other than PyPy/GraalPy.\")\n    else:\n        # Meant to trigger PyModule_GetName() failure:\n        sm_name_orig = sm.__name__\n        sm.__name__ = malformed_utf8\n        try:\n            # We want to assert that a bad __name__ causes some kind of failure, although we do not want to exercise\n            # the internals of PyModule_GetName(). Currently all supported Python versions raise SystemError. If that\n            # changes in future Python versions, simply add the new expected exception types here.\n            with pytest.raises(SystemError):\n                m.def_submodule(sm, b\"SubSubModuleName\")\n        finally:\n            # Clean up to ensure nothing gets upset by a module with an invalid __name__.\n            sm.__name__ = sm_name_orig  # Purely precautionary.\n    # Meant to trigger PyImport_AddModule() failure:\n    with pytest.raises(UnicodeDecodeError):\n        m.def_submodule(sm, malformed_utf8)\n"
  },
  {
    "path": "tests/test_multiple_inheritance.cpp",
    "content": "/*\n    tests/test_multiple_inheritance.cpp -- multiple inheritance,\n    implicit MI casts\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\nnamespace {\n\n// Many bases for testing that multiple inheritance from many classes (i.e. requiring extra\n// space for holder constructed flags) works.\ntemplate <int N>\nstruct BaseN {\n    explicit BaseN(int i) : i(i) {}\n    int i;\n};\n\n// test_mi_static_properties\nstruct Vanilla {\n    std::string vanilla() { return \"Vanilla\"; };\n};\nstruct WithStatic1 {\n    static std::string static_func1() { return \"WithStatic1\"; };\n    static int static_value1;\n};\nstruct WithStatic2 {\n    static std::string static_func2() { return \"WithStatic2\"; };\n    static int static_value2;\n};\nstruct VanillaStaticMix1 : Vanilla, WithStatic1, WithStatic2 {\n    static std::string static_func() { return \"VanillaStaticMix1\"; }\n    static int static_value;\n};\nstruct VanillaStaticMix2 : WithStatic1, Vanilla, WithStatic2 {\n    static std::string static_func() { return \"VanillaStaticMix2\"; }\n    static int static_value;\n};\nint WithStatic1::static_value1 = 1;\nint WithStatic2::static_value2 = 2;\nint VanillaStaticMix1::static_value = 12;\nint VanillaStaticMix2::static_value = 12;\n\n// test_multiple_inheritance_virtbase\nstruct Base1a {\n    explicit Base1a(int i) : i(i) {}\n    int foo() const { return i; }\n    int i;\n};\nstruct Base2a {\n    explicit Base2a(int i) : i(i) {}\n    int bar() const { return i; }\n    int i;\n};\nstruct Base12a : Base1a, Base2a {\n    Base12a(int i, int j) : Base1a(i), Base2a(j) {}\n};\n\n// test_mi_unaligned_base\n// test_mi_base_return\nstruct I801B1 {\n    int a = 1;\n    I801B1() = default;\n    I801B1(const I801B1 &) = default;\n    virtual ~I801B1() = default;\n};\nstruct I801B2 {\n    int b = 2;\n    I801B2() = default;\n    I801B2(const I801B2 &) = default;\n    virtual ~I801B2() = default;\n};\nstruct I801C : I801B1, I801B2 {};\nstruct I801D : I801C {}; // Indirect MI\n\n} // namespace\n\nTEST_SUBMODULE(multiple_inheritance, m) {\n    // Please do not interleave `struct` and `class` definitions with bindings code,\n    // but implement `struct`s and `class`es in the anonymous namespace above.\n    // This helps keeping the smart_holder branch in sync with master.\n\n    // test_multiple_inheritance_mix1\n    // test_multiple_inheritance_mix2\n    struct Base1 {\n        explicit Base1(int i) : i(i) {}\n        int foo() const { return i; }\n        int i;\n    };\n    py::class_<Base1> b1(m, \"Base1\");\n    b1.def(py::init<int>()).def(\"foo\", &Base1::foo);\n\n    struct Base2 {\n        explicit Base2(int i) : i(i) {}\n        int bar() const { return i; }\n        int i;\n    };\n    py::class_<Base2> b2(m, \"Base2\");\n    b2.def(py::init<int>()).def(\"bar\", &Base2::bar);\n\n    // test_multiple_inheritance_cpp\n    struct Base12 : Base1, Base2 {\n        Base12(int i, int j) : Base1(i), Base2(j) {}\n    };\n    struct MIType : Base12 {\n        MIType(int i, int j) : Base12(i, j) {}\n    };\n    py::class_<Base12, Base1, Base2>(m, \"Base12\");\n    py::class_<MIType, Base12>(m, \"MIType\").def(py::init<int, int>());\n\n    // test_multiple_inheritance_python_many_bases\n#define PYBIND11_BASEN(N)                                                                         \\\n    py::class_<BaseN<(N)>>(m, \"BaseN\" #N).def(py::init<int>()).def(\"f\" #N, [](BaseN<N> &b) {      \\\n        return b.i + (N);                                                                         \\\n    })\n    PYBIND11_BASEN(1);\n    PYBIND11_BASEN(2);\n    PYBIND11_BASEN(3);\n    PYBIND11_BASEN(4);\n    PYBIND11_BASEN(5);\n    PYBIND11_BASEN(6);\n    PYBIND11_BASEN(7);\n    PYBIND11_BASEN(8);\n    PYBIND11_BASEN(9);\n    PYBIND11_BASEN(10);\n    PYBIND11_BASEN(11);\n    PYBIND11_BASEN(12);\n    PYBIND11_BASEN(13);\n    PYBIND11_BASEN(14);\n    PYBIND11_BASEN(15);\n    PYBIND11_BASEN(16);\n    PYBIND11_BASEN(17);\n\n    // Uncommenting this should result in a compile time failure (MI can only be specified via\n    // template parameters because pybind has to know the types involved; see discussion in #742\n    // for details).\n    //    struct Base12v2 : Base1, Base2 {\n    //        Base12v2(int i, int j) : Base1(i), Base2(j) { }\n    //    };\n    //    py::class_<Base12v2>(m, \"Base12v2\", b1, b2)\n    //        .def(py::init<int, int>());\n\n    // test_multiple_inheritance_virtbase\n    // Test the case where not all base classes are specified, and where pybind11 requires the\n    // py::multiple_inheritance flag to perform proper casting between types.\n    py::class_<Base1a, std::shared_ptr<Base1a>>(m, \"Base1a\")\n        .def(py::init<int>())\n        .def(\"foo\", &Base1a::foo);\n\n    py::class_<Base2a, std::shared_ptr<Base2a>>(m, \"Base2a\")\n        .def(py::init<int>())\n        .def(\"bar\", &Base2a::bar);\n\n    py::class_<Base12a, /* Base1 missing */ Base2a, std::shared_ptr<Base12a>>(\n        m, \"Base12a\", py::multiple_inheritance())\n        .def(py::init<int, int>());\n\n    m.def(\"bar_base2a\", [](Base2a *b) { return b->bar(); });\n    m.def(\"bar_base2a_sharedptr\", [](const std::shared_ptr<Base2a> &b) { return b->bar(); });\n\n    // test_mi_unaligned_base\n    // test_mi_base_return\n    // Issue #801: invalid casting to derived type with MI bases\n    // Unregistered classes:\n    struct I801B3 {\n        int c = 3;\n        virtual ~I801B3() = default;\n    };\n    struct I801E : I801B3, I801D {};\n\n    py::class_<I801B1, std::shared_ptr<I801B1>>(m, \"I801B1\")\n        .def(py::init<>())\n        .def_readonly(\"a\", &I801B1::a);\n    py::class_<I801B2, std::shared_ptr<I801B2>>(m, \"I801B2\")\n        .def(py::init<>())\n        .def_readonly(\"b\", &I801B2::b);\n    py::class_<I801C, I801B1, I801B2, std::shared_ptr<I801C>>(m, \"I801C\").def(py::init<>());\n    py::class_<I801D, I801C, std::shared_ptr<I801D>>(m, \"I801D\").def(py::init<>());\n\n    // Two separate issues here: first, we want to recognize a pointer to a base type as being a\n    // known instance even when the pointer value is unequal (i.e. due to a non-first\n    // multiple-inheritance base class):\n    m.def(\"i801b1_c\", [](I801C *c) { return static_cast<I801B1 *>(c); });\n    m.def(\"i801b2_c\", [](I801C *c) { return static_cast<I801B2 *>(c); });\n    m.def(\"i801b1_d\", [](I801D *d) { return static_cast<I801B1 *>(d); });\n    m.def(\"i801b2_d\", [](I801D *d) { return static_cast<I801B2 *>(d); });\n\n    // Second, when returned a base class pointer to a derived instance, we cannot assume that the\n    // pointer is `reinterpret_cast`able to the derived pointer because, like above, the base class\n    // pointer could be offset.\n    m.def(\"i801c_b1\", []() -> I801B1 * { return new I801C(); });\n    m.def(\"i801c_b2\", []() -> I801B2 * { return new I801C(); });\n    m.def(\"i801d_b1\", []() -> I801B1 * { return new I801D(); });\n    m.def(\"i801d_b2\", []() -> I801B2 * { return new I801D(); });\n\n    // Return a base class pointer to a pybind-registered type when the actual derived type\n    // isn't pybind-registered (and uses multiple-inheritance to offset the pybind base)\n    m.def(\"i801e_c\", []() -> I801C * { return new I801E(); });\n    m.def(\"i801e_b2\", []() -> I801B2 * { return new I801E(); });\n\n    // test_mi_static_properties\n    py::class_<Vanilla>(m, \"Vanilla\").def(py::init<>()).def(\"vanilla\", &Vanilla::vanilla);\n\n    py::class_<WithStatic1>(m, \"WithStatic1\")\n        .def(py::init<>())\n        .def_static(\"static_func1\", &WithStatic1::static_func1)\n        .def_readwrite_static(\"static_value1\", &WithStatic1::static_value1);\n\n    py::class_<WithStatic2>(m, \"WithStatic2\")\n        .def(py::init<>())\n        .def_static(\"static_func2\", &WithStatic2::static_func2)\n        .def_readwrite_static(\"static_value2\", &WithStatic2::static_value2);\n\n    py::class_<VanillaStaticMix1, Vanilla, WithStatic1, WithStatic2>(m, \"VanillaStaticMix1\")\n        .def(py::init<>())\n        .def_static(\"static_func\", &VanillaStaticMix1::static_func)\n        .def_readwrite_static(\"static_value\", &VanillaStaticMix1::static_value);\n\n    py::class_<VanillaStaticMix2, WithStatic1, Vanilla, WithStatic2>(m, \"VanillaStaticMix2\")\n        .def(py::init<>())\n        .def_static(\"static_func\", &VanillaStaticMix2::static_func)\n        .def_readwrite_static(\"static_value\", &VanillaStaticMix2::static_value);\n\n    struct WithDict {};\n    struct VanillaDictMix1 : Vanilla, WithDict {};\n    struct VanillaDictMix2 : WithDict, Vanilla {};\n    py::class_<WithDict>(m, \"WithDict\", py::dynamic_attr()).def(py::init<>());\n    py::class_<VanillaDictMix1, Vanilla, WithDict>(m, \"VanillaDictMix1\").def(py::init<>());\n    py::class_<VanillaDictMix2, WithDict, Vanilla>(m, \"VanillaDictMix2\").def(py::init<>());\n\n    // test_diamond_inheritance\n    // Issue #959: segfault when constructing diamond inheritance instance\n    // All of these have int members so that there will be various unequal pointers involved.\n    struct B {\n        int b;\n        B() = default;\n        B(const B &) = default;\n        virtual ~B() = default;\n    };\n    struct C0 : public virtual B {\n        int c0;\n    };\n    struct C1 : public virtual B {\n        int c1;\n    };\n    struct D : public C0, public C1 {\n        int d;\n    };\n    py::class_<B>(m, \"B\").def(\"b\", [](B *self) { return self; });\n    py::class_<C0, B>(m, \"C0\").def(\"c0\", [](C0 *self) { return self; });\n    py::class_<C1, B>(m, \"C1\").def(\"c1\", [](C1 *self) { return self; });\n    py::class_<D, C0, C1>(m, \"D\").def(py::init<>());\n\n    // test_pr3635_diamond_*\n    // - functions are get_{base}_{var}, return {var}\n    struct MVB {\n        MVB() = default;\n        MVB(const MVB &) = default;\n        virtual ~MVB() = default;\n\n        int b = 1;\n        int get_b_b() const { return b; }\n    };\n    struct MVC : virtual MVB {\n        int c = 2;\n        int get_c_b() const { return b; }\n        int get_c_c() const { return c; }\n    };\n    struct MVD0 : virtual MVC {\n        int d0 = 3;\n        int get_d0_b() const { return b; }\n        int get_d0_c() const { return c; }\n        int get_d0_d0() const { return d0; }\n    };\n    struct MVD1 : virtual MVC {\n        int d1 = 4;\n        int get_d1_b() const { return b; }\n        int get_d1_c() const { return c; }\n        int get_d1_d1() const { return d1; }\n    };\n    struct MVE : virtual MVD0, virtual MVD1 {\n        int e = 5;\n        int get_e_b() const { return b; }\n        int get_e_c() const { return c; }\n        int get_e_d0() const { return d0; }\n        int get_e_d1() const { return d1; }\n        int get_e_e() const { return e; }\n    };\n    struct MVF : virtual MVE {\n        int f = 6;\n        int get_f_b() const { return b; }\n        int get_f_c() const { return c; }\n        int get_f_d0() const { return d0; }\n        int get_f_d1() const { return d1; }\n        int get_f_e() const { return e; }\n        int get_f_f() const { return f; }\n    };\n    py::class_<MVB>(m, \"MVB\")\n        .def(py::init<>())\n        .def(\"get_b_b\", &MVB::get_b_b)\n        .def_readwrite(\"b\", &MVB::b);\n    py::class_<MVC, MVB>(m, \"MVC\")\n        .def(py::init<>())\n        .def(\"get_c_b\", &MVC::get_c_b)\n        .def(\"get_c_c\", &MVC::get_c_c)\n        .def_readwrite(\"c\", &MVC::c);\n    py::class_<MVD0, MVC>(m, \"MVD0\")\n        .def(py::init<>())\n        .def(\"get_d0_b\", &MVD0::get_d0_b)\n        .def(\"get_d0_c\", &MVD0::get_d0_c)\n        .def(\"get_d0_d0\", &MVD0::get_d0_d0)\n        .def_readwrite(\"d0\", &MVD0::d0);\n    py::class_<MVD1, MVC>(m, \"MVD1\")\n        .def(py::init<>())\n        .def(\"get_d1_b\", &MVD1::get_d1_b)\n        .def(\"get_d1_c\", &MVD1::get_d1_c)\n        .def(\"get_d1_d1\", &MVD1::get_d1_d1)\n        .def_readwrite(\"d1\", &MVD1::d1);\n    py::class_<MVE, MVD0, MVD1>(m, \"MVE\")\n        .def(py::init<>())\n        .def(\"get_e_b\", &MVE::get_e_b)\n        .def(\"get_e_c\", &MVE::get_e_c)\n        .def(\"get_e_d0\", &MVE::get_e_d0)\n        .def(\"get_e_d1\", &MVE::get_e_d1)\n        .def(\"get_e_e\", &MVE::get_e_e)\n        .def_readwrite(\"e\", &MVE::e);\n    py::class_<MVF, MVE>(m, \"MVF\")\n        .def(py::init<>())\n        .def(\"get_f_b\", &MVF::get_f_b)\n        .def(\"get_f_c\", &MVF::get_f_c)\n        .def(\"get_f_d0\", &MVF::get_f_d0)\n        .def(\"get_f_d1\", &MVF::get_f_d1)\n        .def(\"get_f_e\", &MVF::get_f_e)\n        .def(\"get_f_f\", &MVF::get_f_f)\n        .def_readwrite(\"f\", &MVF::f);\n}\n"
  },
  {
    "path": "tests/test_multiple_inheritance.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import multiple_inheritance as m\n\n\ndef test_multiple_inheritance_cpp():\n    mt = m.MIType(3, 4)\n\n    assert mt.foo() == 3\n    assert mt.bar() == 4\n\n\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_multiple_inheritance_mix1():\n    class Base1:\n        def __init__(self, i):\n            self.i = i\n\n        def foo(self):\n            return self.i\n\n    class MITypePy(Base1, m.Base2):\n        def __init__(self, i, j):\n            Base1.__init__(self, i)\n            m.Base2.__init__(self, j)\n\n    mt = MITypePy(3, 4)\n\n    assert mt.foo() == 3\n    assert mt.bar() == 4\n\n\ndef test_multiple_inheritance_mix2():\n    class Base2:\n        def __init__(self, i):\n            self.i = i\n\n        def bar(self):\n            return self.i\n\n    class MITypePy(m.Base1, Base2):\n        def __init__(self, i, j):\n            m.Base1.__init__(self, i)\n            Base2.__init__(self, j)\n\n    mt = MITypePy(3, 4)\n\n    assert mt.foo() == 3\n    assert mt.bar() == 4\n\n\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_multiple_inheritance_python():\n    class MI1(m.Base1, m.Base2):\n        def __init__(self, i, j):\n            m.Base1.__init__(self, i)\n            m.Base2.__init__(self, j)\n\n    class B1:\n        def v(self):\n            return 1\n\n    class MI2(B1, m.Base1, m.Base2):\n        def __init__(self, i, j):\n            B1.__init__(self)\n            m.Base1.__init__(self, i)\n            m.Base2.__init__(self, j)\n\n    class MI3(MI2):\n        def __init__(self, i, j):\n            MI2.__init__(self, i, j)\n\n    class MI4(MI3, m.Base2):\n        def __init__(self, i, j):\n            MI3.__init__(self, i, j)\n            # This should be ignored (Base2 is already initialized via MI2):\n            m.Base2.__init__(self, i + 100)\n\n    class MI5(m.Base2, B1, m.Base1):\n        def __init__(self, i, j):\n            B1.__init__(self)\n            m.Base1.__init__(self, i)\n            m.Base2.__init__(self, j)\n\n    class MI6(m.Base2, B1):\n        def __init__(self, i):\n            m.Base2.__init__(self, i)\n            B1.__init__(self)\n\n    class B2(B1):\n        def v(self):\n            return 2\n\n    class B3:\n        def v(self):\n            return 3\n\n    class B4(B3, B2):\n        def v(self):\n            return 4\n\n    class MI7(B4, MI6):\n        def __init__(self, i):\n            B4.__init__(self)\n            MI6.__init__(self, i)\n\n    class MI8(MI6, B3):\n        def __init__(self, i):\n            MI6.__init__(self, i)\n            B3.__init__(self)\n\n    class MI8b(B3, MI6):\n        def __init__(self, i):\n            B3.__init__(self)\n            MI6.__init__(self, i)\n\n    mi1 = MI1(1, 2)\n    assert mi1.foo() == 1\n    assert mi1.bar() == 2\n\n    mi2 = MI2(3, 4)\n    assert mi2.v() == 1\n    assert mi2.foo() == 3\n    assert mi2.bar() == 4\n\n    mi3 = MI3(5, 6)\n    assert mi3.v() == 1\n    assert mi3.foo() == 5\n    assert mi3.bar() == 6\n\n    mi4 = MI4(7, 8)\n    assert mi4.v() == 1\n    assert mi4.foo() == 7\n    assert mi4.bar() == 8\n\n    mi5 = MI5(10, 11)\n    assert mi5.v() == 1\n    assert mi5.foo() == 10\n    assert mi5.bar() == 11\n\n    mi6 = MI6(12)\n    assert mi6.v() == 1\n    assert mi6.bar() == 12\n\n    mi7 = MI7(13)\n    assert mi7.v() == 4\n    assert mi7.bar() == 13\n\n    mi8 = MI8(14)\n    assert mi8.v() == 1\n    assert mi8.bar() == 14\n\n    mi8b = MI8b(15)\n    assert mi8b.v() == 3\n    assert mi8b.bar() == 15\n\n\ndef test_multiple_inheritance_python_many_bases():\n    class MIMany14(m.BaseN1, m.BaseN2, m.BaseN3, m.BaseN4):\n        def __init__(self):\n            m.BaseN1.__init__(self, 1)\n            m.BaseN2.__init__(self, 2)\n            m.BaseN3.__init__(self, 3)\n            m.BaseN4.__init__(self, 4)\n\n    class MIMany58(m.BaseN5, m.BaseN6, m.BaseN7, m.BaseN8):\n        def __init__(self):\n            m.BaseN5.__init__(self, 5)\n            m.BaseN6.__init__(self, 6)\n            m.BaseN7.__init__(self, 7)\n            m.BaseN8.__init__(self, 8)\n\n    class MIMany916(\n        m.BaseN9,\n        m.BaseN10,\n        m.BaseN11,\n        m.BaseN12,\n        m.BaseN13,\n        m.BaseN14,\n        m.BaseN15,\n        m.BaseN16,\n    ):\n        def __init__(self):\n            m.BaseN9.__init__(self, 9)\n            m.BaseN10.__init__(self, 10)\n            m.BaseN11.__init__(self, 11)\n            m.BaseN12.__init__(self, 12)\n            m.BaseN13.__init__(self, 13)\n            m.BaseN14.__init__(self, 14)\n            m.BaseN15.__init__(self, 15)\n            m.BaseN16.__init__(self, 16)\n\n    class MIMany19(MIMany14, MIMany58, m.BaseN9):\n        def __init__(self):\n            MIMany14.__init__(self)\n            MIMany58.__init__(self)\n            m.BaseN9.__init__(self, 9)\n\n    class MIMany117(MIMany14, MIMany58, MIMany916, m.BaseN17):\n        def __init__(self):\n            MIMany14.__init__(self)\n            MIMany58.__init__(self)\n            MIMany916.__init__(self)\n            m.BaseN17.__init__(self, 17)\n\n    # Inherits from 4 registered C++ classes: can fit in one pointer on any modern arch:\n    a = MIMany14()\n    for i in range(1, 4):\n        assert getattr(a, \"f\" + str(i))() == 2 * i\n\n    # Inherits from 8: requires 1/2 pointers worth of holder flags on 32/64-bit arch:\n    b = MIMany916()\n    for i in range(9, 16):\n        assert getattr(b, \"f\" + str(i))() == 2 * i\n\n    # Inherits from 9: requires >= 2 pointers worth of holder flags\n    c = MIMany19()\n    for i in range(1, 9):\n        assert getattr(c, \"f\" + str(i))() == 2 * i\n\n    # Inherits from 17: requires >= 3 pointers worth of holder flags\n    d = MIMany117()\n    for i in range(1, 17):\n        assert getattr(d, \"f\" + str(i))() == 2 * i\n\n\ndef test_multiple_inheritance_virtbase():\n    class MITypePy(m.Base12a):\n        def __init__(self, i, j):\n            m.Base12a.__init__(self, i, j)\n\n    mt = MITypePy(3, 4)\n    assert mt.bar() == 4\n    assert m.bar_base2a(mt) == 4\n    assert m.bar_base2a_sharedptr(mt) == 4\n\n\ndef test_mi_static_properties():\n    \"\"\"Mixing bases with and without static properties should be possible\n    and the result should be independent of base definition order\"\"\"\n\n    for d in (m.VanillaStaticMix1(), m.VanillaStaticMix2()):\n        assert d.vanilla() == \"Vanilla\"\n        assert d.static_func1() == \"WithStatic1\"\n        assert d.static_func2() == \"WithStatic2\"\n        assert d.static_func() == d.__class__.__name__\n\n        m.WithStatic1.static_value1 = 1\n        m.WithStatic2.static_value2 = 2\n        assert d.static_value1 == 1\n        assert d.static_value2 == 2\n        assert d.static_value == 12\n\n        d.static_value1 = 0\n        assert d.static_value1 == 0\n        d.static_value2 = 0\n        assert d.static_value2 == 0\n        d.static_value = 0\n        assert d.static_value == 0\n\n\ndef test_mi_dynamic_attributes():\n    \"\"\"Mixing bases with and without dynamic attribute support\"\"\"\n\n    for d in (m.VanillaDictMix1(), m.VanillaDictMix2()):\n        d.dynamic = 1\n        assert d.dynamic == 1\n\n\ndef test_mi_unaligned_base():\n    \"\"\"Returning an offset (non-first MI) base class pointer should recognize the instance\"\"\"\n\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    c = m.I801C()\n    d = m.I801D()\n    if not env.GRAALPY:\n        # + 4 below because we have the two instances, and each instance has offset base I801B2\n        assert ConstructorStats.detail_reg_inst() == n_inst + 4\n    b1c = m.i801b1_c(c)\n    assert b1c is c\n    b2c = m.i801b2_c(c)\n    assert b2c is c\n    b1d = m.i801b1_d(d)\n    assert b1d is d\n    b2d = m.i801b2_d(d)\n    assert b2d is d\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    assert ConstructorStats.detail_reg_inst() == n_inst + 4  # no extra instances\n    del c, b1c, b2c\n    assert ConstructorStats.detail_reg_inst() == n_inst + 2\n    del d, b1d, b2d\n    assert ConstructorStats.detail_reg_inst() == n_inst\n\n\ndef test_mi_base_return():\n    \"\"\"Tests returning an offset (non-first MI) base class pointer to a derived instance\"\"\"\n\n    n_inst = ConstructorStats.detail_reg_inst()\n\n    c1 = m.i801c_b1()\n    assert type(c1) is m.I801C\n    assert c1.a == 1\n    assert c1.b == 2\n\n    d1 = m.i801d_b1()\n    assert type(d1) is m.I801D\n    assert d1.a == 1\n    assert d1.b == 2\n\n    if not env.GRAALPY:\n        assert ConstructorStats.detail_reg_inst() == n_inst + 4\n\n    c2 = m.i801c_b2()\n    assert type(c2) is m.I801C\n    assert c2.a == 1\n    assert c2.b == 2\n\n    d2 = m.i801d_b2()\n    assert type(d2) is m.I801D\n    assert d2.a == 1\n    assert d2.b == 2\n\n    if not env.GRAALPY:\n        assert ConstructorStats.detail_reg_inst() == n_inst + 8\n\n        del c2\n        assert ConstructorStats.detail_reg_inst() == n_inst + 6\n        del c1, d1, d2\n        assert ConstructorStats.detail_reg_inst() == n_inst\n\n    # Returning an unregistered derived type with a registered base; we won't\n    # pick up the derived type, obviously, but should still work (as an object\n    # of whatever type was returned).\n    e1 = m.i801e_c()\n    assert type(e1) is m.I801C\n    assert e1.a == 1\n    assert e1.b == 2\n\n    e2 = m.i801e_b2()\n    assert type(e2) is m.I801B2\n    assert e2.b == 2\n\n\ndef test_diamond_inheritance():\n    \"\"\"Tests that diamond inheritance works as expected (issue #959)\"\"\"\n\n    # Issue #959: this shouldn't segfault:\n    d = m.D()\n\n    # Make sure all the various distinct pointers are all recognized as registered instances:\n    assert d is d.c0()\n    assert d is d.c1()\n    assert d is d.b()\n    assert d is d.c0().b()\n    assert d is d.c1().b()\n    assert d is d.c0().c1().b().c0().b()\n\n\ndef test_pr3635_diamond_b():\n    o = m.MVB()\n    assert o.b == 1\n\n    assert o.get_b_b() == 1\n\n\ndef test_pr3635_diamond_c():\n    o = m.MVC()\n    assert o.b == 1\n    assert o.c == 2\n\n    assert o.get_b_b() == 1\n    assert o.get_c_b() == 1\n\n    assert o.get_c_c() == 2\n\n\ndef test_pr3635_diamond_d0():\n    o = m.MVD0()\n    assert o.b == 1\n    assert o.c == 2\n    assert o.d0 == 3\n\n    assert o.get_b_b() == 1\n    assert o.get_c_b() == 1\n    assert o.get_d0_b() == 1\n\n    assert o.get_c_c() == 2\n    assert o.get_d0_c() == 2\n\n    assert o.get_d0_d0() == 3\n\n\ndef test_pr3635_diamond_d1():\n    o = m.MVD1()\n    assert o.b == 1\n    assert o.c == 2\n    assert o.d1 == 4\n\n    assert o.get_b_b() == 1\n    assert o.get_c_b() == 1\n    assert o.get_d1_b() == 1\n\n    assert o.get_c_c() == 2\n    assert o.get_d1_c() == 2\n\n    assert o.get_d1_d1() == 4\n\n\ndef test_pr3635_diamond_e():\n    o = m.MVE()\n    assert o.b == 1\n    assert o.c == 2\n    assert o.d0 == 3\n    assert o.d1 == 4\n    assert o.e == 5\n\n    assert o.get_b_b() == 1\n    assert o.get_c_b() == 1\n    assert o.get_d0_b() == 1\n    assert o.get_d1_b() == 1\n    assert o.get_e_b() == 1\n\n    assert o.get_c_c() == 2\n    assert o.get_d0_c() == 2\n    assert o.get_d1_c() == 2\n    assert o.get_e_c() == 2\n\n    assert o.get_d0_d0() == 3\n    assert o.get_e_d0() == 3\n\n    assert o.get_d1_d1() == 4\n    assert o.get_e_d1() == 4\n\n    assert o.get_e_e() == 5\n\n\ndef test_pr3635_diamond_f():\n    o = m.MVF()\n    assert o.b == 1\n    assert o.c == 2\n    assert o.d0 == 3\n    assert o.d1 == 4\n    assert o.e == 5\n    assert o.f == 6\n\n    assert o.get_b_b() == 1\n    assert o.get_c_b() == 1\n    assert o.get_d0_b() == 1\n    assert o.get_d1_b() == 1\n    assert o.get_e_b() == 1\n    assert o.get_f_b() == 1\n\n    assert o.get_c_c() == 2\n    assert o.get_d0_c() == 2\n    assert o.get_d1_c() == 2\n    assert o.get_e_c() == 2\n    assert o.get_f_c() == 2\n\n    assert o.get_d0_d0() == 3\n    assert o.get_e_d0() == 3\n    assert o.get_f_d0() == 3\n\n    assert o.get_d1_d1() == 4\n    assert o.get_e_d1() == 4\n    assert o.get_f_d1() == 4\n\n    assert o.get_e_e() == 5\n    assert o.get_f_e() == 5\n\n    assert o.get_f_f() == 6\n\n\ndef test_python_inherit_from_mi():\n    \"\"\"Tests extending a Python class from a single inheritor of a MI class\"\"\"\n\n    class PyMVF(m.MVF):\n        g = 7\n\n        def get_g_g(self):\n            return self.g\n\n    o = PyMVF()\n\n    assert o.b == 1\n    assert o.c == 2\n    assert o.d0 == 3\n    assert o.d1 == 4\n    assert o.e == 5\n    assert o.f == 6\n    assert o.g == 7\n\n    assert o.get_g_g() == 7\n"
  },
  {
    "path": "tests/test_multiple_interpreters.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport os\nimport pickle\nimport sys\nimport textwrap\n\nimport pytest\n\nimport env\nimport pybind11_tests\n\nif env.IOS:\n    pytest.skip(\"Subinterpreters not supported on iOS\", allow_module_level=True)\n\n# 3.14.0b3+, though sys.implementation.supports_isolated_interpreters is being added in b4\n# Can be simplified when we drop support for the first three betas\nCONCURRENT_INTERPRETERS_SUPPORT = (\n    sys.version_info >= (3, 14)\n    and (\n        sys.version_info != (3, 14, 0, \"beta\", 1)\n        and sys.version_info != (3, 14, 0, \"beta\", 2)\n    )\n    and (\n        sys.version_info == (3, 14, 0, \"beta\", 3)\n        or sys.implementation.supports_isolated_interpreters\n    )\n)\n\n\ndef get_interpreters(*, modern: bool):\n    if modern and CONCURRENT_INTERPRETERS_SUPPORT:\n        from concurrent import interpreters\n\n        def create():\n            return contextlib.closing(interpreters.create())\n\n        def run_string(\n            interp: interpreters.Interpreter,\n            code: str,\n            *,\n            shared: dict[str, object] | None = None,\n        ) -> Exception | None:\n            if shared:\n                interp.prepare_main(**shared)\n            try:\n                interp.exec(code)\n                return None\n            except interpreters.ExecutionFailed as err:\n                return err\n\n        return run_string, create\n\n    if sys.version_info >= (3, 12):\n        interpreters = pytest.importorskip(\n            \"_interpreters\" if sys.version_info >= (3, 13) else \"_xxsubinterpreters\"\n        )\n\n        @contextlib.contextmanager\n        def create(config: str = \"\"):\n            try:\n                if config:\n                    interp = interpreters.create(config)\n                else:\n                    interp = interpreters.create()\n            except TypeError:\n                pytest.skip(f\"interpreters module needs to support {config} config\")\n\n            try:\n                yield interp\n            finally:\n                interpreters.destroy(interp)\n\n        def run_string(\n            interp: int, code: str, shared: dict[str, object] | None = None\n        ) -> Exception | None:\n            kwargs = {\"shared\": shared} if shared else {}\n            return interpreters.run_string(interp, code, **kwargs)\n\n        return run_string, create\n\n    pytest.skip(\"Test requires the interpreters stdlib module\")\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\ndef test_independent_subinterpreters():\n    \"\"\"Makes sure the internals object differs across independent subinterpreters\"\"\"\n\n    sys.path.insert(0, os.path.dirname(pybind11_tests.__file__))\n\n    run_string, create = get_interpreters(modern=True)\n\n    import mod_per_interpreter_gil as m\n\n    if not m.defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT:\n        pytest.skip(\"Does not have subinterpreter support compiled in\")\n\n    code = textwrap.dedent(\n        \"\"\"\n        import mod_per_interpreter_gil as m\n        import pickle\n        with open(pipeo, 'wb') as f:\n            pickle.dump(m.internals_at(), f)\n        \"\"\"\n    ).strip()\n\n    with create() as interp1, create() as interp2:\n        try:\n            res0 = run_string(interp1, \"import mod_shared_interpreter_gil\")\n            if res0 is not None:\n                res0 = str(res0)\n        except Exception as e:\n            res0 = str(e)\n\n        pipei, pipeo = os.pipe()\n        run_string(interp1, code, shared={\"pipeo\": pipeo})\n        with open(pipei, \"rb\") as f:\n            res1 = pickle.load(f)\n\n        pipei, pipeo = os.pipe()\n        run_string(interp2, code, shared={\"pipeo\": pipeo})\n        with open(pipei, \"rb\") as f:\n            res2 = pickle.load(f)\n\n    assert \"does not support loading in subinterpreters\" in res0, (\n        \"cannot use shared_gil in a default subinterpreter\"\n    )\n    assert res1 != m.internals_at(), \"internals should differ from main interpreter\"\n    assert res2 != m.internals_at(), \"internals should differ from main interpreter\"\n    assert res1 != res2, \"internals should differ between interpreters\"\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\n@pytest.mark.skipif(not CONCURRENT_INTERPRETERS_SUPPORT, reason=\"Requires 3.14.0b3+\")\ndef test_independent_subinterpreters_modern():\n    \"\"\"Makes sure the internals object differs across independent subinterpreters. Modern (3.14+) syntax.\"\"\"\n\n    sys.path.insert(0, os.path.dirname(pybind11_tests.__file__))\n\n    import mod_per_interpreter_gil as m\n\n    if not m.defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT:\n        pytest.skip(\"Does not have subinterpreter support compiled in\")\n\n    from concurrent import interpreters\n\n    code = textwrap.dedent(\n        \"\"\"\n        import mod_per_interpreter_gil as m\n\n        values.put_nowait(m.internals_at())\n        \"\"\"\n    ).strip()\n\n    with contextlib.closing(interpreters.create()) as interp1, contextlib.closing(\n        interpreters.create()\n    ) as interp2:\n        with pytest.raises(\n            interpreters.ExecutionFailed,\n            match=\"does not support loading in subinterpreters\",\n        ):\n            interp1.exec(\"import mod_shared_interpreter_gil\")\n\n        values = interpreters.create_queue()\n        interp1.prepare_main(values=values)\n        interp1.exec(code)\n        res1 = values.get_nowait()\n\n        interp2.prepare_main(values=values)\n        interp2.exec(code)\n        res2 = values.get_nowait()\n\n    assert res1 != m.internals_at(), \"internals should differ from main interpreter\"\n    assert res2 != m.internals_at(), \"internals should differ from main interpreter\"\n    assert res1 != res2, \"internals should differ between interpreters\"\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\ndef test_dependent_subinterpreters():\n    \"\"\"Makes sure the internals object differs across subinterpreters\"\"\"\n\n    sys.path.insert(0, os.path.dirname(pybind11_tests.__file__))\n\n    run_string, create = get_interpreters(modern=False)\n\n    import mod_shared_interpreter_gil as m\n\n    if not m.defined_PYBIND11_HAS_SUBINTERPRETER_SUPPORT:\n        pytest.skip(\"Does not have subinterpreter support compiled in\")\n\n    code = textwrap.dedent(\n        \"\"\"\n        import mod_shared_interpreter_gil as m\n        import pickle\n        with open(pipeo, 'wb') as f:\n            pickle.dump(m.internals_at(), f)\n        \"\"\"\n    ).strip()\n\n    with create(\"legacy\") as interp1:\n        pipei, pipeo = os.pipe()\n        run_string(interp1, code, shared={\"pipeo\": pipeo})\n        with open(pipei, \"rb\") as f:\n            res1 = pickle.load(f)\n\n    assert res1 != m.internals_at(), \"internals should differ from main interpreter\"\n\n\nPREAMBLE_CODE = textwrap.dedent(\n    f\"\"\"\n    def test():\n        import sys\n\n        sys.path.insert(0, {os.path.dirname(env.__file__)!r})\n        sys.path.insert(0, {os.path.dirname(pybind11_tests.__file__)!r})\n\n        import collections\n        import mod_per_interpreter_gil_with_singleton as m\n\n        objects = m.get_objects_in_singleton()\n        expected = [\n            type(None),               # static type: shared between interpreters\n            tuple,                    # static type: shared between interpreters\n            list,                     # static type: shared between interpreters\n            dict,                     # static type: shared between interpreters\n            collections.OrderedDict,  # static type: shared between interpreters\n            collections.defaultdict,  # heap type: dynamically created per interpreter\n            collections.deque,        # heap type: dynamically created per interpreter\n        ]\n        # Check that we have the expected objects. Avoid IndexError by checking lengths first.\n        assert len(objects) == len(expected), (\n            f\"Expected {{expected!r}} ({{len(expected)}}), got {{objects!r}} ({{len(objects)}}).\"\n        )\n        # The first ones are static types shared between interpreters.\n        assert objects[:-2] == expected[:-2], (\n            f\"Expected static objects {{expected[:-2]!r}}, got {{objects[:-2]!r}}.\"\n        )\n        # The last two are heap types created per-interpreter.\n        # The expected objects are dynamically imported from `collections`.\n        assert objects[-2:] == expected[-2:], (\n            f\"Expected heap objects {{expected[-2:]!r}}, got {{objects[-2:]!r}}.\"\n        )\n\n        assert hasattr(m, 'MyClass'), \"Module missing MyClass\"\n        assert hasattr(m, 'MyGlobalError'), \"Module missing MyGlobalError\"\n        assert hasattr(m, 'MyLocalError'), \"Module missing MyLocalError\"\n        assert hasattr(m, 'MyEnum'), \"Module missing MyEnum\"\n    \"\"\"\n).lstrip()\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\n@pytest.mark.skipif(not CONCURRENT_INTERPRETERS_SUPPORT, reason=\"Requires 3.14.0b3+\")\ndef test_import_module_with_singleton_per_interpreter():\n    \"\"\"Tests that a singleton storing Python objects works correctly per-interpreter\"\"\"\n    from concurrent import interpreters\n\n    code = f\"{PREAMBLE_CODE.strip()}\\n\\ntest()\\n\"\n    with contextlib.closing(interpreters.create()) as interp:\n        interp.exec(code)\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\n@pytest.mark.skipif(not CONCURRENT_INTERPRETERS_SUPPORT, reason=\"Requires 3.14.0b3+\")\ndef test_import_in_subinterpreter_after_main():\n    \"\"\"Tests that importing a module in a subinterpreter after the main interpreter works correctly\"\"\"\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import contextlib\n            import gc\n            from concurrent import interpreters\n\n            test()\n\n            interp = None\n            with contextlib.closing(interpreters.create()) as interp:\n                interp.call(test)\n\n            del interp\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import contextlib\n            import gc\n            import random\n            from concurrent import interpreters\n\n            test()\n\n            interps = interp = None\n            with contextlib.ExitStack() as stack:\n                interps = [\n                    stack.enter_context(contextlib.closing(interpreters.create()))\n                    for _ in range(8)\n                ]\n                random.shuffle(interps)\n                for interp in interps:\n                    interp.call(test)\n\n            del interps, interp, stack\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\n@pytest.mark.skipif(not CONCURRENT_INTERPRETERS_SUPPORT, reason=\"Requires 3.14.0b3+\")\ndef test_import_in_subinterpreter_before_main():\n    \"\"\"Tests that importing a module in a subinterpreter before the main interpreter works correctly\"\"\"\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import contextlib\n            import gc\n            from concurrent import interpreters\n\n            interp = None\n            with contextlib.closing(interpreters.create()) as interp:\n                interp.call(test)\n\n            test()\n\n            del interp\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import contextlib\n            import gc\n            from concurrent import interpreters\n\n            interps = interp = None\n            with contextlib.ExitStack() as stack:\n                interps = [\n                    stack.enter_context(contextlib.closing(interpreters.create()))\n                    for _ in range(8)\n                ]\n                for interp in interps:\n                    interp.call(test)\n\n            test()\n\n            del interps, interp, stack\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import contextlib\n            import gc\n            from concurrent import interpreters\n\n            interps = interp = None\n            with contextlib.ExitStack() as stack:\n                interps = [\n                    stack.enter_context(contextlib.closing(interpreters.create()))\n                    for _ in range(8)\n                ]\n                for interp in interps:\n                    interp.call(test)\n\n                test()\n\n            del interps, interp, stack\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n\n\n@pytest.mark.skipif(\n    sys.platform.startswith(\"emscripten\"), reason=\"Requires loadable modules\"\n)\n@pytest.mark.xfail(\n    env.MUSLLINUX,\n    reason=\"Flaky on musllinux, see also: https://github.com/pybind/pybind11/pull/5972#discussion_r2755283335\",\n    strict=False,\n)\n@pytest.mark.skipif(not CONCURRENT_INTERPRETERS_SUPPORT, reason=\"Requires 3.14.0b3+\")\ndef test_import_in_subinterpreter_concurrently():\n    \"\"\"Tests that importing a module in multiple subinterpreters concurrently works correctly\"\"\"\n    env.check_script_success_in_subprocess(\n        PREAMBLE_CODE\n        + textwrap.dedent(\n            \"\"\"\n            import gc\n            from concurrent.futures import InterpreterPoolExecutor, as_completed\n\n            futures = future = None\n            with InterpreterPoolExecutor(max_workers=16) as executor:\n                futures = [executor.submit(test) for _ in range(32)]\n                for future in as_completed(futures):\n                    future.result()\n            del futures, future, executor\n\n            for _ in range(5):\n                gc.collect()\n            \"\"\"\n        )\n    )\n"
  },
  {
    "path": "tests/test_native_enum.cpp",
    "content": "#include <pybind11/native_enum.h>\n\n#include \"pybind11_tests.h\"\n\n#include <typeindex>\n\nnamespace test_native_enum {\n\n// https://en.cppreference.com/w/cpp/language/enum\n\n// enum that takes 16 bits\nenum smallenum : std::int16_t { a, b, c };\n\n// color may be red (value 0), yellow (value 1), green (value 20), or blue (value 21)\nenum color { red, yellow, green = 20, blue };\n\n// altitude may be altitude::high or altitude::low\nenum class altitude : char {\n    high = 'h',\n    low = 'l', // trailing comma only allowed after CWG518\n};\n\nenum class flags_uchar : unsigned char { bit0 = 0x1u, bit1 = 0x2u, bit2 = 0x4u };\nenum class flags_uint : unsigned int { bit0 = 0x1u, bit1 = 0x2u, bit2 = 0x4u };\n\nenum class export_values { exv0, exv1 };\n\nenum class member_doc { mem0, mem1, mem2 };\n\nstruct class_with_enum {\n    enum class in_class { one, two };\n\n    in_class nested_value = in_class::one;\n};\n\n// https://github.com/protocolbuffers/protobuf/blob/d70b5c5156858132decfdbae0a1103e6a5cb1345/src/google/protobuf/generated_enum_util.h#L52-L53\ntemplate <typename T>\nstruct is_proto_enum : std::false_type {};\n\nenum some_proto_enum : int { Zero, One };\n\ntemplate <>\nstruct is_proto_enum<some_proto_enum> : std::true_type {};\n\nenum class func_sig_rendering {};\n\n} // namespace test_native_enum\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Negate this condition to demonstrate \"ambiguous template instantiation\" compilation error:\n#if defined(PYBIND11_HAS_NATIVE_ENUM)\ntemplate <typename ProtoEnumType>\nstruct type_caster_enum_type_enabled<\n    ProtoEnumType,\n    enable_if_t<test_native_enum::is_proto_enum<ProtoEnumType>::value>> : std::false_type {};\n#endif\n\n// https://github.com/pybind/pybind11_protobuf/blob/a50899c2eb604fc5f25deeb8901eff6231b8b3c0/pybind11_protobuf/enum_type_caster.h#L101-L105\ntemplate <typename ProtoEnumType>\nstruct type_caster<ProtoEnumType,\n                   detail::enable_if_t<test_native_enum::is_proto_enum<ProtoEnumType>::value>> {\n    static handle\n    cast(const ProtoEnumType & /*src*/, return_value_policy /*policy*/, handle /*parent*/) {\n        return py::none();\n    }\n\n    bool load(handle /*src*/, bool /*convert*/) {\n        value = static_cast<ProtoEnumType>(0);\n        return true;\n    }\n\n    PYBIND11_TYPE_CASTER(ProtoEnumType, const_name<ProtoEnumType>());\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\nTEST_SUBMODULE(native_enum, m) {\n    using namespace test_native_enum;\n\n    py::native_enum<smallenum>(m, \"smallenum\", \"enum.IntEnum\", \"doc smallenum\")\n        .value(\"a\", smallenum::a)\n        .value(\"b\", smallenum::b)\n        .value(\"c\", smallenum::c)\n        .finalize();\n\n    py::native_enum<color>(m, \"color\", \"enum.IntEnum\")\n        .value(\"red\", color::red)\n        .value(\"yellow\", color::yellow)\n        .value(\"green\", color::green)\n        .value(\"blue\", color::blue)\n        .finalize();\n\n    m.def(\"bind_altitude\", [](const py::module_ &mod) {\n        py::native_enum<altitude>(mod, \"altitude\", \"enum.Enum\")\n            .value(\"high\", altitude::high)\n            .value(\"low\", altitude::low)\n            .finalize();\n    });\n    m.def(\"is_high_altitude\", [](altitude alt) { return alt == altitude::high; });\n    m.def(\"get_altitude\", []() -> altitude { return altitude::high; });\n\n    py::native_enum<flags_uchar>(m, \"flags_uchar\", \"enum.Flag\")\n        .value(\"bit0\", flags_uchar::bit0)\n        .value(\"bit1\", flags_uchar::bit1)\n        .value(\"bit2\", flags_uchar::bit2)\n        .finalize();\n\n    py::native_enum<flags_uint>(m, \"flags_uint\", \"enum.IntFlag\")\n        .value(\"bit0\", flags_uint::bit0)\n        .value(\"bit1\", flags_uint::bit1)\n        .value(\"bit2\", flags_uint::bit2)\n        .finalize();\n\n    py::native_enum<export_values>(m, \"export_values\", \"enum.IntEnum\")\n        .value(\"exv0\", export_values::exv0)\n        .value(\"exv1\", export_values::exv1)\n        .export_values()\n        .finalize();\n\n    py::native_enum<member_doc>(m, \"member_doc\", \"enum.IntEnum\")\n        .value(\"mem0\", member_doc::mem0, \"docA\")\n        .value(\"mem1\", member_doc::mem1)\n        .value(\"mem2\", member_doc::mem2, \"docC\")\n        .finalize();\n\n    py::class_<class_with_enum> py_class_with_enum(m, \"class_with_enum\");\n    py::native_enum<class_with_enum::in_class>(py_class_with_enum, \"in_class\", \"enum.IntEnum\")\n        .value(\"one\", class_with_enum::in_class::one)\n        .value(\"two\", class_with_enum::in_class::two)\n        .finalize();\n\n    py_class_with_enum.def(py::init())\n        .def_readwrite(\"nested_value\", &class_with_enum::nested_value);\n\n    m.def(\"isinstance_color\", [](const py::object &obj) { return py::isinstance<color>(obj); });\n\n    m.def(\"pass_color\", [](color e) { return static_cast<int>(e); });\n    m.def(\"return_color\", [](int i) { return static_cast<color>(i); });\n\n    m.def(\"return_color_const_ptr\", []() -> const color * {\n        static const color test_color = color::red;\n        return &test_color;\n    });\n    m.def(\"return_color_mutbl_ptr\", []() -> color * {\n        static color test_color = color::green;\n        return &test_color;\n    });\n\n    py::native_enum<func_sig_rendering>(m, \"func_sig_rendering\", \"enum.Enum\").finalize();\n    m.def(\n        \"pass_and_return_func_sig_rendering\",\n        [](func_sig_rendering e) { return e; },\n        py::arg(\"e\"));\n\n    m.def(\"pass_some_proto_enum\", [](some_proto_enum) { return py::none(); });\n    m.def(\"return_some_proto_enum\", []() { return some_proto_enum::Zero; });\n\n#if defined(__MINGW32__)\n    m.attr(\"obj_cast_color_ptr\") = \"MinGW: dangling pointer to an unnamed temporary may be used \"\n                                   \"[-Werror=dangling-pointer=]\";\n#elif defined(NDEBUG)\n    m.attr(\"obj_cast_color_ptr\") = \"NDEBUG disables cast safety check\";\n#else\n    m.def(\"obj_cast_color_ptr\", [](const py::object &obj) { obj.cast<color *>(); });\n#endif\n\n    m.def(\"py_cast_color_handle\", [](py::handle obj) {\n        // Exercises `if (is_enum_cast && cast_is_temporary_value_reference<T>::value)`\n        // in `T cast(const handle &handle)`\n        auto e = py::cast<color>(obj);\n        return static_cast<int>(e);\n    });\n\n    m.def(\"exercise_import_or_getattr\", [](py::module_ &m, const char *native_type_name) {\n        enum fake { x };\n        py::native_enum<fake>(m, \"fake_import_or_getattr\", native_type_name)\n            .value(\"x\", fake::x)\n            .finalize();\n    });\n\n    m.def(\"native_enum_data_missing_finalize_error_message\",\n          [](const std::string &enum_name_encoded) {\n              return py::detail::native_enum_missing_finalize_error_message(enum_name_encoded);\n          });\n\n    m.def(\"native_enum_ctor_malformed_utf8\", [](const char *malformed_utf8) {\n        enum fake { x };\n        py::native_enum<fake>{py::none(), malformed_utf8, \"enum.IntEnum\"};\n    });\n\n    m.def(\"native_enum_double_finalize\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake> ne(m, \"fake_native_enum_double_finalize\", \"enum.IntEnum\");\n        ne.finalize();\n        ne.finalize();\n    });\n\n    m.def(\"native_enum_value_after_finalize\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake> ne(m, \"fake_native_enum_value_after_finalize\", \"enum.IntEnum\");\n        ne.finalize();\n        ne.value(\"x\", fake::x);\n    });\n\n    m.def(\"native_enum_value_malformed_utf8\", [](const char *malformed_utf8) {\n        enum fake { x };\n        py::native_enum<fake>(py::none(), \"fake\", \"enum.IntEnum\").value(malformed_utf8, fake::x);\n    });\n\n    m.def(\"double_registration_native_enum\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake>(m, \"fake_double_registration_native_enum\", \"enum.IntEnum\")\n            .value(\"x\", fake::x)\n            .finalize();\n        py::native_enum<fake>(m, \"fake_double_registration_native_enum\", \"enum.Enum\");\n    });\n\n    m.def(\"native_enum_name_clash\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake>(m, \"fake_native_enum_name_clash\", \"enum.IntEnum\")\n            .value(\"x\", fake::x)\n            .finalize();\n    });\n\n    m.def(\"native_enum_value_name_clash\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake>(m, \"fake_native_enum_value_name_clash\", \"enum.IntEnum\")\n            .value(\"fake_native_enum_value_name_clash_x\", fake::x)\n            .export_values()\n            .finalize();\n    });\n\n    m.def(\"double_registration_enum_before_native_enum\", [](py::module_ &m) {\n        enum fake { x };\n        py::enum_<fake>(m, \"fake_enum_first\").value(\"x\", fake::x);\n        py::native_enum<fake>(m, \"fake_enum_first\", \"enum.IntEnum\").value(\"x\", fake::x).finalize();\n    });\n\n    m.def(\"double_registration_native_enum_before_enum\", [](py::module_ &m) {\n        enum fake { x };\n        py::native_enum<fake>(m, \"fake_native_enum_first\", \"enum.IntEnum\")\n            .value(\"x\", fake::x)\n            .finalize();\n        py::enum_<fake>(m, \"name_must_be_different_to_reach_desired_code_path\");\n    });\n\n#if defined(PYBIND11_NEGATE_THIS_CONDITION_FOR_LOCAL_TESTING) && !defined(NDEBUG)\n    m.def(\"native_enum_missing_finalize_failure\", []() {\n        enum fake { x };\n        py::native_enum<fake>(\n            py::none(), \"fake_native_enum_missing_finalize_failure\", \"enum.IntEnum\")\n            .value(\"x\", fake::x)\n            // .finalize() missing\n            ;\n    });\n#else\n    m.attr(\"native_enum_missing_finalize_failure\") = \"For local testing only: terminates process\";\n#endif\n}\n"
  },
  {
    "path": "tests/test_native_enum.py",
    "content": "from __future__ import annotations\n\nimport enum\nimport pickle\n\nimport pytest\n\nimport env\nfrom pybind11_tests import native_enum as m\n\nSMALLENUM_MEMBERS = (\n    (\"a\", 0),\n    (\"b\", 1),\n    (\"c\", 2),\n)\n\nCOLOR_MEMBERS = (\n    (\"red\", 0),\n    (\"yellow\", 1),\n    (\"green\", 20),\n    (\"blue\", 21),\n)\n\nALTITUDE_MEMBERS = (\n    (\"high\", \"h\"),\n    (\"low\", \"l\"),\n)\n\nFLAGS_UCHAR_MEMBERS = (\n    (\"bit0\", 0x1),\n    (\"bit1\", 0x2),\n    (\"bit2\", 0x4),\n)\n\nFLAGS_UINT_MEMBERS = (\n    (\"bit0\", 0x1),\n    (\"bit1\", 0x2),\n    (\"bit2\", 0x4),\n)\n\nCLASS_WITH_ENUM_IN_CLASS_MEMBERS = (\n    (\"one\", 0),\n    (\"two\", 1),\n)\n\nEXPORT_VALUES_MEMBERS = (\n    (\"exv0\", 0),\n    (\"exv1\", 1),\n)\n\nMEMBER_DOC_MEMBERS = (\n    (\"mem0\", 0),\n    (\"mem1\", 1),\n    (\"mem2\", 2),\n)\n\nFUNC_SIG_RENDERING_MEMBERS = ()\n\nENUM_TYPES_AND_MEMBERS = (\n    (m.smallenum, SMALLENUM_MEMBERS),\n    (m.color, COLOR_MEMBERS),\n    (m.flags_uchar, FLAGS_UCHAR_MEMBERS),\n    (m.flags_uint, FLAGS_UINT_MEMBERS),\n    (m.export_values, EXPORT_VALUES_MEMBERS),\n    (m.member_doc, MEMBER_DOC_MEMBERS),\n    (m.func_sig_rendering, FUNC_SIG_RENDERING_MEMBERS),\n    (m.class_with_enum.in_class, CLASS_WITH_ENUM_IN_CLASS_MEMBERS),\n)\n\nENUM_TYPES = [_[0] for _ in ENUM_TYPES_AND_MEMBERS]\n\n\n@pytest.mark.parametrize(\"enum_type\", ENUM_TYPES)\ndef test_enum_type(enum_type):\n    assert isinstance(enum_type, enum.EnumMeta)\n    assert enum_type.__module__ == m.__name__\n\n\n@pytest.mark.parametrize((\"enum_type\", \"members\"), ENUM_TYPES_AND_MEMBERS)\ndef test_enum_members(enum_type, members):\n    for name, value in members:\n        assert enum_type[name].value == value\n\n\n@pytest.mark.parametrize((\"enum_type\", \"members\"), ENUM_TYPES_AND_MEMBERS)\ndef test_pickle_roundtrip(enum_type, members):\n    for name, _ in members:\n        orig = enum_type[name]\n        # This only works if __module__ is correct.\n        serialized = pickle.dumps(orig)\n        restored = pickle.loads(serialized)\n        assert restored == orig\n\n\n@pytest.mark.parametrize(\"enum_type\", [m.flags_uchar, m.flags_uint])\ndef test_enum_flag(enum_type):\n    bits02 = enum_type.bit0 | enum_type.bit2\n    assert enum_type.bit0 in bits02\n    assert enum_type.bit1 not in bits02\n    assert enum_type.bit2 in bits02\n\n\ndef test_export_values():\n    assert m.exv0 is m.export_values.exv0\n    assert m.exv1 is m.export_values.exv1\n\n\ndef test_class_doc():\n    pure_native = enum.IntEnum(\"pure_native\", ((\"mem\", 0),))\n    assert m.smallenum.__doc__ == \"doc smallenum\"\n    assert m.color.__doc__ == pure_native.__doc__\n\n\ndef test_member_doc():\n    pure_native = enum.IntEnum(\"pure_native\", ((\"mem\", 0),))\n    assert m.member_doc.mem0.__doc__ == \"docA\"\n    assert m.member_doc.mem1.__doc__ == pure_native.mem.__doc__\n    assert m.member_doc.mem2.__doc__ == \"docC\"\n\n\ndef test_pybind11_isinstance_color():\n    for name, _ in COLOR_MEMBERS:\n        assert m.isinstance_color(m.color[name])\n    assert not m.isinstance_color(m.color)\n    for name, _ in SMALLENUM_MEMBERS:\n        assert not m.isinstance_color(m.smallenum[name])\n    assert not m.isinstance_color(m.smallenum)\n    assert not m.isinstance_color(None)\n\n\ndef test_pass_color_success():\n    for name, value in COLOR_MEMBERS:\n        assert m.pass_color(m.color[name]) == value\n\n\ndef test_pass_color_fail():\n    with pytest.raises(TypeError) as excinfo:\n        m.pass_color(None)\n    assert \"pybind11_tests.native_enum.color\" in str(excinfo.value)\n\n\ndef test_return_color_success():\n    for name, value in COLOR_MEMBERS:\n        assert m.return_color(value) == m.color[name]\n\n\ndef test_return_color_fail():\n    with pytest.raises(ValueError) as excinfo_direct:\n        m.color(2)\n    with pytest.raises(ValueError) as excinfo_cast:\n        m.return_color(2)\n    assert str(excinfo_cast.value) == str(excinfo_direct.value)\n\n\ndef test_return_color_ptr():\n    assert m.return_color_const_ptr() == m.color.red\n    assert m.return_color_mutbl_ptr() == m.color.green\n\n\ndef test_property_type_hint():\n    prop = m.class_with_enum.__dict__[\"nested_value\"]\n    assert isinstance(prop, property)\n    assert prop.fget.__doc__.startswith(\n        \"(self: pybind11_tests.native_enum.class_with_enum)\"\n        \" -> pybind11_tests.native_enum.class_with_enum.in_class\"\n    )\n\n\ndef test_func_sig_rendering():\n    assert m.pass_and_return_func_sig_rendering.__doc__.startswith(\n        \"pass_and_return_func_sig_rendering(e: pybind11_tests.native_enum.func_sig_rendering)\"\n        \" -> pybind11_tests.native_enum.func_sig_rendering\"\n    )\n\n\ndef test_type_caster_enum_type_enabled_false():\n    # This is really only a \"does it compile\" test.\n    assert m.pass_some_proto_enum(None) is None\n    assert m.return_some_proto_enum() is None\n\n\n@pytest.mark.skipif(isinstance(m.obj_cast_color_ptr, str), reason=m.obj_cast_color_ptr)\ndef test_obj_cast_color_ptr():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.obj_cast_color_ptr(m.color.red)\n    assert str(excinfo.value) == \"Unable to cast native enum type to reference\"\n\n\ndef test_py_cast_color_handle():\n    for name, value in COLOR_MEMBERS:\n        assert m.py_cast_color_handle(m.color[name]) == value\n\n\ndef test_exercise_import_or_getattr_leading_dot():\n    with pytest.raises(ValueError) as excinfo:\n        m.exercise_import_or_getattr(m, \".\")\n    assert str(excinfo.value) == \"Invalid fully-qualified name `.` (native_type_name)\"\n\n\ndef test_exercise_import_or_getattr_bad_top_level():\n    with pytest.raises(ImportError) as excinfo:\n        m.exercise_import_or_getattr(m, \"NeVeRLaNd\")\n    assert (\n        str(excinfo.value)\n        == \"Failed to import top-level module `NeVeRLaNd` (native_type_name)\"\n    )\n\n\ndef test_exercise_import_or_getattr_dot_dot():\n    with pytest.raises(ValueError) as excinfo:\n        m.exercise_import_or_getattr(m, \"enum..\")\n    assert (\n        str(excinfo.value) == \"Invalid fully-qualified name `enum..` (native_type_name)\"\n    )\n\n\ndef test_exercise_import_or_getattr_bad_enum_attr():\n    with pytest.raises(ImportError) as excinfo:\n        m.exercise_import_or_getattr(m, \"enum.NoNeXiStInG\")\n    lines = str(excinfo.value).splitlines()\n    assert len(lines) >= 5\n    assert (\n        lines[0]\n        == \"Failed to import or getattr `NoNeXiStInG` from `enum` (native_type_name)\"\n    )\n    assert lines[1] == \"-------- getattr exception --------\"\n    ix = lines.index(\"-------- import exception --------\")\n    assert ix >= 3\n    assert len(lines) > ix + 0\n\n\ndef test_native_enum_data_missing_finalize_error_message():\n    msg = m.native_enum_data_missing_finalize_error_message(\"Fake\")\n    assert msg == 'pybind11::native_enum<...>(\"Fake\", ...): MISSING .finalize()'\n\n\n@pytest.mark.parametrize(\n    \"func\", [m.native_enum_ctor_malformed_utf8, m.native_enum_value_malformed_utf8]\n)\ndef test_native_enum_malformed_utf8(func):\n    if env.GRAALPY and func is m.native_enum_ctor_malformed_utf8:\n        pytest.skip(\"GraalPy does not raise UnicodeDecodeError\")\n    malformed_utf8 = b\"\\x80\"\n    with pytest.raises(UnicodeDecodeError):\n        func(malformed_utf8)\n\n\ndef test_native_enum_double_finalize():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.native_enum_double_finalize(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_native_enum_double_finalize\"): DOUBLE finalize'\n    )\n\n\ndef test_native_enum_value_after_finalize():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.native_enum_value_after_finalize(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_native_enum_value_after_finalize\"): value after finalize'\n    )\n\n\ndef test_double_registration_native_enum():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.double_registration_native_enum(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_double_registration_native_enum\") is already registered!'\n    )\n\n\ndef test_native_enum_name_clash():\n    m.fake_native_enum_name_clash = None\n    with pytest.raises(RuntimeError) as excinfo:\n        m.native_enum_name_clash(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_native_enum_name_clash\"):'\n        \" an object with that name is already defined\"\n    )\n\n\ndef test_native_enum_value_name_clash():\n    m.fake_native_enum_value_name_clash_x = None\n    with pytest.raises(RuntimeError) as excinfo:\n        m.native_enum_value_name_clash(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_native_enum_value_name_clash\")'\n        '.value(\"fake_native_enum_value_name_clash_x\"):'\n        \" an object with that name is already defined\"\n    )\n\n\ndef test_double_registration_enum_before_native_enum():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.double_registration_enum_before_native_enum(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::native_enum<...>(\"fake_enum_first\") is already registered'\n        \" as a `pybind11::enum_` or `pybind11::class_`!\"\n    )\n\n\ndef test_double_registration_native_enum_before_enum():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.double_registration_native_enum_before_enum(m)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::enum_ \"name_must_be_different_to_reach_desired_code_path\"'\n        \" is already registered as a pybind11::native_enum!\"\n    )\n\n\ndef test_native_enum_missing_finalize_failure():\n    if not isinstance(m.native_enum_missing_finalize_failure, str):\n        m.native_enum_missing_finalize_failure()\n        pytest.fail(\"Process termination expected.\")\n\n\ndef test_unregister_native_enum_when_destroyed():\n    # For stability when running tests in parallel, this test should be the\n    # only one that touches `m.altitude` or calls `m.bind_altitude`.\n\n    def test_altitude_enum():\n        # Logic copied from test_enum_type / test_enum_members.\n        # We don't test altitude there to avoid possible clashes if\n        # parallelizing against other tests in this file, and we also\n        # don't want to hold any references to the enumerators that\n        # would prevent GCing the enum type below.\n        assert isinstance(m.altitude, enum.EnumMeta)\n        assert m.altitude.__module__ == m.__name__\n        for name, value in ALTITUDE_MEMBERS:\n            assert m.altitude[name].value == value\n\n    def test_altitude_binding():\n        assert m.is_high_altitude(m.altitude.high)\n        assert not m.is_high_altitude(m.altitude.low)\n        assert m.get_altitude() is m.altitude.high\n        with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n            m.is_high_altitude(\"oops\")\n\n    m.bind_altitude(m)\n    test_altitude_enum()\n    test_altitude_binding()\n\n    if env.TYPES_ARE_IMMORTAL:\n        pytest.skip(\"can't GC type objects on this platform\")\n\n    # Delete the enum type. Returning an instance from Python should fail\n    # rather than accessing a deleted object.\n    pytest.delattr_and_ensure_destroyed((m, \"altitude\"))\n    with pytest.raises(TypeError, match=\"Unable to convert function return\"):\n        m.get_altitude()\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.is_high_altitude(\"oops\")\n\n    # Recreate the enum type; should not have any duplicate-binding error\n    m.bind_altitude(m)\n    test_altitude_enum()\n    test_altitude_binding()\n\n    # Remove the pybind11 capsule without removing the type; enum is still\n    # usable but can't be passed to/from bound functions\n    del m.altitude.__pybind11_native_enum__\n    pytest.gc_collect()\n    test_altitude_enum()  # enum itself still works\n\n    with pytest.raises(TypeError, match=\"Unable to convert function return\"):\n        m.get_altitude()\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.is_high_altitude(m.altitude.high)\n\n    del m.altitude\n"
  },
  {
    "path": "tests/test_numpy_array.cpp",
    "content": "/*\n    tests/test_numpy_array.cpp -- test core array functionality\n\n    Copyright (c) 2016 Ivan Smirnov <i.s.smirnov@gmail.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n\n#include \"pybind11_tests.h\"\n\n#include <cstdint>\n#include <utility>\n#include <vector>\n\n// Size / dtype checks.\nstruct DtypeCheck {\n    py::dtype numpy;\n    py::dtype pybind11;\n};\n\ntemplate <typename T>\nDtypeCheck get_dtype_check(const char *name) {\n    py::module_ np = py::module_::import(\"numpy\");\n    DtypeCheck check{};\n    check.numpy = np.attr(\"dtype\")(np.attr(name));\n    check.pybind11 = py::dtype::of<T>();\n    return check;\n}\n\nstd::vector<DtypeCheck> get_concrete_dtype_checks() {\n    return {// Normalization\n            get_dtype_check<std::int8_t>(\"int8\"),\n            get_dtype_check<std::uint8_t>(\"uint8\"),\n            get_dtype_check<std::int16_t>(\"int16\"),\n            get_dtype_check<std::uint16_t>(\"uint16\"),\n            get_dtype_check<std::int32_t>(\"int32\"),\n            get_dtype_check<std::uint32_t>(\"uint32\"),\n            get_dtype_check<std::int64_t>(\"int64\"),\n            get_dtype_check<std::uint64_t>(\"uint64\")};\n}\n\nstruct DtypeSizeCheck {\n    std::string name;\n    int size_cpp{};\n    int size_numpy{};\n    // For debugging.\n    py::dtype dtype;\n};\n\ntemplate <typename T>\nDtypeSizeCheck get_dtype_size_check() {\n    DtypeSizeCheck check{};\n    check.name = py::type_id<T>();\n    check.size_cpp = sizeof(T);\n    check.dtype = py::dtype::of<T>();\n    check.size_numpy = check.dtype.attr(\"itemsize\").template cast<int>();\n    return check;\n}\n\nstd::vector<DtypeSizeCheck> get_platform_dtype_size_checks() {\n    return {\n        get_dtype_size_check<short>(),\n        get_dtype_size_check<unsigned short>(),\n        get_dtype_size_check<int>(),\n        get_dtype_size_check<unsigned int>(),\n        get_dtype_size_check<long>(),\n        get_dtype_size_check<unsigned long>(),\n        get_dtype_size_check<long long>(),\n        get_dtype_size_check<unsigned long long>(),\n    };\n}\n\n// Arrays.\nusing arr = py::array;\nusing arr_t = py::array_t<uint16_t, 0>;\nstatic_assert(std::is_same<arr_t::value_type, uint16_t>::value, \"\");\n\ntemplate <typename... Ix>\narr data(const arr &a, Ix... index) {\n    return arr(a.nbytes() - a.offset_at(index...), (const uint8_t *) a.data(index...));\n}\n\ntemplate <typename... Ix>\narr data_t(const arr_t &a, Ix... index) {\n    return arr(a.size() - a.index_at(index...), a.data(index...));\n}\n\ntemplate <typename... Ix>\narr &mutate_data(arr &a, Ix... index) {\n    auto *ptr = (uint8_t *) a.mutable_data(index...);\n    for (py::ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++) {\n        ptr[i] = (uint8_t) (ptr[i] * 2);\n    }\n    return a;\n}\n\ntemplate <typename... Ix>\narr_t &mutate_data_t(arr_t &a, Ix... index) {\n    auto ptr = a.mutable_data(index...);\n    for (py::ssize_t i = 0; i < a.size() - a.index_at(index...); i++) {\n        ptr[i]++;\n    }\n    return a;\n}\n\ntemplate <typename... Ix>\npy::ssize_t index_at(const arr &a, Ix... idx) {\n    return a.index_at(idx...);\n}\ntemplate <typename... Ix>\npy::ssize_t index_at_t(const arr_t &a, Ix... idx) {\n    return a.index_at(idx...);\n}\ntemplate <typename... Ix>\npy::ssize_t offset_at(const arr &a, Ix... idx) {\n    return a.offset_at(idx...);\n}\ntemplate <typename... Ix>\npy::ssize_t offset_at_t(const arr_t &a, Ix... idx) {\n    return a.offset_at(idx...);\n}\ntemplate <typename... Ix>\npy::ssize_t at_t(const arr_t &a, Ix... idx) {\n    return a.at(idx...);\n}\ntemplate <typename... Ix>\narr_t &mutate_at_t(arr_t &a, Ix... idx) {\n    a.mutable_at(idx...)++;\n    return a;\n}\n\n#define def_index_fn(name, type)                                                                  \\\n    sm.def(#name, [](type a) { return name(a); });                                                \\\n    sm.def(#name, [](type a, int i) { return name(a, i); });                                      \\\n    sm.def(#name, [](type a, int i, int j) { return name(a, i, j); });                            \\\n    sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); });\n\ntemplate <typename T, typename T2>\npy::handle auxiliaries(T &&r, T2 &&r2) {\n    if (r.ndim() != 2) {\n        throw std::domain_error(\"error: ndim != 2\");\n    }\n    py::list l;\n    l.append(*r.data(0, 0));\n    l.append(*r2.mutable_data(0, 0));\n    l.append(r.data(0, 1) == r2.mutable_data(0, 1));\n    l.append(r.ndim());\n    l.append(r.itemsize());\n    l.append(r.shape(0));\n    l.append(r.shape(1));\n    l.append(r.size());\n    l.append(r.nbytes());\n    return l.release();\n}\n\ntemplate <typename PyObjectType>\nPyObjectType convert_to_pyobjecttype(py::object obj);\n\ntemplate <>\nPyObject *convert_to_pyobjecttype<PyObject *>(py::object obj) {\n    return obj.release().ptr();\n}\n\ntemplate <>\npy::handle convert_to_pyobjecttype<py::handle>(py::object obj) {\n    return obj.release();\n}\n\ntemplate <>\npy::object convert_to_pyobjecttype<py::object>(py::object obj) {\n    return obj;\n}\n\ntemplate <typename PyObjectType>\nstd::string pass_array_return_sum_str_values(const py::array_t<PyObjectType> &objs) {\n    std::string sum_str_values;\n    for (const auto &obj : objs) {\n        sum_str_values += py::str(obj.attr(\"value\"));\n    }\n    return sum_str_values;\n}\n\ntemplate <typename PyObjectType>\npy::list pass_array_return_as_list(const py::array_t<PyObjectType> &objs) {\n    return objs;\n}\n\ntemplate <typename PyObjectType>\npy::array_t<PyObjectType> return_array_cpp_loop(const py::list &objs) {\n    py::size_t arr_size = py::len(objs);\n    py::array_t<PyObjectType> arr_from_list(static_cast<py::ssize_t>(arr_size));\n    PyObjectType *data = arr_from_list.mutable_data();\n    for (py::size_t i = 0; i < arr_size; i++) {\n        assert(!data[i]);\n        data[i] = convert_to_pyobjecttype<PyObjectType>(objs[i].attr(\"value\"));\n    }\n    return arr_from_list;\n}\n\ntemplate <typename PyObjectType>\npy::array_t<PyObjectType> return_array_from_list(const py::list &objs) {\n    return objs;\n}\n\n// note: declaration at local scope would create a dangling reference!\nstatic int data_i = 42;\n\nTEST_SUBMODULE(numpy_array, sm) {\n    try {\n        py::module_::import(\"numpy\");\n    } catch (const py::error_already_set &) {\n        return;\n    }\n\n    // test_dtypes\n    py::class_<DtypeCheck>(sm, \"DtypeCheck\")\n        .def_readonly(\"numpy\", &DtypeCheck::numpy)\n        .def_readonly(\"pybind11\", &DtypeCheck::pybind11)\n        .def(\"__repr__\", [](const DtypeCheck &self) {\n            return py::str(\"<DtypeCheck numpy={} pybind11={}>\").format(self.numpy, self.pybind11);\n        });\n    sm.def(\"get_concrete_dtype_checks\", &get_concrete_dtype_checks);\n\n    py::class_<DtypeSizeCheck>(sm, \"DtypeSizeCheck\")\n        .def_readonly(\"name\", &DtypeSizeCheck::name)\n        .def_readonly(\"size_cpp\", &DtypeSizeCheck::size_cpp)\n        .def_readonly(\"size_numpy\", &DtypeSizeCheck::size_numpy)\n        .def(\"__repr__\", [](const DtypeSizeCheck &self) {\n            return py::str(\"<DtypeSizeCheck name='{}' size_cpp={} size_numpy={} dtype={}>\")\n                .format(self.name, self.size_cpp, self.size_numpy, self.dtype);\n        });\n    sm.def(\"get_platform_dtype_size_checks\", &get_platform_dtype_size_checks);\n\n    // test_array_attributes\n    sm.def(\"ndim\", [](const arr &a) { return a.ndim(); });\n    sm.def(\"shape\", [](const arr &a) { return arr(a.ndim(), a.shape()); });\n    sm.def(\"shape\", [](const arr &a, py::ssize_t dim) { return a.shape(dim); });\n    sm.def(\"strides\", [](const arr &a) { return arr(a.ndim(), a.strides()); });\n    sm.def(\"strides\", [](const arr &a, py::ssize_t dim) { return a.strides(dim); });\n    sm.def(\"writeable\", [](const arr &a) { return a.writeable(); });\n    sm.def(\"size\", [](const arr &a) { return a.size(); });\n    sm.def(\"itemsize\", [](const arr &a) { return a.itemsize(); });\n    sm.def(\"nbytes\", [](const arr &a) { return a.nbytes(); });\n    sm.def(\"owndata\", [](const arr &a) { return a.owndata(); });\n\n#ifdef PYBIND11_HAS_SPAN\n    // test_shape_strides_span\n    sm.def(\"shape_span\", [](const arr &a) {\n        auto span = a.shape_span();\n        return std::vector<py::ssize_t>(span.begin(), span.end());\n    });\n    sm.def(\"strides_span\", [](const arr &a) {\n        auto span = a.strides_span();\n        return std::vector<py::ssize_t>(span.begin(), span.end());\n    });\n    // Test that spans can be used to construct new arrays\n    sm.def(\"array_from_spans\", [](const arr &a) {\n        return py::array(a.dtype(), a.shape_span(), a.strides_span(), a.data(), a);\n    });\n#endif\n\n    // test_index_offset\n    def_index_fn(index_at, const arr &);\n    def_index_fn(index_at_t, const arr_t &);\n    def_index_fn(offset_at, const arr &);\n    def_index_fn(offset_at_t, const arr_t &);\n    // test_data\n    def_index_fn(data, const arr &);\n    def_index_fn(data_t, const arr_t &);\n    // test_mutate_data, test_mutate_readonly\n    def_index_fn(mutate_data, arr &);\n    def_index_fn(mutate_data_t, arr_t &);\n    def_index_fn(at_t, const arr_t &);\n    def_index_fn(mutate_at_t, arr_t &);\n\n    // test_make_c_f_array\n    sm.def(\"make_f_array\", [] { return py::array_t<float>({2, 2}, {4, 8}); });\n    sm.def(\"make_c_array\", [] { return py::array_t<float>({2, 2}, {8, 4}); });\n\n    // test_empty_shaped_array\n    sm.def(\"make_empty_shaped_array\", [] { return py::array(py::dtype(\"f\"), {}, {}); });\n    // test numpy scalars (empty shape, ndim==0)\n    sm.def(\"scalar_int\", []() { return py::array(py::dtype(\"i\"), {}, {}, &data_i); });\n\n    // test_wrap\n    sm.def(\"wrap\", [](const py::array &a) {\n        return py::array(a.dtype(),\n                         {a.shape(), a.shape() + a.ndim()},\n                         {a.strides(), a.strides() + a.ndim()},\n                         a.data(),\n                         a);\n    });\n\n    // test_numpy_view\n    struct ArrayClass {\n        int data[2] = {1, 2};\n        ArrayClass() { py::print(\"ArrayClass()\"); }\n        ArrayClass(const ArrayClass &) = default;\n        ~ArrayClass() { py::print(\"~ArrayClass()\"); }\n    };\n    py::class_<ArrayClass>(sm, \"ArrayClass\")\n        .def(py::init<>())\n        .def(\"numpy_view\", [](py::object &obj) {\n            py::print(\"ArrayClass::numpy_view()\");\n            auto &a = obj.cast<ArrayClass &>();\n            return py::array_t<int>({2}, {4}, a.data, obj);\n        });\n\n    // test_cast_numpy_int64_to_uint64\n    sm.def(\"function_taking_uint64\", [](uint64_t) {});\n\n    // test_isinstance\n    sm.def(\"isinstance_untyped\", [](py::object yes, py::object no) {\n        return py::isinstance<py::array>(std::move(yes))\n               && !py::isinstance<py::array>(std::move(no));\n    });\n    sm.def(\"isinstance_typed\", [](const py::object &o) {\n        return py::isinstance<py::array_t<double>>(o) && !py::isinstance<py::array_t<int>>(o);\n    });\n\n    // test_constructors\n    sm.def(\"default_constructors\", []() {\n        return py::dict(\"array\"_a = py::array(),\n                        \"array_t<int32>\"_a = py::array_t<std::int32_t>(),\n                        \"array_t<double>\"_a = py::array_t<double>());\n    });\n    sm.def(\"converting_constructors\", [](const py::object &o) {\n        return py::dict(\"array\"_a = py::array(o),\n                        \"array_t<int32>\"_a = py::array_t<std::int32_t>(o),\n                        \"array_t<double>\"_a = py::array_t<double>(o));\n    });\n\n    // test_overload_resolution\n    sm.def(\"overloaded\", [](const py::array_t<double> &) { return \"double\"; });\n    sm.def(\"overloaded\", [](const py::array_t<float> &) { return \"float\"; });\n    sm.def(\"overloaded\", [](const py::array_t<int> &) { return \"int\"; });\n    sm.def(\"overloaded\", [](const py::array_t<unsigned short> &) { return \"unsigned short\"; });\n    sm.def(\"overloaded\", [](const py::array_t<long long> &) { return \"long long\"; });\n    sm.def(\"overloaded\",\n           [](const py::array_t<std::complex<double>> &) { return \"double complex\"; });\n    sm.def(\"overloaded\", [](const py::array_t<std::complex<float>> &) { return \"float complex\"; });\n\n    sm.def(\"overloaded2\",\n           [](const py::array_t<std::complex<double>> &) { return \"double complex\"; });\n    sm.def(\"overloaded2\", [](const py::array_t<double> &) { return \"double\"; });\n    sm.def(\"overloaded2\",\n           [](const py::array_t<std::complex<float>> &) { return \"float complex\"; });\n    sm.def(\"overloaded2\", [](const py::array_t<float> &) { return \"float\"; });\n\n    // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.\n\n    // Only accept the exact types:\n    sm.def(\"overloaded3\", [](const py::array_t<int> &) { return \"int\"; }, py::arg{}.noconvert());\n    sm.def(\n        \"overloaded3\",\n        [](const py::array_t<double> &) { return \"double\"; },\n        py::arg{}.noconvert());\n\n    // Make sure we don't do unsafe coercion (e.g. float to int) when not using forcecast, but\n    // rather that float gets converted via the safe (conversion to double) overload:\n    sm.def(\"overloaded4\", [](const py::array_t<long long, 0> &) { return \"long long\"; });\n    sm.def(\"overloaded4\", [](const py::array_t<double, 0> &) { return \"double\"; });\n\n    // But we do allow conversion to int if forcecast is enabled (but only if no overload matches\n    // without conversion)\n    sm.def(\"overloaded5\", [](const py::array_t<unsigned int> &) { return \"unsigned int\"; });\n    sm.def(\"overloaded5\", [](const py::array_t<double> &) { return \"double\"; });\n\n    // test_greedy_string_overload\n    // Issue 685: ndarray shouldn't go to std::string overload\n    sm.def(\"issue685\", [](const std::string &) { return \"string\"; });\n    sm.def(\"issue685\", [](const py::array &) { return \"array\"; });\n    sm.def(\"issue685\", [](const py::object &) { return \"other\"; });\n\n    // test_array_unchecked_fixed_dims\n    sm.def(\n        \"proxy_add2\",\n        [](py::array_t<double> a, double v) {\n            auto r = a.mutable_unchecked<2>();\n            for (py::ssize_t i = 0; i < r.shape(0); i++) {\n                for (py::ssize_t j = 0; j < r.shape(1); j++) {\n                    r(i, j) += v;\n                }\n            }\n        },\n        py::arg{}.noconvert(),\n        py::arg());\n\n    sm.def(\"proxy_init3\", [](double start) {\n        py::array_t<double, py::array::c_style> a({3, 3, 3});\n        auto r = a.mutable_unchecked<3>();\n        for (py::ssize_t i = 0; i < r.shape(0); i++) {\n            for (py::ssize_t j = 0; j < r.shape(1); j++) {\n                for (py::ssize_t k = 0; k < r.shape(2); k++) {\n                    r(i, j, k) = start++;\n                }\n            }\n        }\n        return a;\n    });\n    sm.def(\"proxy_init3F\", [](double start) {\n        py::array_t<double, py::array::f_style> a({3, 3, 3});\n        auto r = a.mutable_unchecked<3>();\n        for (py::ssize_t k = 0; k < r.shape(2); k++) {\n            for (py::ssize_t j = 0; j < r.shape(1); j++) {\n                for (py::ssize_t i = 0; i < r.shape(0); i++) {\n                    r(i, j, k) = start++;\n                }\n            }\n        }\n        return a;\n    });\n    sm.def(\"proxy_squared_L2_norm\", [](const py::array_t<double> &a) {\n        auto r = a.unchecked<1>();\n        double sumsq = 0;\n        for (py::ssize_t i = 0; i < r.shape(0); i++) {\n            sumsq += r[i] * r(i); // Either notation works for a 1D array\n        }\n        return sumsq;\n    });\n\n    sm.def(\"proxy_auxiliaries2\", [](py::array_t<double> a) {\n        auto r = a.unchecked<2>();\n        auto r2 = a.mutable_unchecked<2>();\n        return auxiliaries(r, r2);\n    });\n\n    sm.def(\"proxy_auxiliaries1_const_ref\", [](py::array_t<double> a) {\n        const auto &r = a.unchecked<1>();\n        const auto &r2 = a.mutable_unchecked<1>();\n        return r(0) == r2(0) && r[0] == r2[0];\n    });\n\n    sm.def(\"proxy_auxiliaries2_const_ref\", [](py::array_t<double> a) {\n        const auto &r = a.unchecked<2>();\n        const auto &r2 = a.mutable_unchecked<2>();\n        return r(0, 0) == r2(0, 0);\n    });\n\n    // test_array_unchecked_dyn_dims\n    // Same as the above, but without a compile-time dimensions specification:\n    sm.def(\n        \"proxy_add2_dyn\",\n        [](py::array_t<double> a, double v) {\n            auto r = a.mutable_unchecked();\n            if (r.ndim() != 2) {\n                throw std::domain_error(\"error: ndim != 2\");\n            }\n            for (py::ssize_t i = 0; i < r.shape(0); i++) {\n                for (py::ssize_t j = 0; j < r.shape(1); j++) {\n                    r(i, j) += v;\n                }\n            }\n        },\n        py::arg{}.noconvert(),\n        py::arg());\n    sm.def(\"proxy_init3_dyn\", [](double start) {\n        py::array_t<double, py::array::c_style> a({3, 3, 3});\n        auto r = a.mutable_unchecked();\n        if (r.ndim() != 3) {\n            throw std::domain_error(\"error: ndim != 3\");\n        }\n        for (py::ssize_t i = 0; i < r.shape(0); i++) {\n            for (py::ssize_t j = 0; j < r.shape(1); j++) {\n                for (py::ssize_t k = 0; k < r.shape(2); k++) {\n                    r(i, j, k) = start++;\n                }\n            }\n        }\n        return a;\n    });\n    sm.def(\"proxy_auxiliaries2_dyn\", [](py::array_t<double> a) {\n        return auxiliaries(a.unchecked(), a.mutable_unchecked());\n    });\n\n    sm.def(\"array_auxiliaries2\", [](py::array_t<double> a) { return auxiliaries(a, a); });\n\n    // test_array_failures\n    // Issue #785: Uninformative \"Unknown internal error\" exception when constructing array from\n    // empty object:\n    sm.def(\"array_fail_test\", []() { return py::array(py::object()); });\n    sm.def(\"array_t_fail_test\", []() { return py::array_t<double>(py::object()); });\n    // Make sure the error from numpy is being passed through:\n    sm.def(\"array_fail_test_negative_size\", []() {\n        int c = 0;\n        return py::array(-1, &c);\n    });\n\n    // test_initializer_list\n    // Issue (unnumbered; reported in #788): regression: initializer lists can be ambiguous\n    sm.def(\"array_initializer_list1\", []() { return py::array_t<float>(1); });\n    // { 1 } also works for the above, but clang warns about it\n    sm.def(\"array_initializer_list2\", []() { return py::array_t<float>({1, 2}); });\n    sm.def(\"array_initializer_list3\", []() { return py::array_t<float>({1, 2, 3}); });\n    sm.def(\"array_initializer_list4\", []() { return py::array_t<float>({1, 2, 3, 4}); });\n\n    // test_array_resize\n    // reshape array to 2D without changing size\n    sm.def(\"array_reshape2\", [](py::array_t<double> a) {\n        const auto dim_sz = (py::ssize_t) std::sqrt(a.size());\n        if (dim_sz * dim_sz != a.size()) {\n            throw std::domain_error(\n                \"array_reshape2: input array total size is not a squared integer\");\n        }\n        a.resize({dim_sz, dim_sz});\n    });\n\n    // resize to 3D array with each dimension = N\n    sm.def(\"array_resize3\",\n           [](py::array_t<double> a, size_t N, bool refcheck) { a.resize({N, N, N}, refcheck); });\n\n    // test_array_create_and_resize\n    // return 2D array with Nrows = Ncols = N\n    sm.def(\"create_and_resize\", [](size_t N) {\n        py::array_t<double> a;\n        a.resize({N, N});\n        std::fill(a.mutable_data(), a.mutable_data() + a.size(), 42.);\n        return a;\n    });\n\n    sm.def(\"array_view\",\n           [](py::array_t<uint8_t> a, const std::string &dtype) { return a.view(dtype); });\n\n    sm.def(\"reshape_initializer_list\",\n           [](py::array_t<int> a, size_t N, size_t M, size_t O) { return a.reshape({N, M, O}); });\n    sm.def(\"reshape_tuple\", [](py::array_t<int> a, const std::vector<int> &new_shape) {\n        return a.reshape(new_shape);\n    });\n\n    sm.def(\"index_using_ellipsis\",\n           [](const py::array &a) { return a[py::make_tuple(0, py::ellipsis(), 0)]; });\n\n    // test_argument_conversions\n    sm.def(\"accept_double\", [](const py::array_t<double, 0> &) {}, py::arg(\"a\"));\n    sm.def(\n        \"accept_double_forcecast\",\n        [](const py::array_t<double, py::array::forcecast> &) {},\n        py::arg(\"a\"));\n    sm.def(\n        \"accept_double_c_style\",\n        [](const py::array_t<double, py::array::c_style> &) {},\n        py::arg(\"a\"));\n    sm.def(\n        \"accept_double_c_style_forcecast\",\n        [](const py::array_t<double, py::array::forcecast | py::array::c_style> &) {},\n        py::arg(\"a\"));\n    sm.def(\n        \"accept_double_f_style\",\n        [](const py::array_t<double, py::array::f_style> &) {},\n        py::arg(\"a\"));\n    sm.def(\n        \"accept_double_f_style_forcecast\",\n        [](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {},\n        py::arg(\"a\"));\n    sm.def(\"accept_double_noconvert\", [](const py::array_t<double, 0> &) {}, \"a\"_a.noconvert());\n    sm.def(\n        \"accept_double_forcecast_noconvert\",\n        [](const py::array_t<double, py::array::forcecast> &) {},\n        \"a\"_a.noconvert());\n    sm.def(\n        \"accept_double_c_style_noconvert\",\n        [](const py::array_t<double, py::array::c_style> &) {},\n        \"a\"_a.noconvert());\n    sm.def(\n        \"accept_double_c_style_forcecast_noconvert\",\n        [](const py::array_t<double, py::array::forcecast | py::array::c_style> &) {},\n        \"a\"_a.noconvert());\n    sm.def(\n        \"accept_double_f_style_noconvert\",\n        [](const py::array_t<double, py::array::f_style> &) {},\n        \"a\"_a.noconvert());\n    sm.def(\n        \"accept_double_f_style_forcecast_noconvert\",\n        [](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {},\n        \"a\"_a.noconvert());\n\n    // Check that types returns correct npy format descriptor\n    sm.def(\"test_fmt_desc_float\", [](const py::array_t<float> &) {});\n    sm.def(\"test_fmt_desc_double\", [](const py::array_t<double> &) {});\n    sm.def(\"test_fmt_desc_const_float\", [](const py::array_t<const float> &) {});\n    sm.def(\"test_fmt_desc_const_double\", [](const py::array_t<const double> &) {});\n\n    sm.def(\"round_trip_float\", [](double d) { return d; });\n\n    sm.def(\"pass_array_pyobject_ptr_return_sum_str_values\",\n           pass_array_return_sum_str_values<PyObject *>);\n    sm.def(\"pass_array_handle_return_sum_str_values\",\n           pass_array_return_sum_str_values<py::handle>);\n    sm.def(\"pass_array_object_return_sum_str_values\",\n           pass_array_return_sum_str_values<py::object>);\n\n    sm.def(\"pass_array_pyobject_ptr_return_as_list\", pass_array_return_as_list<PyObject *>);\n    sm.def(\"pass_array_handle_return_as_list\", pass_array_return_as_list<py::handle>);\n    sm.def(\"pass_array_object_return_as_list\", pass_array_return_as_list<py::object>);\n\n    sm.def(\"return_array_pyobject_ptr_cpp_loop\", return_array_cpp_loop<PyObject *>);\n    sm.def(\"return_array_handle_cpp_loop\", return_array_cpp_loop<py::handle>);\n    sm.def(\"return_array_object_cpp_loop\", return_array_cpp_loop<py::object>);\n\n    sm.def(\"return_array_pyobject_ptr_from_list\", return_array_from_list<PyObject *>);\n    sm.def(\"return_array_handle_from_list\", return_array_from_list<py::handle>);\n    sm.def(\"return_array_object_from_list\", return_array_from_list<py::object>);\n\n    sm.def(\n        \"round_trip_array_t\",\n        [](const py::array_t<float> &x) -> py::array_t<float> { return x; },\n        py::arg(\"x\"));\n    sm.def(\n        \"round_trip_array_t_noconvert\",\n        [](const py::array_t<float> &x) -> py::array_t<float> { return x; },\n        py::arg(\"x\").noconvert());\n}\n"
  },
  {
    "path": "tests/test_numpy_array.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import numpy_array as m\n\nnp = pytest.importorskip(\"numpy\")\n\n\ndef test_dtypes():\n    # See issue #1328.\n    # - Platform-dependent sizes.\n    for size_check in m.get_platform_dtype_size_checks():\n        print(size_check)\n        assert size_check.size_cpp == size_check.size_numpy, size_check\n    # - Concrete sizes.\n    for check in m.get_concrete_dtype_checks():\n        print(check)\n        assert check.numpy == check.pybind11, check\n        if check.numpy.num != check.pybind11.num:\n            print(\n                f\"NOTE: typenum mismatch for {check}: {check.numpy.num} != {check.pybind11.num}\"\n            )\n\n\n@pytest.fixture\ndef arr():\n    return np.array([[1, 2, 3], [4, 5, 6]], \"=u2\")\n\n\ndef test_array_attributes():\n    a = np.array(0, \"f8\")\n    assert m.ndim(a) == 0\n    assert all(m.shape(a) == [])\n    assert all(m.strides(a) == [])\n    with pytest.raises(IndexError) as excinfo:\n        m.shape(a, 0)\n    assert str(excinfo.value) == \"invalid axis: 0 (ndim = 0)\"\n    with pytest.raises(IndexError) as excinfo:\n        m.strides(a, 0)\n    assert str(excinfo.value) == \"invalid axis: 0 (ndim = 0)\"\n    assert m.writeable(a)\n    assert m.size(a) == 1\n    assert m.itemsize(a) == 8\n    assert m.nbytes(a) == 8\n    assert m.owndata(a)\n\n    a = np.array([[1, 2, 3], [4, 5, 6]], \"u2\").view()\n    a.flags.writeable = False\n    assert m.ndim(a) == 2\n    assert all(m.shape(a) == [2, 3])\n    assert m.shape(a, 0) == 2\n    assert m.shape(a, 1) == 3\n    assert all(m.strides(a) == [6, 2])\n    assert m.strides(a, 0) == 6\n    assert m.strides(a, 1) == 2\n    with pytest.raises(IndexError) as excinfo:\n        m.shape(a, 2)\n    assert str(excinfo.value) == \"invalid axis: 2 (ndim = 2)\"\n    with pytest.raises(IndexError) as excinfo:\n        m.strides(a, 2)\n    assert str(excinfo.value) == \"invalid axis: 2 (ndim = 2)\"\n    assert not m.writeable(a)\n    assert m.size(a) == 6\n    assert m.itemsize(a) == 2\n    assert m.nbytes(a) == 12\n    assert not m.owndata(a)\n\n\n@pytest.mark.skipif(not hasattr(m, \"shape_span\"), reason=\"std::span not available\")\ndef test_shape_strides_span():\n    # Test 0-dimensional array (scalar)\n    a = np.array(42, \"f8\")\n    assert m.ndim(a) == 0\n    assert m.shape_span(a) == []\n    assert m.strides_span(a) == []\n\n    # Test 1-dimensional array\n    a = np.array([1, 2, 3, 4], \"u2\")\n    assert m.ndim(a) == 1\n    assert m.shape_span(a) == [4]\n    assert m.strides_span(a) == [2]\n\n    # Test 2-dimensional array\n    a = np.array([[1, 2, 3], [4, 5, 6]], \"u2\").view()\n    a.flags.writeable = False\n    assert m.ndim(a) == 2\n    assert m.shape_span(a) == [2, 3]\n    assert m.strides_span(a) == [6, 2]\n\n    # Test 3-dimensional array\n    a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], \"i4\")\n    assert m.ndim(a) == 3\n    assert m.shape_span(a) == [2, 2, 2]\n    # Verify spans match regular shape/strides\n    assert list(m.shape_span(a)) == list(m.shape(a))\n    assert list(m.strides_span(a)) == list(m.strides(a))\n\n    # Test that spans can be used to construct new arrays\n    original = np.array([[1, 2, 3], [4, 5, 6]], \"f4\")\n    new_array = m.array_from_spans(original)\n    assert new_array.shape == original.shape\n    assert new_array.strides == original.strides\n    assert new_array.dtype == original.dtype\n    # Verify data is shared (since we pass the same data pointer)\n    np.testing.assert_array_equal(new_array, original)\n\n\n@pytest.mark.parametrize(\n    (\"args\", \"ret\"), [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]\n)\ndef test_index_offset(arr, args, ret):\n    assert m.index_at(arr, *args) == ret\n    assert m.index_at_t(arr, *args) == ret\n    assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize\n    assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize\n\n\ndef test_dim_check_fail(arr):\n    for func in (\n        m.index_at,\n        m.index_at_t,\n        m.offset_at,\n        m.offset_at_t,\n        m.data,\n        m.data_t,\n        m.mutate_data,\n        m.mutate_data_t,\n    ):\n        with pytest.raises(IndexError) as excinfo:\n            func(arr, 1, 2, 3)\n        assert str(excinfo.value) == \"too many indices for an array: 3 (ndim = 2)\"\n\n\n@pytest.mark.parametrize(\n    (\"args\", \"ret\"),\n    [\n        ([], [1, 2, 3, 4, 5, 6]),\n        ([1], [4, 5, 6]),\n        ([0, 1], [2, 3, 4, 5, 6]),\n        ([1, 2], [6]),\n    ],\n)\ndef test_data(arr, args, ret):\n    from sys import byteorder\n\n    assert all(m.data_t(arr, *args) == ret)\n    assert all(m.data(arr, *args)[(0 if byteorder == \"little\" else 1) :: 2] == ret)\n    assert all(m.data(arr, *args)[(1 if byteorder == \"little\" else 0) :: 2] == 0)\n\n\n@pytest.mark.parametrize(\"dim\", [0, 1, 3])\ndef test_at_fail(arr, dim):\n    for func in m.at_t, m.mutate_at_t:\n        with pytest.raises(IndexError) as excinfo:\n            func(arr, *([0] * dim))\n        assert str(excinfo.value) == f\"index dimension mismatch: {dim} (ndim = 2)\"\n\n\ndef test_at(arr):\n    assert m.at_t(arr, 0, 2) == 3\n    assert m.at_t(arr, 1, 0) == 4\n\n    assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])\n    assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])\n\n\ndef test_mutate_readonly(arr):\n    arr.flags.writeable = False\n    for func, args in (\n        (m.mutate_data, ()),\n        (m.mutate_data_t, ()),\n        (m.mutate_at_t, (0, 0)),\n    ):\n        with pytest.raises(ValueError) as excinfo:\n            func(arr, *args)\n        assert str(excinfo.value) == \"array is not writeable\"\n\n\ndef test_mutate_data(arr):\n    assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])\n    assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])\n    assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])\n    assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])\n    assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])\n\n    assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])\n    assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])\n    assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])\n    assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])\n    assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])\n\n\ndef test_bounds_check(arr):\n    for func in (\n        m.index_at,\n        m.index_at_t,\n        m.data,\n        m.data_t,\n        m.mutate_data,\n        m.mutate_data_t,\n        m.at_t,\n        m.mutate_at_t,\n    ):\n        with pytest.raises(IndexError) as excinfo:\n            func(arr, 2, 0)\n        assert str(excinfo.value) == \"index 2 is out of bounds for axis 0 with size 2\"\n        with pytest.raises(IndexError) as excinfo:\n            func(arr, 0, 4)\n        assert str(excinfo.value) == \"index 4 is out of bounds for axis 1 with size 3\"\n\n\ndef test_make_c_f_array():\n    assert m.make_c_array().flags.c_contiguous\n    assert not m.make_c_array().flags.f_contiguous\n    assert m.make_f_array().flags.f_contiguous\n    assert not m.make_f_array().flags.c_contiguous\n\n\ndef test_make_empty_shaped_array():\n    m.make_empty_shaped_array()\n\n    # empty shape means numpy scalar, PEP 3118\n    assert m.scalar_int().ndim == 0\n    assert m.scalar_int().shape == ()\n    assert m.scalar_int() == 42\n\n\ndef test_wrap():\n    def assert_references(a, b, base=None):\n        if base is None:\n            base = a\n        assert a is not b\n        assert a.__array_interface__[\"data\"][0] == b.__array_interface__[\"data\"][0]\n        assert a.shape == b.shape\n        assert a.strides == b.strides\n        assert a.flags.c_contiguous == b.flags.c_contiguous\n        assert a.flags.f_contiguous == b.flags.f_contiguous\n        assert a.flags.writeable == b.flags.writeable\n        assert a.flags.aligned == b.flags.aligned\n        assert a.flags.writebackifcopy == b.flags.writebackifcopy\n        assert np.all(a == b)\n        assert not b.flags.owndata\n        assert b.base is base\n        if a.flags.writeable and a.ndim == 2:\n            a[0, 0] = 1234\n            assert b[0, 0] == 1234\n\n    a1 = np.array([1, 2], dtype=np.int16)\n    assert a1.flags.owndata\n    assert a1.base is None\n    a2 = m.wrap(a1)\n    assert_references(a1, a2)\n\n    a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=\"F\")\n    assert a1.flags.owndata\n    assert a1.base is None\n    a2 = m.wrap(a1)\n    assert_references(a1, a2)\n\n    a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=\"C\")\n    a1.flags.writeable = False\n    a2 = m.wrap(a1)\n    assert_references(a1, a2)\n\n    a1 = np.random.random((4, 4, 4))\n    a2 = m.wrap(a1)\n    assert_references(a1, a2)\n\n    a1t = a1.transpose()\n    a2 = m.wrap(a1t)\n    assert_references(a1t, a2, a1)\n\n    a1d = a1.diagonal()\n    a2 = m.wrap(a1d)\n    assert_references(a1d, a2, a1)\n\n    a1m = a1[::-1, ::-1, ::-1]\n    a2 = m.wrap(a1m)\n    assert_references(a1m, a2, a1)\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_numpy_view(capture):\n    with capture:\n        ac = m.ArrayClass()\n        ac_view_1 = ac.numpy_view()\n        ac_view_2 = ac.numpy_view()\n        assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))\n        del ac\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        ArrayClass()\n        ArrayClass::numpy_view()\n        ArrayClass::numpy_view()\n    \"\"\"\n    )\n    ac_view_1[0] = 4\n    ac_view_1[1] = 3\n    assert ac_view_2[0] == 4\n    assert ac_view_2[1] == 3\n    with capture:\n        del ac_view_1\n        del ac_view_2\n        pytest.gc_collect()\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        ~ArrayClass()\n    \"\"\"\n    )\n\n\ndef test_cast_numpy_int64_to_uint64():\n    m.function_taking_uint64(123)\n    m.function_taking_uint64(np.uint64(123))\n\n\ndef test_isinstance():\n    assert m.isinstance_untyped(np.array([1, 2, 3]), \"not an array\")\n    assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))\n\n\ndef test_constructors():\n    defaults = m.default_constructors()\n    for a in defaults.values():\n        assert a.size == 0\n    assert defaults[\"array\"].dtype == np.array([]).dtype\n    assert defaults[\"array_t<int32>\"].dtype == np.int32\n    assert defaults[\"array_t<double>\"].dtype == np.float64\n\n    results = m.converting_constructors([1, 2, 3])\n    for a in results.values():\n        np.testing.assert_array_equal(a, [1, 2, 3])\n    assert results[\"array\"].dtype == np.dtype(int)\n    assert results[\"array_t<int32>\"].dtype == np.int32\n    assert results[\"array_t<double>\"].dtype == np.float64\n\n\ndef test_array_object_type(doc):\n    assert (\n        doc(m.pass_array_object_return_as_list)\n        == \"pass_array_object_return_as_list(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.object_]) -> list\"\n    )\n\n\ndef test_overload_resolution(msg):\n    # Exact overload matches:\n    assert m.overloaded(np.array([1], dtype=\"float64\")) == \"double\"\n    assert m.overloaded(np.array([1], dtype=\"float32\")) == \"float\"\n    assert m.overloaded(np.array([1], dtype=\"ushort\")) == \"unsigned short\"\n    assert m.overloaded(np.array([1], dtype=\"intc\")) == \"int\"\n    assert m.overloaded(np.array([1], dtype=\"longlong\")) == \"long long\"\n    assert m.overloaded(np.array([1], dtype=\"complex\")) == \"double complex\"\n    assert m.overloaded(np.array([1], dtype=\"csingle\")) == \"float complex\"\n\n    # No exact match, should call first convertible version:\n    assert m.overloaded(np.array([1], dtype=\"uint8\")) == \"double\"\n\n    with pytest.raises(TypeError) as excinfo:\n        m.overloaded(\"not an array\")\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        overloaded(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float64]) -> str\n            2. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.float32]) -> str\n            3. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.int32]) -> str\n            4. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.uint16]) -> str\n            5. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.int64]) -> str\n            6. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.complex128]) -> str\n            7. (arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.complex64]) -> str\n\n        Invoked with: 'not an array'\n    \"\"\"\n    )\n\n    assert m.overloaded2(np.array([1], dtype=\"float64\")) == \"double\"\n    assert m.overloaded2(np.array([1], dtype=\"float32\")) == \"float\"\n    assert m.overloaded2(np.array([1], dtype=\"complex64\")) == \"float complex\"\n    assert m.overloaded2(np.array([1], dtype=\"complex128\")) == \"double complex\"\n    assert m.overloaded2(np.array([1], dtype=\"float32\")) == \"float\"\n\n    assert m.overloaded3(np.array([1], dtype=\"float64\")) == \"double\"\n    assert m.overloaded3(np.array([1], dtype=\"intc\")) == \"int\"\n    expected_exc = \"\"\"\n        overloaded3(): incompatible function arguments. The following argument types are supported:\n            1. (arg0: numpy.typing.NDArray[numpy.int32]) -> str\n            2. (arg0: numpy.typing.NDArray[numpy.float64]) -> str\n\n        Invoked with: \"\"\"\n\n    with pytest.raises(TypeError) as excinfo:\n        m.overloaded3(np.array([1], dtype=\"uintc\"))\n    assert msg(excinfo.value) == expected_exc + repr(np.array([1], dtype=\"uint32\"))\n    with pytest.raises(TypeError) as excinfo:\n        m.overloaded3(np.array([1], dtype=\"float32\"))\n    assert msg(excinfo.value) == expected_exc + repr(np.array([1.0], dtype=\"float32\"))\n    with pytest.raises(TypeError) as excinfo:\n        m.overloaded3(np.array([1], dtype=\"complex\"))\n    assert msg(excinfo.value) == expected_exc + repr(np.array([1.0 + 0.0j]))\n\n    # Exact matches:\n    assert m.overloaded4(np.array([1], dtype=\"double\")) == \"double\"\n    assert m.overloaded4(np.array([1], dtype=\"longlong\")) == \"long long\"\n    # Non-exact matches requiring conversion.  Since float to integer isn't a\n    # save conversion, it should go to the double overload, but short can go to\n    # either (and so should end up on the first-registered, the long long).\n    assert m.overloaded4(np.array([1], dtype=\"float32\")) == \"double\"\n    assert m.overloaded4(np.array([1], dtype=\"short\")) == \"long long\"\n\n    assert m.overloaded5(np.array([1], dtype=\"double\")) == \"double\"\n    assert m.overloaded5(np.array([1], dtype=\"uintc\")) == \"unsigned int\"\n    assert m.overloaded5(np.array([1], dtype=\"float32\")) == \"unsigned int\"\n\n\ndef test_greedy_string_overload():\n    \"\"\"Tests fix for #685 - ndarray shouldn't go to std::string overload\"\"\"\n\n    assert m.issue685(\"abc\") == \"string\"\n    assert m.issue685(np.array([97, 98, 99], dtype=\"b\")) == \"array\"\n    assert m.issue685(123) == \"other\"\n\n\ndef test_array_unchecked_fixed_dims(msg):\n    z1 = np.array([[1, 2], [3, 4]], dtype=\"float64\")\n    m.proxy_add2(z1, 10)\n    assert np.all(z1 == [[11, 12], [13, 14]])\n\n    with pytest.raises(ValueError) as excinfo:\n        m.proxy_add2(np.array([1.0, 2, 3]), 5.0)\n    assert (\n        msg(excinfo.value) == \"array has incorrect number of dimensions: 1; expected 2\"\n    )\n\n    expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=\"int\")\n    assert np.all(m.proxy_init3(3.0) == expect_c)\n    expect_f = np.transpose(expect_c)\n    assert np.all(m.proxy_init3F(3.0) == expect_f)\n\n    assert m.proxy_squared_L2_norm(np.array(range(6))) == 55\n    assert m.proxy_squared_L2_norm(np.array(range(6), dtype=\"float64\")) == 55\n\n    assert m.proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]\n    assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)\n\n    assert m.proxy_auxiliaries1_const_ref(z1[0, :])\n    assert m.proxy_auxiliaries2_const_ref(z1)\n\n\ndef test_array_unchecked_dyn_dims():\n    z1 = np.array([[1, 2], [3, 4]], dtype=\"float64\")\n    m.proxy_add2_dyn(z1, 10)\n    assert np.all(z1 == [[11, 12], [13, 14]])\n\n    expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=\"int\")\n    assert np.all(m.proxy_init3_dyn(3.0) == expect_c)\n\n    assert m.proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]\n    assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)\n\n\ndef test_array_failure():\n    with pytest.raises(ValueError) as excinfo:\n        m.array_fail_test()\n    assert str(excinfo.value) == \"cannot create a pybind11::array from a nullptr\"\n\n    with pytest.raises(ValueError) as excinfo:\n        m.array_t_fail_test()\n    assert str(excinfo.value) == \"cannot create a pybind11::array_t from a nullptr\"\n\n    with pytest.raises(ValueError) as excinfo:\n        m.array_fail_test_negative_size()\n    assert str(excinfo.value) == \"negative dimensions are not allowed\"\n\n\ndef test_initializer_list():\n    assert m.array_initializer_list1().shape == (1,)\n    assert m.array_initializer_list2().shape == (1, 2)\n    assert m.array_initializer_list3().shape == (1, 2, 3)\n    assert m.array_initializer_list4().shape == (1, 2, 3, 4)\n\n\ndef test_array_resize():\n    a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=\"float64\")\n    m.array_reshape2(a)\n    assert a.size == 9\n    assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n\n    # total size change should succced with refcheck off\n    m.array_resize3(a, 4, False)\n    assert a.size == 64\n    # ... and fail with refcheck on\n    try:\n        m.array_resize3(a, 3, True)\n    except ValueError as e:\n        assert str(e).startswith(\"cannot resize an array\")  # noqa: PT017\n    # transposed array doesn't own data\n    b = a.transpose()\n    try:\n        m.array_resize3(b, 3, False)\n    except ValueError as e:\n        assert str(e).startswith(  # noqa: PT017\n            \"cannot resize this array: it does not own its data\"\n        )\n    # ... but reshape should be fine\n    m.array_reshape2(b)\n    assert b.shape == (8, 8)\n\n\n@pytest.mark.xfail(\"env.PYPY or env.GRAALPY\")\ndef test_array_create_and_resize():\n    a = m.create_and_resize(2)\n    assert a.size == 4\n    assert np.all(a == 42.0)\n\n\ndef test_array_view():\n    a = np.ones(100 * 4).astype(\"uint8\")\n    a_float_view = m.array_view(a, \"float32\")\n    assert a_float_view.shape == (100 * 1,)  # 1 / 4 bytes = 8 / 32\n\n    a_int16_view = m.array_view(a, \"int16\")  # 1 / 2 bytes = 16 / 32\n    assert a_int16_view.shape == (100 * 2,)\n\n\ndef test_array_view_invalid():\n    a = np.ones(100 * 4).astype(\"uint8\")\n    with pytest.raises(TypeError):\n        m.array_view(a, \"deadly_dtype\")\n\n\ndef test_reshape_initializer_list():\n    a = np.arange(2 * 7 * 3) + 1\n    x = m.reshape_initializer_list(a, 2, 7, 3)\n    assert x.shape == (2, 7, 3)\n    assert list(x[1][4]) == [34, 35, 36]\n    with pytest.raises(ValueError) as excinfo:\n        m.reshape_initializer_list(a, 1, 7, 3)\n    assert str(excinfo.value) == \"cannot reshape array of size 42 into shape (1,7,3)\"\n\n\ndef test_reshape_tuple():\n    a = np.arange(3 * 7 * 2) + 1\n    x = m.reshape_tuple(a, (3, 7, 2))\n    assert x.shape == (3, 7, 2)\n    assert list(x[1][4]) == [23, 24]\n    y = m.reshape_tuple(x, (x.size,))\n    assert y.shape == (42,)\n    with pytest.raises(ValueError) as excinfo:\n        m.reshape_tuple(a, (3, 7, 1))\n    assert str(excinfo.value) == \"cannot reshape array of size 42 into shape (3,7,1)\"\n    with pytest.raises(ValueError) as excinfo:\n        m.reshape_tuple(a, ())\n    assert str(excinfo.value) == \"cannot reshape array of size 42 into shape ()\"\n\n\ndef test_index_using_ellipsis():\n    a = m.index_using_ellipsis(np.zeros((5, 6, 7)))\n    assert a.shape == (6,)\n\n\n@pytest.mark.parametrize(\n    \"test_func\",\n    [\n        m.test_fmt_desc_float,\n        m.test_fmt_desc_double,\n        m.test_fmt_desc_const_float,\n        m.test_fmt_desc_const_double,\n    ],\n)\ndef test_format_descriptors_for_floating_point_types(test_func):\n    assert \"numpy.typing.ArrayLike, numpy.float\" in test_func.__doc__\n\n\n@pytest.mark.parametrize(\"forcecast\", [False, True])\n@pytest.mark.parametrize(\"contiguity\", [None, \"C\", \"F\"])\n@pytest.mark.parametrize(\"noconvert\", [False, True])\n@pytest.mark.filterwarnings(\n    \"ignore:Casting complex values to real discards the imaginary part:\"\n    + (\n        \"numpy.exceptions.ComplexWarning\"\n        if hasattr(np, \"exceptions\")\n        else \"numpy.ComplexWarning\"\n    )\n)\ndef test_argument_conversions(forcecast, contiguity, noconvert):\n    function_name = \"accept_double\"\n    if contiguity == \"C\":\n        function_name += \"_c_style\"\n    elif contiguity == \"F\":\n        function_name += \"_f_style\"\n    if forcecast:\n        function_name += \"_forcecast\"\n    if noconvert:\n        function_name += \"_noconvert\"\n    function = getattr(m, function_name)\n\n    for dtype in [np.dtype(\"float32\"), np.dtype(\"float64\"), np.dtype(\"complex128\")]:\n        for order in [\"C\", \"F\"]:\n            for shape in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:\n                if not noconvert:\n                    # If noconvert is not passed, only complex128 needs to be truncated and\n                    # \"cannot be safely obtained\". So without `forcecast`, the argument shouldn't\n                    # be accepted.\n                    should_raise = dtype.name == \"complex128\" and not forcecast\n                else:\n                    # If noconvert is passed, only float64 and the matching order is accepted.\n                    # If at most one dimension has a size greater than 1, the array is also\n                    # trivially contiguous.\n                    trivially_contiguous = sum(1 for d in shape if d > 1) <= 1\n                    should_raise = dtype.name != \"float64\" or (\n                        contiguity is not None\n                        and contiguity != order\n                        and not trivially_contiguous\n                    )\n\n                array = np.zeros(shape, dtype=dtype, order=order)\n                if not should_raise:\n                    function(array)\n                else:\n                    with pytest.raises(\n                        TypeError, match=\"incompatible function arguments\"\n                    ):\n                        function(array)\n\n\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_dtype_refcount_leak():\n    from sys import getrefcount\n\n    # Was np.float_ but that alias for float64 was removed in NumPy 2.\n    dtype = np.dtype(np.float64)\n    a = np.array([1], dtype=dtype)\n    before = getrefcount(dtype)\n    m.ndim(a)\n    after = getrefcount(dtype)\n    assert after == before\n\n\ndef test_round_trip_float():\n    arr = np.zeros((), np.float64)\n    arr[()] = 37.2\n    assert m.round_trip_float(arr) == 37.2\n\n\n# HINT: An easy and robust way (although only manual unfortunately) to check for\n#       ref-count leaks in the test_.*pyobject_ptr.* functions below is to\n#           * temporarily insert `while True:` (one-by-one),\n#           * run this test, and\n#           * run the Linux `top` command in another shell to visually monitor\n#             `RES` for a minute or two.\n#       If there is a leak, it is usually evident in seconds because the `RES`\n#       value increases without bounds. (Don't forget to Ctrl-C the test!)\n\n\n# For use as a temporary user-defined object, to maximize sensitivity of the tests below:\n#     * Ref-count leaks will be immediately evident.\n#     * Sanitizers are much more likely to detect heap-use-after-free due to\n#       other ref-count bugs.\nclass PyValueHolder:\n    def __init__(self, value):\n        self.value = value\n\n\ndef WrapWithPyValueHolder(*values):\n    return [PyValueHolder(v) for v in values]\n\n\ndef UnwrapPyValueHolder(vhs):\n    return [vh.value for vh in vhs]\n\n\nPASS_ARRAY_PYOBJECT_RETURN_SUM_STR_VALUES_FUNCTIONS = [\n    m.pass_array_pyobject_ptr_return_sum_str_values,\n    m.pass_array_handle_return_sum_str_values,\n    m.pass_array_object_return_sum_str_values,\n]\n\n\n@pytest.mark.parametrize(\n    \"pass_array\", PASS_ARRAY_PYOBJECT_RETURN_SUM_STR_VALUES_FUNCTIONS\n)\ndef test_pass_array_object_return_sum_str_values_ndarray(pass_array):\n    # Intentionally all temporaries, do not change.\n    assert (\n        pass_array(np.array(WrapWithPyValueHolder(-3, \"four\", 5.0), dtype=object))\n        == \"-3four5.0\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"pass_array\", PASS_ARRAY_PYOBJECT_RETURN_SUM_STR_VALUES_FUNCTIONS\n)\ndef test_pass_array_object_return_sum_str_values_list(pass_array):\n    # Intentionally all temporaries, do not change.\n    assert pass_array(WrapWithPyValueHolder(2, \"three\", -4.0)) == \"2three-4.0\"\n\n\n@pytest.mark.parametrize(\n    \"pass_array\",\n    [\n        m.pass_array_pyobject_ptr_return_as_list,\n        m.pass_array_handle_return_as_list,\n        m.pass_array_object_return_as_list,\n    ],\n)\ndef test_pass_array_object_return_as_list(pass_array):\n    # Intentionally all temporaries, do not change.\n    assert UnwrapPyValueHolder(\n        pass_array(np.array(WrapWithPyValueHolder(-1, \"two\", 3.0), dtype=object))\n    ) == [-1, \"two\", 3.0]\n\n\n@pytest.mark.parametrize(\n    (\"return_array\", \"unwrap\"),\n    [\n        (m.return_array_pyobject_ptr_cpp_loop, list),\n        (m.return_array_handle_cpp_loop, list),\n        (m.return_array_object_cpp_loop, list),\n        (m.return_array_pyobject_ptr_from_list, UnwrapPyValueHolder),\n        (m.return_array_handle_from_list, UnwrapPyValueHolder),\n        (m.return_array_object_from_list, UnwrapPyValueHolder),\n    ],\n)\ndef test_return_array_object_cpp_loop(return_array, unwrap):\n    # Intentionally all temporaries, do not change.\n    arr_from_list = return_array(WrapWithPyValueHolder(6, \"seven\", -8.0))\n    assert isinstance(arr_from_list, np.ndarray)\n    assert arr_from_list.dtype == np.dtype(\"O\")\n    assert unwrap(arr_from_list) == [6, \"seven\", -8.0]\n\n\ndef test_arraylike_signature(doc):\n    assert (\n        doc(m.round_trip_array_t)\n        == \"round_trip_array_t(x: typing.Annotated[numpy.typing.ArrayLike, numpy.float32]) -> numpy.typing.NDArray[numpy.float32]\"\n    )\n    assert (\n        doc(m.round_trip_array_t_noconvert)\n        == \"round_trip_array_t_noconvert(x: numpy.typing.NDArray[numpy.float32]) -> numpy.typing.NDArray[numpy.float32]\"\n    )\n    m.round_trip_array_t([1, 2, 3])\n    with pytest.raises(TypeError, match=\"incompatible function arguments\"):\n        m.round_trip_array_t_noconvert([1, 2, 3])\n"
  },
  {
    "path": "tests/test_numpy_dtypes.cpp",
    "content": "/*\n  tests/test_numpy_dtypes.cpp -- Structured and compound NumPy dtypes\n\n  Copyright (c) 2016 Ivan Smirnov\n\n  All rights reserved. Use of this source code is governed by a\n  BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/numpy.h>\n\n#include \"pybind11_tests.h\"\n\n#include <cstdint>\n#include <stdexcept>\n\n#ifdef __GNUC__\n#    define PYBIND11_PACKED(cls) cls __attribute__((__packed__))\n#else\n#    define PYBIND11_PACKED(cls) __pragma(pack(push, 1)) cls __pragma(pack(pop))\n#endif\n\nnamespace py = pybind11;\n\nstruct SimpleStruct {\n    bool bool_;\n    uint32_t uint_;\n    float float_;\n    long double ldbl_;\n};\n\nstd::ostream &operator<<(std::ostream &os, const SimpleStruct &v) {\n    return os << \"s:\" << v.bool_ << \",\" << v.uint_ << \",\" << v.float_ << \",\" << v.ldbl_;\n}\n\nstruct SimpleStructReordered {\n    bool bool_;\n    float float_;\n    uint32_t uint_;\n    long double ldbl_;\n};\n\nPYBIND11_PACKED(struct PackedStruct {\n    bool bool_;\n    uint32_t uint_;\n    float float_;\n    long double ldbl_;\n});\n\nstd::ostream &operator<<(std::ostream &os, const PackedStruct &v) {\n    return os << \"p:\" << v.bool_ << \",\" << v.uint_ << \",\" << v.float_ << \",\" << v.ldbl_;\n}\n\nPYBIND11_PACKED(struct NestedStruct {\n    SimpleStruct a;\n    PackedStruct b;\n});\n\nstd::ostream &operator<<(std::ostream &os, const NestedStruct &v) {\n    return os << \"n:a=\" << v.a << \";b=\" << v.b;\n}\n\nstruct PartialStruct {\n    bool bool_;\n    uint32_t uint_;\n    float float_;\n    uint64_t dummy2;\n    long double ldbl_;\n};\n\nstruct PartialNestedStruct {\n    uint64_t dummy1;\n    PartialStruct a;\n    uint64_t dummy2;\n};\n\nstruct UnboundStruct {};\n\nstruct StringStruct {\n    char a[3];\n    std::array<char, 3> b;\n};\n\nstruct ComplexStruct {\n    std::complex<float> cflt;\n    std::complex<double> cdbl;\n};\n\nstd::ostream &operator<<(std::ostream &os, const ComplexStruct &v) {\n    return os << \"c:\" << v.cflt << \",\" << v.cdbl;\n}\n\nstruct ArrayStruct {\n    char a[3][4];\n    int32_t b[2];\n    std::array<uint8_t, 3> c;\n    std::array<float, 2> d[4];\n};\n\nPYBIND11_PACKED(struct StructWithUglyNames {\n    int8_t __x__;\n    uint64_t __y__;\n});\n\nenum class E1 : int64_t { A = -1, B = 1 };\nenum E2 : uint8_t { X = 1, Y = 2 };\n\nPYBIND11_PACKED(struct EnumStruct {\n    E1 e1;\n    E2 e2;\n});\n\nstd::ostream &operator<<(std::ostream &os, const StringStruct &v) {\n    os << \"a='\";\n    for (size_t i = 0; i < 3 && (v.a[i] != 0); i++) {\n        os << v.a[i];\n    }\n    os << \"',b='\";\n    for (size_t i = 0; i < 3 && (v.b[i] != 0); i++) {\n        os << v.b[i];\n    }\n    return os << \"'\";\n}\n\nstd::ostream &operator<<(std::ostream &os, const ArrayStruct &v) {\n    os << \"a={\";\n    for (int i = 0; i < 3; i++) {\n        if (i > 0) {\n            os << ',';\n        }\n        os << '{';\n        for (int j = 0; j < 3; j++) {\n            os << v.a[i][j] << ',';\n        }\n        os << v.a[i][3] << '}';\n    }\n    os << \"},b={\" << v.b[0] << ',' << v.b[1];\n    os << \"},c={\" << int(v.c[0]) << ',' << int(v.c[1]) << ',' << int(v.c[2]);\n    os << \"},d={\";\n    for (int i = 0; i < 4; i++) {\n        if (i > 0) {\n            os << ',';\n        }\n        os << '{' << v.d[i][0] << ',' << v.d[i][1] << '}';\n    }\n    return os << '}';\n}\n\nstd::ostream &operator<<(std::ostream &os, const EnumStruct &v) {\n    return os << \"e1=\" << (v.e1 == E1::A ? \"A\" : \"B\") << \",e2=\" << (v.e2 == E2::X ? \"X\" : \"Y\");\n}\n\ntemplate <typename T>\npy::array mkarray_via_buffer(size_t n) {\n    return py::array(py::buffer_info(\n        nullptr, sizeof(T), py::format_descriptor<T>::format(), 1, {n}, {sizeof(T)}));\n}\n\n#define SET_TEST_VALS(s, i)                                                                       \\\n    do {                                                                                          \\\n        (s).bool_ = (i) % 2 != 0;                                                                 \\\n        (s).uint_ = (uint32_t) (i);                                                               \\\n        (s).float_ = (float) (i) * 1.5f;                                                          \\\n        (s).ldbl_ = (long double) (i) * -2.5L;                                                    \\\n    } while (0)\n\ntemplate <typename S>\npy::array_t<S, 0> create_recarray(size_t n) {\n    auto arr = mkarray_via_buffer<S>(n);\n    auto req = arr.request();\n    auto *ptr = static_cast<S *>(req.ptr);\n    for (size_t i = 0; i < n; i++) {\n        SET_TEST_VALS(ptr[i], i);\n    }\n    return arr;\n}\n\ntemplate <typename S>\npy::list print_recarray(const py::array_t<S, 0> &arr) {\n    const auto req = arr.request();\n    auto *const ptr = static_cast<S *>(req.ptr);\n    auto l = py::list();\n    for (py::ssize_t i = 0; i < req.size; i++) {\n        std::stringstream ss;\n        ss << ptr[i];\n        l.append(py::str(ss.str()));\n    }\n    return l;\n}\n\npy::array_t<int32_t, 0> test_array_ctors(int i) {\n    using arr_t = py::array_t<int32_t, 0>;\n\n    std::vector<int32_t> data{1, 2, 3, 4, 5, 6};\n    std::vector<py::ssize_t> shape{3, 2};\n    std::vector<py::ssize_t> strides{8, 4};\n\n    auto *ptr = data.data();\n    auto *vptr = (void *) ptr;\n    auto dtype = py::dtype(\"int32\");\n\n    py::buffer_info buf_ndim1(vptr, 4, \"i\", 6);\n    py::buffer_info buf_ndim1_null(nullptr, 4, \"i\", 6);\n    py::buffer_info buf_ndim2(vptr, 4, \"i\", 2, shape, strides);\n    py::buffer_info buf_ndim2_null(nullptr, 4, \"i\", 2, shape, strides);\n\n    auto fill = [](py::array arr) {\n        auto req = arr.request();\n        for (int i = 0; i < 6; i++) {\n            ((int32_t *) req.ptr)[i] = i + 1;\n        }\n        return arr;\n    };\n\n    switch (i) {\n        // shape: (3, 2)\n        case 10:\n            return arr_t(shape, strides, ptr);\n        case 11:\n            return py::array(shape, strides, ptr);\n        case 12:\n            return py::array(dtype, shape, strides, vptr);\n        case 13:\n            return arr_t(shape, ptr);\n        case 14:\n            return py::array(shape, ptr);\n        case 15:\n            return py::array(dtype, shape, vptr);\n        case 16:\n            return arr_t(buf_ndim2);\n        case 17:\n            return py::array(buf_ndim2);\n        // shape: (3, 2) - post-fill\n        case 20:\n            return fill(arr_t(shape, strides));\n        case 21:\n            return py::array(shape, strides, ptr); // can't have nullptr due to templated ctor\n        case 22:\n            return fill(py::array(dtype, shape, strides));\n        case 23:\n            return fill(arr_t(shape));\n        case 24:\n            return py::array(shape, ptr); // can't have nullptr due to templated ctor\n        case 25:\n            return fill(py::array(dtype, shape));\n        case 26:\n            return fill(arr_t(buf_ndim2_null));\n        case 27:\n            return fill(py::array(buf_ndim2_null));\n        // shape: (6, )\n        case 30:\n            return arr_t(6, ptr);\n        case 31:\n            return py::array(6, ptr);\n        case 32:\n            return py::array(dtype, 6, vptr);\n        case 33:\n            return arr_t(buf_ndim1);\n        case 34:\n            return py::array(buf_ndim1);\n        // shape: (6, )\n        case 40:\n            return fill(arr_t(6));\n        case 41:\n            return py::array(6, ptr); // can't have nullptr due to templated ctor\n        case 42:\n            return fill(py::array(dtype, 6));\n        case 43:\n            return fill(arr_t(buf_ndim1_null));\n        case 44:\n            return fill(py::array(buf_ndim1_null));\n        default:\n            break;\n    }\n    return arr_t();\n}\n\npy::list test_dtype_ctors() {\n    py::list list;\n    list.append(py::dtype(\"int32\"));\n    list.append(py::dtype(std::string(\"float64\")));\n    list.append(py::dtype::from_args(py::str(\"bool\")));\n    py::list names, offsets, formats;\n    py::dict dict;\n    names.append(py::str(\"a\"));\n    names.append(py::str(\"b\"));\n    dict[\"names\"] = names;\n    offsets.append(py::int_(1));\n    offsets.append(py::int_(10));\n    dict[\"offsets\"] = offsets;\n    formats.append(py::dtype(\"int32\"));\n    formats.append(py::dtype(\"float64\"));\n    dict[\"formats\"] = formats;\n    dict[\"itemsize\"] = py::int_(20);\n    list.append(py::dtype::from_args(dict));\n    list.append(py::dtype(names, formats, offsets, 20));\n    list.append(py::dtype(py::buffer_info((void *) nullptr, sizeof(unsigned int), \"I\", 1)));\n    list.append(py::dtype(py::buffer_info((void *) nullptr, 0, \"T{i:a:f:b:}\", 1)));\n    list.append(py::dtype(py::detail::npy_api::NPY_DOUBLE_));\n    return list;\n}\n\ntemplate <typename T>\npy::array_t<T> dispatch_array_increment(const py::array_t<T> &arr) {\n    py::array_t<T> res(arr.shape(0));\n    for (py::ssize_t i = 0; i < arr.shape(0); ++i) {\n        res.mutable_at(i) = T(arr.at(i) + 1);\n    }\n    return res;\n}\n\nstruct A {};\nstruct B {};\n\nTEST_SUBMODULE(numpy_dtypes, m) {\n    try {\n        py::module_::import(\"numpy\");\n    } catch (const py::error_already_set &) {\n        return;\n    }\n\n    // typeinfo may be registered before the dtype descriptor for scalar casts to work...\n    py::class_<SimpleStruct>(m, \"SimpleStruct\")\n        // Explicit construct to ensure zero-valued initialization.\n        .def(py::init([]() { return SimpleStruct(); }))\n        .def_readwrite(\"bool_\", &SimpleStruct::bool_)\n        .def_readwrite(\"uint_\", &SimpleStruct::uint_)\n        .def_readwrite(\"float_\", &SimpleStruct::float_)\n        .def_readwrite(\"ldbl_\", &SimpleStruct::ldbl_)\n        .def(\"astuple\",\n             [](const SimpleStruct &self) {\n                 return py::make_tuple(self.bool_, self.uint_, self.float_, self.ldbl_);\n             })\n        .def_static(\"fromtuple\", [](const py::tuple &tup) {\n            if (py::len(tup) != 4) {\n                throw py::cast_error(\"Invalid size\");\n            }\n            return SimpleStruct{tup[0].cast<bool>(),\n                                tup[1].cast<uint32_t>(),\n                                tup[2].cast<float>(),\n                                tup[3].cast<long double>()};\n        });\n\n    PYBIND11_NUMPY_DTYPE(SimpleStruct, bool_, uint_, float_, ldbl_);\n    PYBIND11_NUMPY_DTYPE(SimpleStructReordered, bool_, uint_, float_, ldbl_);\n    PYBIND11_NUMPY_DTYPE(PackedStruct, bool_, uint_, float_, ldbl_);\n    PYBIND11_NUMPY_DTYPE(NestedStruct, a, b);\n    PYBIND11_NUMPY_DTYPE(PartialStruct, bool_, uint_, float_, ldbl_);\n    PYBIND11_NUMPY_DTYPE(PartialNestedStruct, a);\n    PYBIND11_NUMPY_DTYPE(StringStruct, a, b);\n    PYBIND11_NUMPY_DTYPE(ArrayStruct, a, b, c, d);\n    PYBIND11_NUMPY_DTYPE(EnumStruct, e1, e2);\n    PYBIND11_NUMPY_DTYPE(ComplexStruct, cflt, cdbl);\n\n    // ... or after\n    py::class_<PackedStruct>(m, \"PackedStruct\");\n\n    PYBIND11_NUMPY_DTYPE_EX(StructWithUglyNames, __x__, \"x\", __y__, \"y\");\n\n#ifdef PYBIND11_NEVER_DEFINED_EVER\n    // If enabled, this should produce a static_assert failure telling the user that the struct\n    // is not a POD type\n    struct NotPOD {\n        std::string v;\n        NotPOD() : v(\"hi\") {};\n    };\n    PYBIND11_NUMPY_DTYPE(NotPOD, v);\n#endif\n\n    // Check that dtypes can be registered programmatically, both from\n    // initializer lists of field descriptors and from other containers.\n    py::detail::npy_format_descriptor<A>::register_dtype({});\n    py::detail::npy_format_descriptor<B>::register_dtype(\n        std::vector<py::detail::field_descriptor>{});\n\n    // test_recarray, test_scalar_conversion\n    m.def(\"create_rec_simple\", &create_recarray<SimpleStruct>);\n    m.def(\"create_rec_packed\", &create_recarray<PackedStruct>);\n    m.def(\"create_rec_nested\", [](size_t n) { // test_signature\n        py::array_t<NestedStruct, 0> arr = mkarray_via_buffer<NestedStruct>(n);\n        auto req = arr.request();\n        auto *ptr = static_cast<NestedStruct *>(req.ptr);\n        for (size_t i = 0; i < n; i++) {\n            SET_TEST_VALS(ptr[i].a, i);\n            SET_TEST_VALS(ptr[i].b, i + 1);\n        }\n        return arr;\n    });\n    m.def(\"create_rec_partial\", &create_recarray<PartialStruct>);\n    m.def(\"create_rec_partial_nested\", [](size_t n) {\n        py::array_t<PartialNestedStruct, 0> arr = mkarray_via_buffer<PartialNestedStruct>(n);\n        auto req = arr.request();\n        auto *ptr = static_cast<PartialNestedStruct *>(req.ptr);\n        for (size_t i = 0; i < n; i++) {\n            SET_TEST_VALS(ptr[i].a, i);\n        }\n        return arr;\n    });\n    m.def(\"print_rec_simple\", &print_recarray<SimpleStruct>);\n    m.def(\"print_rec_packed\", &print_recarray<PackedStruct>);\n    m.def(\"print_rec_nested\", &print_recarray<NestedStruct>);\n\n    // test_format_descriptors\n    m.def(\"get_format_unbound\", []() { return py::format_descriptor<UnboundStruct>::format(); });\n    m.def(\"print_format_descriptors\", []() {\n        py::list l;\n        for (const auto &fmt : {py::format_descriptor<SimpleStruct>::format(),\n                                py::format_descriptor<PackedStruct>::format(),\n                                py::format_descriptor<NestedStruct>::format(),\n                                py::format_descriptor<PartialStruct>::format(),\n                                py::format_descriptor<PartialNestedStruct>::format(),\n                                py::format_descriptor<StringStruct>::format(),\n                                py::format_descriptor<ArrayStruct>::format(),\n                                py::format_descriptor<EnumStruct>::format(),\n                                py::format_descriptor<ComplexStruct>::format()}) {\n            l.append(py::cast(fmt));\n        }\n        return l;\n    });\n\n    // test_dtype\n    // Below we use `L` for unsigned long as unfortunately the only name that\n    // works reliably on Both NumPy 2.x and old NumPy 1.x.\n    std::vector<const char *> dtype_names{\n        \"byte\",\n        \"short\",\n        \"intc\",\n        \"long\",\n        \"longlong\",\n        \"ubyte\",\n        \"ushort\",\n        \"uintc\",\n        \"L\",\n        \"ulonglong\",\n        \"half\",\n        \"single\",\n        \"double\",\n        \"longdouble\",\n        \"csingle\",\n        \"cdouble\",\n        \"clongdouble\",\n        \"bool_\",\n        \"datetime64\",\n        \"timedelta64\",\n        \"object_\",\n        // platform dependent aliases (int_ and uint are also NumPy version dependent on windows)\n        \"int_\",\n        \"uint\",\n        \"intp\",\n        \"uintp\"};\n\n    m.def(\"print_dtypes\", []() {\n        py::list l;\n        for (const py::handle &d : {py::dtype::of<SimpleStruct>(),\n                                    py::dtype::of<PackedStruct>(),\n                                    py::dtype::of<NestedStruct>(),\n                                    py::dtype::of<PartialStruct>(),\n                                    py::dtype::of<PartialNestedStruct>(),\n                                    py::dtype::of<StringStruct>(),\n                                    py::dtype::of<ArrayStruct>(),\n                                    py::dtype::of<EnumStruct>(),\n                                    py::dtype::of<StructWithUglyNames>(),\n                                    py::dtype::of<ComplexStruct>()}) {\n            l.append(py::str(d));\n        }\n        return l;\n    });\n    m.def(\"test_dtype_ctors\", &test_dtype_ctors);\n    m.def(\"test_dtype_kind\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).kind());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_char_\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).char_());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_num\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).num());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_byteorder\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).byteorder());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_alignment\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).alignment());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_flags\", [dtype_names]() {\n        py::list list;\n        for (const auto &dt_name : dtype_names) {\n            list.append(py::dtype(dt_name).flags());\n        }\n        return list;\n    });\n    m.def(\"test_dtype_num_of\", []() -> py::list {\n        py::list res;\n#define TEST_DTYPE(T) res.append(py::make_tuple(py::dtype::of<T>().num(), py::dtype::num_of<T>()));\n        TEST_DTYPE(bool)\n        TEST_DTYPE(signed char)\n        TEST_DTYPE(unsigned char)\n        TEST_DTYPE(short)\n        TEST_DTYPE(unsigned short)\n        TEST_DTYPE(int)\n        TEST_DTYPE(unsigned int)\n        TEST_DTYPE(long)\n        TEST_DTYPE(unsigned long)\n        TEST_DTYPE(long long)\n        TEST_DTYPE(unsigned long long)\n        TEST_DTYPE(float)\n        TEST_DTYPE(double)\n        TEST_DTYPE(long double)\n        TEST_DTYPE(std::complex<float>)\n        TEST_DTYPE(std::complex<double>)\n        TEST_DTYPE(std::complex<long double>)\n        TEST_DTYPE(int8_t)\n        TEST_DTYPE(uint8_t)\n        TEST_DTYPE(int16_t)\n        TEST_DTYPE(uint16_t)\n        TEST_DTYPE(int32_t)\n        TEST_DTYPE(uint32_t)\n        TEST_DTYPE(int64_t)\n        TEST_DTYPE(uint64_t)\n#undef TEST_DTYPE\n        return res;\n    });\n    m.def(\"test_dtype_normalized_num\", []() -> py::list {\n        py::list res;\n#define TEST_DTYPE(NT, T)                                                                         \\\n    res.append(py::make_tuple(py::dtype(py::detail::npy_api::NT).normalized_num(),                \\\n                              py::dtype::num_of<T>()));\n        TEST_DTYPE(NPY_BOOL_, bool)\n        TEST_DTYPE(NPY_BYTE_, signed char);\n        TEST_DTYPE(NPY_UBYTE_, unsigned char);\n        TEST_DTYPE(NPY_SHORT_, short);\n        TEST_DTYPE(NPY_USHORT_, unsigned short);\n        TEST_DTYPE(NPY_INT_, int);\n        TEST_DTYPE(NPY_UINT_, unsigned int);\n        TEST_DTYPE(NPY_LONG_, long);\n        TEST_DTYPE(NPY_ULONG_, unsigned long);\n        TEST_DTYPE(NPY_LONGLONG_, long long);\n        TEST_DTYPE(NPY_ULONGLONG_, unsigned long long);\n        TEST_DTYPE(NPY_FLOAT_, float);\n        TEST_DTYPE(NPY_DOUBLE_, double);\n        TEST_DTYPE(NPY_LONGDOUBLE_, long double);\n        TEST_DTYPE(NPY_CFLOAT_, std::complex<float>);\n        TEST_DTYPE(NPY_CDOUBLE_, std::complex<double>);\n        TEST_DTYPE(NPY_CLONGDOUBLE_, std::complex<long double>);\n        TEST_DTYPE(NPY_INT8_, int8_t);\n        TEST_DTYPE(NPY_UINT8_, uint8_t);\n        TEST_DTYPE(NPY_INT16_, int16_t);\n        TEST_DTYPE(NPY_UINT16_, uint16_t);\n        TEST_DTYPE(NPY_INT32_, int32_t);\n        TEST_DTYPE(NPY_UINT32_, uint32_t);\n        TEST_DTYPE(NPY_INT64_, int64_t);\n        TEST_DTYPE(NPY_UINT64_, uint64_t);\n#undef TEST_DTYPE\n        return res;\n    });\n    m.def(\"test_dtype_switch\", [](const py::array &arr) -> py::array {\n        switch (arr.dtype().normalized_num()) {\n            case py::dtype::num_of<int8_t>():\n                return dispatch_array_increment<int8_t>(arr);\n            case py::dtype::num_of<uint8_t>():\n                return dispatch_array_increment<uint8_t>(arr);\n            case py::dtype::num_of<int16_t>():\n                return dispatch_array_increment<int16_t>(arr);\n            case py::dtype::num_of<uint16_t>():\n                return dispatch_array_increment<uint16_t>(arr);\n            case py::dtype::num_of<int32_t>():\n                return dispatch_array_increment<int32_t>(arr);\n            case py::dtype::num_of<uint32_t>():\n                return dispatch_array_increment<uint32_t>(arr);\n            case py::dtype::num_of<int64_t>():\n                return dispatch_array_increment<int64_t>(arr);\n            case py::dtype::num_of<uint64_t>():\n                return dispatch_array_increment<uint64_t>(arr);\n            case py::dtype::num_of<float>():\n                return dispatch_array_increment<float>(arr);\n            case py::dtype::num_of<double>():\n                return dispatch_array_increment<double>(arr);\n            case py::dtype::num_of<long double>():\n                return dispatch_array_increment<long double>(arr);\n            default:\n                throw std::runtime_error(\"Unsupported dtype\");\n        }\n    });\n    m.def(\"test_dtype_methods\", []() {\n        py::list list;\n        auto dt1 = py::dtype::of<int32_t>();\n        auto dt2 = py::dtype::of<SimpleStruct>();\n        list.append(dt1);\n        list.append(dt2);\n        list.append(py::bool_(dt1.has_fields()));\n        list.append(py::bool_(dt2.has_fields()));\n        list.append(py::int_(dt1.itemsize()));\n        list.append(py::int_(dt2.itemsize()));\n        return list;\n    });\n    struct TrailingPaddingStruct {\n        int32_t a;\n        char b;\n    };\n    PYBIND11_NUMPY_DTYPE(TrailingPaddingStruct, a, b);\n    m.def(\"trailing_padding_dtype\", []() { return py::dtype::of<TrailingPaddingStruct>(); });\n\n    // test_string_array\n    m.def(\"create_string_array\", [](bool non_empty) {\n        py::array_t<StringStruct, 0> arr = mkarray_via_buffer<StringStruct>(non_empty ? 4 : 0);\n        if (non_empty) {\n            auto req = arr.request();\n            auto *ptr = static_cast<StringStruct *>(req.ptr);\n            for (py::ssize_t i = 0; i < req.size * req.itemsize; i++) {\n                static_cast<char *>(req.ptr)[i] = 0;\n            }\n            ptr[1].a[0] = 'a';\n            ptr[1].b[0] = 'a';\n            ptr[2].a[0] = 'a';\n            ptr[2].b[0] = 'a';\n            ptr[3].a[0] = 'a';\n            ptr[3].b[0] = 'a';\n\n            ptr[2].a[1] = 'b';\n            ptr[2].b[1] = 'b';\n            ptr[3].a[1] = 'b';\n            ptr[3].b[1] = 'b';\n\n            ptr[3].a[2] = 'c';\n            ptr[3].b[2] = 'c';\n        }\n        return arr;\n    });\n    m.def(\"print_string_array\", &print_recarray<StringStruct>);\n\n    // test_array_array\n    m.def(\"create_array_array\", [](size_t n) {\n        py::array_t<ArrayStruct, 0> arr = mkarray_via_buffer<ArrayStruct>(n);\n        auto *ptr = (ArrayStruct *) arr.mutable_data();\n        for (size_t i = 0; i < n; i++) {\n            for (size_t j = 0; j < 3; j++) {\n                for (size_t k = 0; k < 4; k++) {\n                    ptr[i].a[j][k] = char('A' + (i * 100 + j * 10 + k) % 26);\n                }\n            }\n            for (size_t j = 0; j < 2; j++) {\n                ptr[i].b[j] = int32_t(i * 1000 + j);\n            }\n            for (size_t j = 0; j < 3; j++) {\n                ptr[i].c[j] = uint8_t(i * 10 + j);\n            }\n            for (size_t j = 0; j < 4; j++) {\n                for (size_t k = 0; k < 2; k++) {\n                    ptr[i].d[j][k] = float(i) * 100.0f + float(j) * 10.0f + float(k);\n                }\n            }\n        }\n        return arr;\n    });\n    m.def(\"print_array_array\", &print_recarray<ArrayStruct>);\n\n    // test_enum_array\n    m.def(\"create_enum_array\", [](size_t n) {\n        py::array_t<EnumStruct, 0> arr = mkarray_via_buffer<EnumStruct>(n);\n        auto *ptr = (EnumStruct *) arr.mutable_data();\n        for (size_t i = 0; i < n; i++) {\n            ptr[i].e1 = static_cast<E1>(-1 + ((int) i % 2) * 2);\n            ptr[i].e2 = static_cast<E2>(1 + (i % 2));\n        }\n        return arr;\n    });\n    m.def(\"print_enum_array\", &print_recarray<EnumStruct>);\n\n    // test_complex_array\n    m.def(\"create_complex_array\", [](size_t n) {\n        py::array_t<ComplexStruct, 0> arr = mkarray_via_buffer<ComplexStruct>(n);\n        auto *ptr = (ComplexStruct *) arr.mutable_data();\n        for (size_t i = 0; i < n; i++) {\n            ptr[i].cflt.real(float(i));\n            ptr[i].cflt.imag(float(i) + 0.25f);\n            ptr[i].cdbl.real(double(i) + 0.5);\n            ptr[i].cdbl.imag(double(i) + 0.75);\n        }\n        return arr;\n    });\n    m.def(\"print_complex_array\", &print_recarray<ComplexStruct>);\n\n    // test_array_constructors\n    m.def(\"test_array_ctors\", &test_array_ctors);\n\n    // test_compare_buffer_info\n    struct CompareStruct {\n        bool x;\n        uint32_t y;\n        float z;\n    };\n    PYBIND11_NUMPY_DTYPE(CompareStruct, x, y, z);\n    m.def(\"compare_buffer_info\", []() {\n        py::list list;\n        list.append(py::bool_(py::detail::compare_buffer_info<float>::compare(\n            py::buffer_info(nullptr, sizeof(float), \"f\", 1))));\n        list.append(py::bool_(py::detail::compare_buffer_info<unsigned>::compare(\n            py::buffer_info(nullptr, sizeof(int), \"I\", 1))));\n        list.append(py::bool_(py::detail::compare_buffer_info<long>::compare(\n            py::buffer_info(nullptr, sizeof(long), \"l\", 1))));\n        list.append(py::bool_(py::detail::compare_buffer_info<long>::compare(\n            py::buffer_info(nullptr, sizeof(long), sizeof(long) == sizeof(int) ? \"i\" : \"q\", 1))));\n        list.append(py::bool_(py::detail::compare_buffer_info<CompareStruct>::compare(\n            py::buffer_info(nullptr, sizeof(CompareStruct), \"T{?:x:3xI:y:f:z:}\", 1))));\n        return list;\n    });\n    m.def(\"buffer_to_dtype\", [](py::buffer &buf) { return py::dtype(buf.request()); });\n\n    // test_scalar_conversion\n    auto f_simple = [](SimpleStruct s) { return s.uint_ * 10; };\n    m.def(\"f_simple\", f_simple);\n    m.def(\"f_packed\", [](PackedStruct s) { return s.uint_ * 10; });\n    m.def(\"f_nested\", [](NestedStruct s) { return s.a.uint_ * 10; });\n\n    // test_vectorize\n    m.def(\"f_simple_vectorized\", py::vectorize(f_simple));\n    auto f_simple_pass_thru = [](SimpleStruct s) { return s; };\n    m.def(\"f_simple_pass_thru_vectorized\", py::vectorize(f_simple_pass_thru));\n\n    // test_register_dtype\n    m.def(\"register_dtype\",\n          []() { PYBIND11_NUMPY_DTYPE(SimpleStruct, bool_, uint_, float_, ldbl_); });\n\n    // test_str_leak\n    m.def(\"dtype_wrapper\", [](const py::object &d) { return py::dtype::from_args(d); });\n}\n"
  },
  {
    "path": "tests/test_numpy_dtypes.py",
    "content": "from __future__ import annotations\n\nimport re\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import numpy_dtypes as m\n\nnp = pytest.importorskip(\"numpy\")\n\n\n@pytest.fixture(scope=\"module\")\ndef simple_dtype():\n    ld = np.dtype(\"longdouble\")\n    return np.dtype(\n        {\n            \"names\": [\"bool_\", \"uint_\", \"float_\", \"ldbl_\"],\n            \"formats\": [\"?\", \"u4\", \"f4\", f\"f{ld.itemsize}\"],\n            \"offsets\": [0, 4, 8, (16 if ld.alignment > 4 else 12)],\n        }\n    )\n\n\n@pytest.fixture(scope=\"module\")\ndef packed_dtype():\n    return np.dtype([(\"bool_\", \"?\"), (\"uint_\", \"u4\"), (\"float_\", \"f4\"), (\"ldbl_\", \"g\")])\n\n\ndef dt_fmt():\n    from sys import byteorder\n\n    e = \"<\" if byteorder == \"little\" else \">\"\n    return (\n        \"{{'names':['bool_','uint_','float_','ldbl_'],\"\n        \"'formats':['?','\" + e + \"u4','\" + e + \"f4','\" + e + \"f{}'],\"\n        \"'offsets':[0,4,8,{}],'itemsize':{}}}\"\n    )\n\n\ndef simple_dtype_fmt():\n    ld = np.dtype(\"longdouble\")\n    simple_ld_off = 12 + 4 * (ld.alignment > 4)\n    return dt_fmt().format(ld.itemsize, simple_ld_off, simple_ld_off + ld.itemsize)\n\n\ndef packed_dtype_fmt():\n    from sys import byteorder\n\n    return \"[('bool_','?'),('uint_','{e}u4'),('float_','{e}f4'),('ldbl_','{e}f{}')]\".format(\n        np.dtype(\"longdouble\").itemsize, e=\"<\" if byteorder == \"little\" else \">\"\n    )\n\n\ndef partial_ld_offset():\n    return (\n        12\n        + 4 * (np.dtype(\"uint64\").alignment > 4)\n        + 8\n        + 8 * (np.dtype(\"longdouble\").alignment > 8)\n    )\n\n\ndef partial_dtype_fmt():\n    ld = np.dtype(\"longdouble\")\n    partial_ld_off = partial_ld_offset()\n    partial_size = partial_ld_off + ld.itemsize\n    partial_end_padding = partial_size % np.dtype(\"uint64\").alignment\n    return dt_fmt().format(\n        ld.itemsize, partial_ld_off, partial_size + partial_end_padding\n    )\n\n\ndef partial_nested_fmt():\n    ld = np.dtype(\"longdouble\")\n    partial_nested_off = 8 + 8 * (ld.alignment > 8)\n    partial_ld_off = partial_ld_offset()\n    partial_size = partial_ld_off + ld.itemsize\n    partial_end_padding = partial_size % np.dtype(\"uint64\").alignment\n    partial_nested_size = partial_nested_off * 2 + partial_size + partial_end_padding\n    return f\"{{'names':['a'],'formats':[{partial_dtype_fmt()}],'offsets':[{partial_nested_off}],'itemsize':{partial_nested_size}}}\"\n\n\ndef assert_equal(actual, expected_data, expected_dtype):\n    np.testing.assert_equal(actual, np.array(expected_data, dtype=expected_dtype))\n\n\ndef test_format_descriptors():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.get_format_unbound()\n    assert re.match(\n        \"^NumPy type info missing for .*UnboundStruct.*$\", str(excinfo.value)\n    )\n\n    ld = np.dtype(\"longdouble\")\n    ldbl_fmt = (\"4x\" if ld.alignment > 4 else \"\") + ld.char\n    ss_fmt = \"^T{?:bool_:3xI:uint_:f:float_:\" + ldbl_fmt + \":ldbl_:}\"\n    dbl = np.dtype(\"double\")\n    end_padding = ld.itemsize % np.dtype(\"uint64\").alignment\n    partial_fmt = (\n        \"^T{?:bool_:3xI:uint_:f:float_:\"\n        + str(4 * (dbl.alignment > 4) + dbl.itemsize + 8 * (ld.alignment > 8))\n        + \"xg:ldbl_:\"\n        + (str(end_padding) + \"x}\" if end_padding > 0 else \"}\")\n    )\n    nested_extra = str(max(8, ld.alignment))\n    assert m.print_format_descriptors() == [\n        ss_fmt,\n        \"^T{?:bool_:I:uint_:f:float_:g:ldbl_:}\",\n        \"^T{\" + ss_fmt + \":a:^T{?:bool_:I:uint_:f:float_:g:ldbl_:}:b:}\",\n        partial_fmt,\n        \"^T{\" + nested_extra + \"x\" + partial_fmt + \":a:\" + nested_extra + \"x}\",\n        \"^T{3s:a:3s:b:}\",\n        \"^T{(3)4s:a:(2)i:b:(3)B:c:1x(4, 2)f:d:}\",\n        \"^T{q:e1:B:e2:}\",\n        \"^T{Zf:cflt:Zd:cdbl:}\",\n    ]\n\n\ndef test_dtype(simple_dtype):\n    from sys import byteorder\n\n    e = \"<\" if byteorder == \"little\" else \">\"\n\n    assert [x.replace(\" \", \"\") for x in m.print_dtypes()] == [\n        simple_dtype_fmt(),\n        packed_dtype_fmt(),\n        f\"[('a',{simple_dtype_fmt()}),('b',{packed_dtype_fmt()})]\",\n        partial_dtype_fmt(),\n        partial_nested_fmt(),\n        \"[('a','S3'),('b','S3')]\",\n        (\n            \"{'names':['a','b','c','d'],\"\n            f\"'formats':[('S4',(3,)),('{e}i4',(2,)),('u1',(3,)),('{e}f4',(4,2))],\"\n            \"'offsets':[0,12,20,24],'itemsize':56}\"\n        ),\n        \"[('e1','\" + e + \"i8'),('e2','u1')]\",\n        \"[('x','i1'),('y','\" + e + \"u8')]\",\n        \"[('cflt','\" + e + \"c8'),('cdbl','\" + e + \"c16')]\",\n    ]\n\n    d1 = np.dtype(\n        {\n            \"names\": [\"a\", \"b\"],\n            \"formats\": [\"int32\", \"float64\"],\n            \"offsets\": [1, 10],\n            \"itemsize\": 20,\n        }\n    )\n    d2 = np.dtype([(\"a\", \"i4\"), (\"b\", \"f4\")])\n    assert m.test_dtype_ctors() == [\n        np.dtype(\"int32\"),\n        np.dtype(\"float64\"),\n        np.dtype(\"bool\"),\n        d1,\n        d1,\n        np.dtype(\"uint32\"),\n        d2,\n        np.dtype(\"d\"),\n    ]\n\n    assert m.test_dtype_methods() == [\n        np.dtype(\"int32\"),\n        simple_dtype,\n        False,\n        True,\n        np.dtype(\"int32\").itemsize,\n        simple_dtype.itemsize,\n    ]\n\n    assert m.trailing_padding_dtype() == m.buffer_to_dtype(\n        np.zeros(1, m.trailing_padding_dtype())\n    )\n\n    expected_chars = list(\"bhilqBHILQefdgFDG?MmO\")\n    # Note that int_ and uint size and mapping is NumPy version dependent:\n    expected_chars += [np.dtype(_).char for _ in (\"int_\", \"uint\", \"intp\", \"uintp\")]\n    assert m.test_dtype_kind() == list(\"iiiiiuuuuuffffcccbMmOiuiu\")\n    assert m.test_dtype_char_() == list(expected_chars)\n    assert m.test_dtype_num() == [np.dtype(ch).num for ch in expected_chars]\n    assert m.test_dtype_byteorder() == [np.dtype(ch).byteorder for ch in expected_chars]\n    assert m.test_dtype_alignment() == [np.dtype(ch).alignment for ch in expected_chars]\n    assert m.test_dtype_flags() == [np.dtype(ch).flags for ch in expected_chars]\n\n    for a, b in m.test_dtype_num_of():\n        assert a == b\n\n    for a, b in m.test_dtype_normalized_num():\n        assert a == b\n\n    arr = np.array([4, 84, 21, 36])\n    # Note: \"ulong\" does not work in NumPy 1.x, so we use \"L\"\n    assert (m.test_dtype_switch(arr.astype(\"byte\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"ubyte\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"short\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"ushort\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"intc\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"uintc\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"long\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"L\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"longlong\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"ulonglong\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"single\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"double\")) == arr + 1).all()\n    assert (m.test_dtype_switch(arr.astype(\"longdouble\")) == arr + 1).all()\n\n\ndef test_recarray(simple_dtype, packed_dtype):\n    elements = [(False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)]\n\n    for func, dtype in [\n        (m.create_rec_simple, simple_dtype),\n        (m.create_rec_packed, packed_dtype),\n    ]:\n        arr = func(0)\n        assert arr.dtype == dtype\n        assert_equal(arr, [], simple_dtype)\n        assert_equal(arr, [], packed_dtype)\n\n        arr = func(3)\n        assert arr.dtype == dtype\n        assert_equal(arr, elements, simple_dtype)\n        assert_equal(arr, elements, packed_dtype)\n\n        # Show what recarray's look like in NumPy.\n        assert type(arr[0]) == np.void\n        assert type(arr[0].item()) == tuple\n\n        if dtype == simple_dtype:\n            assert m.print_rec_simple(arr) == [\n                \"s:0,0,0,-0\",\n                \"s:1,1,1.5,-2.5\",\n                \"s:0,2,3,-5\",\n            ]\n        else:\n            assert m.print_rec_packed(arr) == [\n                \"p:0,0,0,-0\",\n                \"p:1,1,1.5,-2.5\",\n                \"p:0,2,3,-5\",\n            ]\n\n    nested_dtype = np.dtype([(\"a\", simple_dtype), (\"b\", packed_dtype)])\n\n    arr = m.create_rec_nested(0)\n    assert arr.dtype == nested_dtype\n    assert_equal(arr, [], nested_dtype)\n\n    arr = m.create_rec_nested(3)\n    assert arr.dtype == nested_dtype\n    assert_equal(\n        arr,\n        [\n            ((False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5)),\n            ((True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)),\n            ((False, 2, 3.0, -5.0), (True, 3, 4.5, -7.5)),\n        ],\n        nested_dtype,\n    )\n    assert m.print_rec_nested(arr) == [\n        \"n:a=s:0,0,0,-0;b=p:1,1,1.5,-2.5\",\n        \"n:a=s:1,1,1.5,-2.5;b=p:0,2,3,-5\",\n        \"n:a=s:0,2,3,-5;b=p:1,3,4.5,-7.5\",\n    ]\n\n    arr = m.create_rec_partial(3)\n    assert str(arr.dtype).replace(\" \", \"\") == partial_dtype_fmt()\n    partial_dtype = arr.dtype\n    assert \"\" not in arr.dtype.fields\n    assert partial_dtype.itemsize > simple_dtype.itemsize\n    assert_equal(arr, elements, simple_dtype)\n    assert_equal(arr, elements, packed_dtype)\n\n    arr = m.create_rec_partial_nested(3)\n    assert str(arr.dtype).replace(\" \", \"\") == partial_nested_fmt()\n    assert \"\" not in arr.dtype.fields\n    assert \"\" not in arr.dtype.fields[\"a\"][0].fields\n    assert arr.dtype.itemsize > partial_dtype.itemsize\n    np.testing.assert_equal(arr[\"a\"], m.create_rec_partial(3))\n\n\ndef test_array_constructors():\n    data = np.arange(1, 7, dtype=\"int32\")\n    for i in range(8):\n        np.testing.assert_array_equal(m.test_array_ctors(10 + i), data.reshape((3, 2)))\n        np.testing.assert_array_equal(m.test_array_ctors(20 + i), data.reshape((3, 2)))\n    for i in range(5):\n        np.testing.assert_array_equal(m.test_array_ctors(30 + i), data)\n        np.testing.assert_array_equal(m.test_array_ctors(40 + i), data)\n\n\ndef test_string_array():\n    arr = m.create_string_array(True)\n    assert str(arr.dtype) == \"[('a', 'S3'), ('b', 'S3')]\"\n    assert m.print_string_array(arr) == [\n        \"a='',b=''\",\n        \"a='a',b='a'\",\n        \"a='ab',b='ab'\",\n        \"a='abc',b='abc'\",\n    ]\n    dtype = arr.dtype\n    assert arr[\"a\"].tolist() == [b\"\", b\"a\", b\"ab\", b\"abc\"]\n    assert arr[\"b\"].tolist() == [b\"\", b\"a\", b\"ab\", b\"abc\"]\n    arr = m.create_string_array(False)\n    assert dtype == arr.dtype\n\n\ndef test_array_array():\n    from sys import byteorder\n\n    e = \"<\" if byteorder == \"little\" else \">\"\n\n    arr = m.create_array_array(3)\n    assert str(arr.dtype).replace(\" \", \"\") == (\n        \"{'names':['a','b','c','d'],\"\n        f\"'formats':[('S4',(3,)),('{e}i4',(2,)),('u1',(3,)),('{e}f4',(4,2))],\"\n        \"'offsets':[0,12,20,24],'itemsize':56}\"\n    )\n    assert m.print_array_array(arr) == [\n        \"a={{A,B,C,D},{K,L,M,N},{U,V,W,X}},b={0,1},\"\n        \"c={0,1,2},d={{0,1},{10,11},{20,21},{30,31}}\",\n        \"a={{W,X,Y,Z},{G,H,I,J},{Q,R,S,T}},b={1000,1001},\"\n        \"c={10,11,12},d={{100,101},{110,111},{120,121},{130,131}}\",\n        \"a={{S,T,U,V},{C,D,E,F},{M,N,O,P}},b={2000,2001},\"\n        \"c={20,21,22},d={{200,201},{210,211},{220,221},{230,231}}\",\n    ]\n    assert arr[\"a\"].tolist() == [\n        [b\"ABCD\", b\"KLMN\", b\"UVWX\"],\n        [b\"WXYZ\", b\"GHIJ\", b\"QRST\"],\n        [b\"STUV\", b\"CDEF\", b\"MNOP\"],\n    ]\n    assert arr[\"b\"].tolist() == [[0, 1], [1000, 1001], [2000, 2001]]\n    assert m.create_array_array(0).dtype == arr.dtype\n\n\ndef test_enum_array():\n    from sys import byteorder\n\n    e = \"<\" if byteorder == \"little\" else \">\"\n\n    arr = m.create_enum_array(3)\n    dtype = arr.dtype\n    assert dtype == np.dtype([(\"e1\", e + \"i8\"), (\"e2\", \"u1\")])\n    assert m.print_enum_array(arr) == [\"e1=A,e2=X\", \"e1=B,e2=Y\", \"e1=A,e2=X\"]\n    assert arr[\"e1\"].tolist() == [-1, 1, -1]\n    assert arr[\"e2\"].tolist() == [1, 2, 1]\n    assert m.create_enum_array(0).dtype == dtype\n\n\ndef test_complex_array():\n    from sys import byteorder\n\n    e = \"<\" if byteorder == \"little\" else \">\"\n\n    arr = m.create_complex_array(3)\n    dtype = arr.dtype\n    assert dtype == np.dtype([(\"cflt\", e + \"c8\"), (\"cdbl\", e + \"c16\")])\n    assert m.print_complex_array(arr) == [\n        \"c:(0,0.25),(0.5,0.75)\",\n        \"c:(1,1.25),(1.5,1.75)\",\n        \"c:(2,2.25),(2.5,2.75)\",\n    ]\n    assert arr[\"cflt\"].tolist() == [0.0 + 0.25j, 1.0 + 1.25j, 2.0 + 2.25j]\n    assert arr[\"cdbl\"].tolist() == [0.5 + 0.75j, 1.5 + 1.75j, 2.5 + 2.75j]\n    assert m.create_complex_array(0).dtype == dtype\n\n\ndef test_signature(doc):\n    assert (\n        doc(m.create_rec_nested)\n        == \"create_rec_nested(arg0: typing.SupportsInt | typing.SupportsIndex) -> numpy.typing.NDArray[NestedStruct]\"\n    )\n\n\ndef test_scalar_conversion():\n    n = 3\n    arrays = [\n        m.create_rec_simple(n),\n        m.create_rec_packed(n),\n        m.create_rec_nested(n),\n        m.create_enum_array(n),\n    ]\n    funcs = [m.f_simple, m.f_packed, m.f_nested]\n\n    for i, func in enumerate(funcs):\n        for j, arr in enumerate(arrays):\n            if i == j and i < 2:\n                assert [func(arr[k]) for k in range(n)] == [k * 10 for k in range(n)]\n            else:\n                with pytest.raises(TypeError) as excinfo:\n                    func(arr[0])\n                assert \"incompatible function arguments\" in str(excinfo.value)\n\n\ndef test_vectorize():\n    n = 3\n    array = m.create_rec_simple(n)\n    values = m.f_simple_vectorized(array)\n    np.testing.assert_array_equal(values, [0, 10, 20])\n    array_2 = m.f_simple_pass_thru_vectorized(array)\n    np.testing.assert_array_equal(array, array_2)\n\n\ndef test_cls_and_dtype_conversion(simple_dtype):\n    s = m.SimpleStruct()\n    assert s.astuple() == (False, 0, 0.0, 0.0)\n    assert m.SimpleStruct.fromtuple(s.astuple()).astuple() == s.astuple()\n\n    s.uint_ = 2\n    assert m.f_simple(s) == 20\n\n    # Try as recarray of shape==(1,).\n    s_recarray = np.array([(False, 2, 0.0, 0.0)], dtype=simple_dtype)\n    # Show that this will work for vectorized case.\n    np.testing.assert_array_equal(m.f_simple_vectorized(s_recarray), [20])\n\n    # Show as a scalar that inherits from np.generic.\n    s_scalar = s_recarray[0]\n    assert isinstance(s_scalar, np.void)\n    assert m.f_simple(s_scalar) == 20\n\n    # Show that an *array* scalar (np.ndarray.shape == ()) does not convert.\n    # More specifically, conversion to SimpleStruct is not implicit.\n    s_recarray_scalar = s_recarray.reshape(())\n    assert isinstance(s_recarray_scalar, np.ndarray)\n    assert s_recarray_scalar.dtype == simple_dtype\n    with pytest.raises(TypeError) as excinfo:\n        m.f_simple(s_recarray_scalar)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    # Explicitly convert to m.SimpleStruct.\n    assert m.f_simple(m.SimpleStruct.fromtuple(s_recarray_scalar.item())) == 20\n\n    # Show that an array of dtype=object does *not* convert.\n    s_array_object = np.array([s])\n    assert s_array_object.dtype == object\n    with pytest.raises(TypeError) as excinfo:\n        m.f_simple_vectorized(s_array_object)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n    # Explicitly convert to `np.array(..., dtype=simple_dtype)`\n    s_array = np.array([s.astuple()], dtype=simple_dtype)\n    np.testing.assert_array_equal(m.f_simple_vectorized(s_array), [20])\n\n\ndef test_register_dtype():\n    with pytest.raises(RuntimeError) as excinfo:\n        m.register_dtype()\n    assert \"dtype is already registered\" in str(excinfo.value)\n\n\n@pytest.mark.xfail(\"env.PYPY\")\ndef test_str_leak():\n    from sys import getrefcount\n\n    fmt = \"f4\"\n    pytest.gc_collect()\n    start = getrefcount(fmt)\n    d = m.dtype_wrapper(fmt)\n    assert d is np.dtype(\"f4\")\n    del d\n    pytest.gc_collect()\n    assert getrefcount(fmt) == start\n\n\ndef test_compare_buffer_info():\n    assert all(m.compare_buffer_info())\n"
  },
  {
    "path": "tests/test_numpy_scalars.cpp",
    "content": "/*\n  tests/test_numpy_scalars.cpp -- strict NumPy scalars\n\n  Copyright (c) 2021 Steve R. Sun\n\n  All rights reserved. Use of this source code is governed by a\n  BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/numpy.h>\n\n#include \"pybind11_tests.h\"\n\n#include <complex>\n#include <cstdint>\n\nnamespace py = pybind11;\n\nnamespace pybind11_test_numpy_scalars {\n\ntemplate <typename T>\nstruct add {\n    T x;\n    explicit add(T x) : x(x) {}\n    T operator()(T y) const { return static_cast<T>(x + y); }\n};\n\ntemplate <typename T, typename F>\nvoid register_test(py::module &m, const char *name, F &&func) {\n    m.def((std::string(\"test_\") + name).c_str(),\n          [=](py::numpy_scalar<T> v) {\n              return std::make_tuple(name, py::make_scalar(static_cast<T>(func(v.value))));\n          },\n          py::arg(\"x\"));\n}\n\n} // namespace pybind11_test_numpy_scalars\n\nusing namespace pybind11_test_numpy_scalars;\n\nTEST_SUBMODULE(numpy_scalars, m) {\n    using cfloat = std::complex<float>;\n    using cdouble = std::complex<double>;\n\n    register_test<bool>(m, \"bool\", [](bool x) { return !x; });\n    register_test<int8_t>(m, \"int8\", add<int8_t>(-8));\n    register_test<int16_t>(m, \"int16\", add<int16_t>(-16));\n    register_test<int32_t>(m, \"int32\", add<int32_t>(-32));\n    register_test<int64_t>(m, \"int64\", add<int64_t>(-64));\n    register_test<uint8_t>(m, \"uint8\", add<uint8_t>(8));\n    register_test<uint16_t>(m, \"uint16\", add<uint16_t>(16));\n    register_test<uint32_t>(m, \"uint32\", add<uint32_t>(32));\n    register_test<uint64_t>(m, \"uint64\", add<uint64_t>(64));\n    register_test<float>(m, \"float32\", add<float>(0.125f));\n    register_test<double>(m, \"float64\", add<double>(0.25f));\n    register_test<cfloat>(m, \"complex64\", add<cfloat>({0, -0.125f}));\n    register_test<cdouble>(m, \"complex128\", add<cdouble>({0, -0.25f}));\n\n    m.def(\"test_eq\",\n          [](py::numpy_scalar<int32_t> a, py::numpy_scalar<int32_t> b) { return a == b; });\n    m.def(\"test_ne\",\n          [](py::numpy_scalar<int32_t> a, py::numpy_scalar<int32_t> b) { return a != b; });\n}\n"
  },
  {
    "path": "tests/test_numpy_scalars.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import numpy_scalars as m\n\nnp = pytest.importorskip(\"numpy\")\n\nNPY_SCALAR_TYPES = {\n    np.bool_: False,\n    np.int8: -7,\n    np.int16: -15,\n    np.int32: -31,\n    np.int64: -63,\n    np.uint8: 9,\n    np.uint16: 17,\n    np.uint32: 33,\n    np.uint64: 65,\n    np.single: 1.125,\n    np.double: 1.25,\n    np.complex64: 1 - 0.125j,\n    np.complex128: 1 - 0.25j,\n}\n\nALL_SCALAR_TYPES = tuple(NPY_SCALAR_TYPES.keys()) + (int, bool, float, bytes, str)\n\n\n@pytest.mark.parametrize(\n    (\"npy_scalar_type\", \"expected_value\"), NPY_SCALAR_TYPES.items()\n)\ndef test_numpy_scalars(npy_scalar_type, expected_value):\n    tpnm = npy_scalar_type.__name__.rstrip(\"_\")\n    test_tpnm = getattr(m, \"test_\" + tpnm)\n    assert (\n        test_tpnm.__doc__\n        == f\"test_{tpnm}(x: numpy.{tpnm}) -> tuple[str, numpy.{tpnm}]\\n\"\n    )\n    for tp in ALL_SCALAR_TYPES:\n        value = tp(1)\n        if tp is npy_scalar_type:\n            result_tpnm, result_value = test_tpnm(value)\n            assert result_tpnm == tpnm\n            assert isinstance(result_value, npy_scalar_type)\n            assert result_value == tp(expected_value)\n        else:\n            with pytest.raises(TypeError):\n                test_tpnm(value)\n\n\ndef test_eq_ne():\n    assert m.test_eq(np.int32(3), np.int32(3))\n    assert not m.test_eq(np.int32(3), np.int32(5))\n    assert not m.test_ne(np.int32(3), np.int32(3))\n    assert m.test_ne(np.int32(3), np.int32(5))\n"
  },
  {
    "path": "tests/test_numpy_vectorize.cpp",
    "content": "/*\n    tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array\n    arguments\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/numpy.h>\n\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\ndouble my_func(int x, float y, double z) {\n    py::print(\"my_func(x:int={}, y:float={:.0f}, z:float={:.0f})\"_s.format(x, y, z));\n    return (float) x * y * z;\n}\n\nTEST_SUBMODULE(numpy_vectorize, m) {\n    try {\n        py::module_::import(\"numpy\");\n    } catch (const py::error_already_set &) {\n        return;\n    }\n\n    // test_vectorize, test_docs, test_array_collapse\n    // Vectorize all arguments of a function (though non-vector arguments are also allowed)\n    m.def(\"vectorized_func\", py::vectorize(my_func));\n\n    // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the\n    // vectorization)\n    m.def(\"vectorized_func2\", [](py::array_t<int> x, py::array_t<float> y, float z) {\n        return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(std::move(x),\n                                                                               std::move(y));\n    });\n\n    // Vectorize a complex-valued function\n    m.def(\"vectorized_func3\",\n          py::vectorize([](std::complex<double> c) { return c * std::complex<double>(2.f); }));\n\n    // test_type_selection\n    // NumPy function which only accepts specific data types\n    // A lot of these no lints could be replaced with const refs, and probably should at some\n    // point.\n    m.def(\"selective_func\",\n          [](const py::array_t<int, py::array::c_style> &) { return \"Int branch taken.\"; });\n    m.def(\"selective_func\",\n          [](const py::array_t<float, py::array::c_style> &) { return \"Float branch taken.\"; });\n    m.def(\"selective_func\", [](const py::array_t<std::complex<float>, py::array::c_style> &) {\n        return \"Complex float branch taken.\";\n    });\n\n    // test_passthrough_arguments\n    // Passthrough test: references and non-pod types should be automatically passed through (in\n    // the function definition below, only `b`, `d`, and `g` are vectorized):\n    struct NonPODClass {\n        explicit NonPODClass(int v) : value{v} {}\n        int value;\n    };\n    py::class_<NonPODClass>(m, \"NonPODClass\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &NonPODClass::value);\n    m.def(\"vec_passthrough\",\n          py::vectorize([](const double *a,\n                           double b,\n                           // Changing this broke things\n                           // NOLINTNEXTLINE(performance-unnecessary-value-param)\n                           py::array_t<double> c,\n                           const int &d,\n                           int &e,\n                           NonPODClass f,\n                           const double g) { return *a + b + c.at(0) + d + e + f.value + g; }));\n\n    // test_method_vectorization\n    struct VectorizeTestClass {\n        explicit VectorizeTestClass(int v) : value{v} {};\n        float method(int x, float y) const { return y + (float) (x + value); }\n        int value = 0;\n    };\n    py::class_<VectorizeTestClass> vtc(m, \"VectorizeTestClass\");\n    vtc.def(py::init<int>()).def_readwrite(\"value\", &VectorizeTestClass::value);\n\n    // Automatic vectorizing of methods\n    vtc.def(\"method\", py::vectorize(&VectorizeTestClass::method));\n\n    // test_trivial_broadcasting\n    // Internal optimization test for whether the input is trivially broadcastable:\n    py::enum_<py::detail::broadcast_trivial>(m, \"trivial\")\n        .value(\"f_trivial\", py::detail::broadcast_trivial::f_trivial)\n        .value(\"c_trivial\", py::detail::broadcast_trivial::c_trivial)\n        .value(\"non_trivial\", py::detail::broadcast_trivial::non_trivial);\n    m.def(\"vectorized_is_trivial\",\n          [](const py::array_t<int, py::array::forcecast> &arg1,\n             const py::array_t<float, py::array::forcecast> &arg2,\n             const py::array_t<double, py::array::forcecast> &arg3) {\n              py::ssize_t ndim = 0;\n              std::vector<py::ssize_t> shape;\n              std::array<py::buffer_info, 3> buffers{\n                  {arg1.request(), arg2.request(), arg3.request()}};\n              return py::detail::broadcast(buffers, ndim, shape);\n          });\n\n    m.def(\"add_to\", py::vectorize([](NonPODClass &x, int a) { x.value += a; }));\n}\n"
  },
  {
    "path": "tests/test_numpy_vectorize.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import numpy_vectorize as m\n\nnp = pytest.importorskip(\"numpy\")\n\n\ndef test_vectorize(capture):\n    assert np.isclose(m.vectorized_func3(np.array(3 + 7j)), [6 + 14j])\n\n    for f in [m.vectorized_func, m.vectorized_func2]:\n        with capture:\n            assert np.isclose(f(1, 2, 3), 6)\n        assert capture == \"my_func(x:int=1, y:float=2, z:float=3)\"\n        with capture:\n            assert np.isclose(f(np.array(1), np.array(2), 3), 6)\n        assert capture == \"my_func(x:int=1, y:float=2, z:float=3)\"\n        with capture:\n            assert np.allclose(f(np.array([1, 3]), np.array([2, 4]), 3), [6, 36])\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=3)\n            my_func(x:int=3, y:float=4, z:float=3)\n        \"\"\"\n        )\n        with capture:\n            a = np.array([[1, 2], [3, 4]], order=\"F\")\n            b = np.array([[10, 20], [30, 40]], order=\"F\")\n            c = 3\n            result = f(a, b, c)\n            assert np.allclose(result, a * b * c)\n            assert result.flags.f_contiguous\n        # All inputs are F order and full or singletons, so we the result is in col-major order:\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=10, z:float=3)\n            my_func(x:int=3, y:float=30, z:float=3)\n            my_func(x:int=2, y:float=20, z:float=3)\n            my_func(x:int=4, y:float=40, z:float=3)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = (\n                np.array([[1, 3, 5], [7, 9, 11]]),\n                np.array([[2, 4, 6], [8, 10, 12]]),\n                3,\n            )\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=3)\n            my_func(x:int=3, y:float=4, z:float=3)\n            my_func(x:int=5, y:float=6, z:float=3)\n            my_func(x:int=7, y:float=8, z:float=3)\n            my_func(x:int=9, y:float=10, z:float=3)\n            my_func(x:int=11, y:float=12, z:float=3)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = np.array([[1, 2, 3], [4, 5, 6]]), np.array([2, 3, 4]), 2\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=2)\n            my_func(x:int=2, y:float=3, z:float=2)\n            my_func(x:int=3, y:float=4, z:float=2)\n            my_func(x:int=4, y:float=2, z:float=2)\n            my_func(x:int=5, y:float=3, z:float=2)\n            my_func(x:int=6, y:float=4, z:float=2)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = np.array([[1, 2, 3], [4, 5, 6]]), np.array([[2], [3]]), 2\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=2)\n            my_func(x:int=2, y:float=2, z:float=2)\n            my_func(x:int=3, y:float=2, z:float=2)\n            my_func(x:int=4, y:float=3, z:float=2)\n            my_func(x:int=5, y:float=3, z:float=2)\n            my_func(x:int=6, y:float=3, z:float=2)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = (\n                np.array([[1, 2, 3], [4, 5, 6]], order=\"F\"),\n                np.array([[2], [3]]),\n                2,\n            )\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=2)\n            my_func(x:int=2, y:float=2, z:float=2)\n            my_func(x:int=3, y:float=2, z:float=2)\n            my_func(x:int=4, y:float=3, z:float=2)\n            my_func(x:int=5, y:float=3, z:float=2)\n            my_func(x:int=6, y:float=3, z:float=2)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = np.array([[1, 2, 3], [4, 5, 6]])[::, ::2], np.array([[2], [3]]), 2\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=2)\n            my_func(x:int=3, y:float=2, z:float=2)\n            my_func(x:int=4, y:float=3, z:float=2)\n            my_func(x:int=6, y:float=3, z:float=2)\n        \"\"\"\n        )\n        with capture:\n            a, b, c = (\n                np.array([[1, 2, 3], [4, 5, 6]], order=\"F\")[::, ::2],\n                np.array([[2], [3]]),\n                2,\n            )\n            assert np.allclose(f(a, b, c), a * b * c)\n        assert (\n            capture\n            == \"\"\"\n            my_func(x:int=1, y:float=2, z:float=2)\n            my_func(x:int=3, y:float=2, z:float=2)\n            my_func(x:int=4, y:float=3, z:float=2)\n            my_func(x:int=6, y:float=3, z:float=2)\n        \"\"\"\n        )\n\n\ndef test_type_selection():\n    assert m.selective_func(np.array([1], dtype=np.int32)) == \"Int branch taken.\"\n    assert m.selective_func(np.array([1.0], dtype=np.float32)) == \"Float branch taken.\"\n    assert (\n        m.selective_func(np.array([1.0j], dtype=np.complex64))\n        == \"Complex float branch taken.\"\n    )\n\n\ndef test_docs(doc):\n    assert (\n        doc(m.vectorized_func)\n        == \"\"\"\n        vectorized_func(arg0: typing.Annotated[numpy.typing.ArrayLike, numpy.int32], arg1: typing.Annotated[numpy.typing.ArrayLike, numpy.float32], arg2: typing.Annotated[numpy.typing.ArrayLike, numpy.float64]) -> object\n    \"\"\"\n    )\n\n\ndef test_trivial_broadcasting():\n    trivial, vectorized_is_trivial = m.trivial, m.vectorized_is_trivial\n\n    assert vectorized_is_trivial(1, 2, 3) == trivial.c_trivial\n    assert vectorized_is_trivial(np.array(1), np.array(2), 3) == trivial.c_trivial\n    assert (\n        vectorized_is_trivial(np.array([1, 3]), np.array([2, 4]), 3)\n        == trivial.c_trivial\n    )\n    assert trivial.c_trivial == vectorized_is_trivial(\n        np.array([[1, 3, 5], [7, 9, 11]]), np.array([[2, 4, 6], [8, 10, 12]]), 3\n    )\n    assert (\n        vectorized_is_trivial(np.array([[1, 2, 3], [4, 5, 6]]), np.array([2, 3, 4]), 2)\n        == trivial.non_trivial\n    )\n    assert (\n        vectorized_is_trivial(np.array([[1, 2, 3], [4, 5, 6]]), np.array([[2], [3]]), 2)\n        == trivial.non_trivial\n    )\n    z1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=\"int32\")\n    z2 = np.array(z1, dtype=\"float32\")\n    z3 = np.array(z1, dtype=\"float64\")\n    assert vectorized_is_trivial(z1, z2, z3) == trivial.c_trivial\n    assert vectorized_is_trivial(1, z2, z3) == trivial.c_trivial\n    assert vectorized_is_trivial(z1, 1, z3) == trivial.c_trivial\n    assert vectorized_is_trivial(z1, z2, 1) == trivial.c_trivial\n    assert vectorized_is_trivial(z1[::2, ::2], 1, 1) == trivial.non_trivial\n    assert vectorized_is_trivial(1, 1, z1[::2, ::2]) == trivial.c_trivial\n    assert vectorized_is_trivial(1, 1, z3[::2, ::2]) == trivial.non_trivial\n    assert vectorized_is_trivial(z1, 1, z3[1::4, 1::4]) == trivial.c_trivial\n\n    y1 = np.array(z1, order=\"F\")\n    y2 = np.array(y1)\n    y3 = np.array(y1)\n    assert vectorized_is_trivial(y1, y2, y3) == trivial.f_trivial\n    assert vectorized_is_trivial(y1, 1, 1) == trivial.f_trivial\n    assert vectorized_is_trivial(1, y2, 1) == trivial.f_trivial\n    assert vectorized_is_trivial(1, 1, y3) == trivial.f_trivial\n    assert vectorized_is_trivial(y1, z2, 1) == trivial.non_trivial\n    assert vectorized_is_trivial(z1[1::4, 1::4], y2, 1) == trivial.f_trivial\n    assert vectorized_is_trivial(y1[1::4, 1::4], z2, 1) == trivial.c_trivial\n\n    assert m.vectorized_func(z1, z2, z3).flags.c_contiguous\n    assert m.vectorized_func(y1, y2, y3).flags.f_contiguous\n    assert m.vectorized_func(z1, 1, 1).flags.c_contiguous\n    assert m.vectorized_func(1, y2, 1).flags.f_contiguous\n    assert m.vectorized_func(z1[1::4, 1::4], y2, 1).flags.f_contiguous\n    assert m.vectorized_func(y1[1::4, 1::4], z2, 1).flags.c_contiguous\n\n\ndef test_passthrough_arguments(doc):\n    assert doc(m.vec_passthrough) == (\n        \"vec_passthrough(\"\n        + \", \".join(\n            [\n                \"arg0: typing.SupportsFloat | typing.SupportsIndex\",\n                \"arg1: typing.Annotated[numpy.typing.ArrayLike, numpy.float64]\",\n                \"arg2: typing.Annotated[numpy.typing.ArrayLike, numpy.float64]\",\n                \"arg3: typing.Annotated[numpy.typing.ArrayLike, numpy.int32]\",\n                \"arg4: typing.SupportsInt | typing.SupportsIndex\",\n                \"arg5: m.numpy_vectorize.NonPODClass\",\n                \"arg6: typing.Annotated[numpy.typing.ArrayLike, numpy.float64]\",\n            ]\n        )\n        + \") -> object\"\n    )\n\n    b = np.array([[10, 20, 30]], dtype=\"float64\")\n    c = np.array([100, 200])  # NOT a vectorized argument\n    d = np.array([[1000], [2000], [3000]], dtype=\"int\")\n    g = np.array([[1000000, 2000000, 3000000]], dtype=\"int\")  # requires casting\n    assert np.all(\n        m.vec_passthrough(1, b, c, d, 10000, m.NonPODClass(100000), g)\n        == np.array(\n            [\n                [1111111, 2111121, 3111131],\n                [1112111, 2112121, 3112131],\n                [1113111, 2113121, 3113131],\n            ]\n        )\n    )\n\n\ndef test_method_vectorization():\n    o = m.VectorizeTestClass(3)\n    x = np.array([1, 2], dtype=\"int\")\n    y = np.array([[10], [20]], dtype=\"float32\")\n    assert np.all(o.method(x, y) == [[14, 15], [24, 25]])\n\n\ndef test_array_collapse():\n    assert not isinstance(m.vectorized_func(1, 2, 3), np.ndarray)\n    assert not isinstance(m.vectorized_func(np.array(1), 2, 3), np.ndarray)\n    z = m.vectorized_func([1], 2, 3)\n    assert isinstance(z, np.ndarray)\n    assert z.shape == (1,)\n    z = m.vectorized_func(1, [[[2]]], 3)\n    assert isinstance(z, np.ndarray)\n    assert z.shape == (1, 1, 1)\n\n\ndef test_vectorized_noreturn():\n    x = m.NonPODClass(0)\n    assert x.value == 0\n    m.add_to(x, [1, 2, 3, 4])\n    assert x.value == 10\n    m.add_to(x, 1)\n    assert x.value == 11\n    m.add_to(x, [[1, 1], [2, 3]])\n    assert x.value == 18\n"
  },
  {
    "path": "tests/test_opaque_types.cpp",
    "content": "/*\n    tests/test_opaque_types.cpp -- opaque types, passing void pointers\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n\n#include \"pybind11_tests.h\"\n\n#include <vector>\n\n// IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures\n//\n// This also deliberately doesn't use the below StringList type alias to test\n// that MAKE_OPAQUE can handle a type containing a `,`.  (The `std::allocator`\n// bit is just the default `std::vector` allocator).\nPYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>)\n\nusing StringList = std::vector<std::string, std::allocator<std::string>>;\n\nTEST_SUBMODULE(opaque_types, m) {\n    // test_string_list\n    py::class_<StringList>(m, \"StringList\")\n        .def(py::init<>())\n        .def(\"pop_back\", &StringList::pop_back)\n        /* There are multiple versions of push_back(), etc. Select the right ones. */\n        .def(\"push_back\", (void (StringList::*)(const std::string &)) &StringList::push_back)\n        .def(\"back\", (std::string & (StringList::*) ()) & StringList::back)\n        .def(\"__len__\", [](const StringList &v) { return v.size(); })\n        .def(\n            \"__iter__\",\n            [](StringList &v) { return py::make_iterator(v.begin(), v.end()); },\n            py::keep_alive<0, 1>());\n\n    class ClassWithSTLVecProperty {\n    public:\n        StringList stringList;\n    };\n    py::class_<ClassWithSTLVecProperty>(m, \"ClassWithSTLVecProperty\")\n        .def(py::init<>())\n        .def_readwrite(\"stringList\", &ClassWithSTLVecProperty::stringList);\n\n    m.def(\"print_opaque_list\", [](const StringList &l) {\n        std::string ret = \"Opaque list: [\";\n        bool first = true;\n        for (const auto &entry : l) {\n            if (!first) {\n                ret += \", \";\n            }\n            ret += entry;\n            first = false;\n        }\n        return ret + \"]\";\n    });\n\n    // test_pointers\n    m.def(\"return_void_ptr\", []() { return (void *) 0x1234; });\n    m.def(\"get_void_ptr_value\", [](void *ptr) { return reinterpret_cast<std::intptr_t>(ptr); });\n    m.def(\"return_null_str\", []() { return (char *) nullptr; });\n    m.def(\"get_null_str_value\", [](char *ptr) { return reinterpret_cast<std::intptr_t>(ptr); });\n\n    m.def(\"return_unique_ptr\", []() -> std::unique_ptr<StringList> {\n        auto *result = new StringList();\n        result->emplace_back(\"some value\");\n        return std::unique_ptr<StringList>(result);\n    });\n\n    // test unions\n    py::class_<IntFloat>(m, \"IntFloat\")\n        .def(py::init<>())\n        .def_readwrite(\"i\", &IntFloat::i)\n        .def_readwrite(\"f\", &IntFloat::f);\n}\n"
  },
  {
    "path": "tests/test_opaque_types.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats, UserType\nfrom pybind11_tests import opaque_types as m\n\n\ndef test_string_list():\n    lst = m.StringList()\n    lst.push_back(\"Element 1\")\n    lst.push_back(\"Element 2\")\n    assert m.print_opaque_list(lst) == \"Opaque list: [Element 1, Element 2]\"\n    assert lst.back() == \"Element 2\"\n\n    for i, k in enumerate(lst, start=1):\n        assert k == f\"Element {i}\"\n    lst.pop_back()\n    assert m.print_opaque_list(lst) == \"Opaque list: [Element 1]\"\n\n    cvp = m.ClassWithSTLVecProperty()\n    assert m.print_opaque_list(cvp.stringList) == \"Opaque list: []\"\n\n    cvp.stringList = lst\n    cvp.stringList.push_back(\"Element 3\")\n    assert m.print_opaque_list(cvp.stringList) == \"Opaque list: [Element 1, Element 3]\"\n\n\ndef test_pointers(msg, backport_typehints):\n    living_before = ConstructorStats.get(UserType).alive()\n    assert m.get_void_ptr_value(m.return_void_ptr()) == 0x1234\n    assert m.get_void_ptr_value(UserType())  # Should also work for other C++ types\n\n    if not env.GRAALPY:\n        assert ConstructorStats.get(UserType).alive() == living_before\n\n    with pytest.raises(TypeError) as excinfo:\n        m.get_void_ptr_value([1, 2, 3])  # This should not work\n\n    assert (\n        backport_typehints(msg(excinfo.value))\n        == \"\"\"\n            get_void_ptr_value(): incompatible function arguments. The following argument types are supported:\n                1. (arg0: types.CapsuleType) -> int\n\n            Invoked with: [1, 2, 3]\n        \"\"\"\n    )\n\n    assert m.return_null_str() is None\n    assert m.get_null_str_value(m.return_null_str()) is not None\n\n    ptr = m.return_unique_ptr()\n    assert \"StringList\" in repr(ptr)\n    assert m.print_opaque_list(ptr) == \"Opaque list: [some value]\"\n\n\ndef test_unions():\n    int_float_union = m.IntFloat()\n    int_float_union.i = 42\n    assert int_float_union.i == 42\n    int_float_union.f = 3.0\n    assert int_float_union.f == 3.0\n"
  },
  {
    "path": "tests/test_operator_overloading.cpp",
    "content": "/*\n    tests/test_operator_overloading.cpp -- operator overloading\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/operators.h>\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <functional>\n\nclass Vector2 {\npublic:\n    Vector2(float x, float y) : x(x), y(y) { print_created(this, toString()); }\n    Vector2(const Vector2 &v) : x(v.x), y(v.y) { print_copy_created(this); }\n    Vector2(Vector2 &&v) noexcept : x(v.x), y(v.y) {\n        print_move_created(this);\n        v.x = v.y = 0;\n    }\n    Vector2 &operator=(const Vector2 &v) {\n        x = v.x;\n        y = v.y;\n        print_copy_assigned(this);\n        return *this;\n    }\n    Vector2 &operator=(Vector2 &&v) noexcept {\n        x = v.x;\n        y = v.y;\n        v.x = v.y = 0;\n        print_move_assigned(this);\n        return *this;\n    }\n    ~Vector2() { print_destroyed(this); }\n\n    std::string toString() const {\n        return \"[\" + std::to_string(x) + \", \" + std::to_string(y) + \"]\";\n    }\n\n    Vector2 operator-() const { return Vector2(-x, -y); }\n    Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }\n    Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); }\n    Vector2 operator-(float value) const { return Vector2(x - value, y - value); }\n    Vector2 operator+(float value) const { return Vector2(x + value, y + value); }\n    Vector2 operator*(float value) const { return Vector2(x * value, y * value); }\n    Vector2 operator/(float value) const { return Vector2(x / value, y / value); }\n    Vector2 operator*(const Vector2 &v) const { return Vector2(x * v.x, y * v.y); }\n    Vector2 operator/(const Vector2 &v) const { return Vector2(x / v.x, y / v.y); }\n    Vector2 &operator+=(const Vector2 &v) {\n        x += v.x;\n        y += v.y;\n        return *this;\n    }\n    Vector2 &operator-=(const Vector2 &v) {\n        x -= v.x;\n        y -= v.y;\n        return *this;\n    }\n    Vector2 &operator*=(float v) {\n        x *= v;\n        y *= v;\n        return *this;\n    }\n    Vector2 &operator/=(float v) {\n        x /= v;\n        y /= v;\n        return *this;\n    }\n    Vector2 &operator*=(const Vector2 &v) {\n        x *= v.x;\n        y *= v.y;\n        return *this;\n    }\n    Vector2 &operator/=(const Vector2 &v) {\n        x /= v.x;\n        y /= v.y;\n        return *this;\n    }\n\n    friend Vector2 operator+(float f, const Vector2 &v) { return Vector2(f + v.x, f + v.y); }\n    friend Vector2 operator-(float f, const Vector2 &v) { return Vector2(f - v.x, f - v.y); }\n    friend Vector2 operator*(float f, const Vector2 &v) { return Vector2(f * v.x, f * v.y); }\n    friend Vector2 operator/(float f, const Vector2 &v) { return Vector2(f / v.x, f / v.y); }\n\n    bool operator==(const Vector2 &v) const { return x == v.x && y == v.y; }\n    bool operator!=(const Vector2 &v) const { return x != v.x || y != v.y; }\n\nprivate:\n    float x, y;\n};\n\nclass C1 {};\nclass C2 {};\n\nint operator+(const C1 &, const C1 &) { return 11; }\nint operator+(const C2 &, const C2 &) { return 22; }\nint operator+(const C2 &, const C1 &) { return 21; }\nint operator+(const C1 &, const C2 &) { return 12; }\n\nstruct HashMe {\n    std::string member;\n};\n\nbool operator==(const HashMe &lhs, const HashMe &rhs) { return lhs.member == rhs.member; }\n\n// Note: Specializing explicit within `namespace std { ... }` is done due to a\n// bug in GCC<7. If you are supporting compilers later than this, consider\n// specializing `using template<> struct std::hash<...>` in the global\n// namespace instead, per this recommendation:\n// https://en.cppreference.com/w/cpp/language/extending_std#Adding_template_specializations\nnamespace std {\ntemplate <>\nstruct hash<Vector2> {\n    // Not a good hash function, but easy to test\n    size_t operator()(const Vector2 &) { return 4; }\n};\n\n// HashMe has a hash function in C++ but no `__hash__` for Python.\ntemplate <>\nstruct hash<HashMe> {\n    std::size_t operator()(const HashMe &selector) const {\n        return std::hash<std::string>()(selector.member);\n    }\n};\n} // namespace std\n\n// Not a good abs function, but easy to test.\nstd::string abs(const Vector2 &) { return \"abs(Vector2)\"; }\n\n// clang 7.0.0 and Apple LLVM 10.0.1 introduce `-Wself-assign-overloaded` to\n// `-Wall`, which is used here for overloading (e.g. `py::self += py::self `).\n// Here, we suppress the warning\n// Taken from: https://github.com/RobotLocomotion/drake/commit/aaf84b46\n// TODO(eric): This could be resolved using a function / functor (e.g. `py::self()`).\n#if defined(__APPLE__) && defined(__clang__)\n#    if (__clang_major__ >= 10)\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wself-assign-overloaded\")\n#    endif\n#elif defined(__clang__)\n#    if (__clang_major__ >= 7)\nPYBIND11_WARNING_DISABLE_CLANG(\"-Wself-assign-overloaded\")\n#    endif\n#endif\n\nTEST_SUBMODULE(operators, m) {\n\n    // test_operator_overloading\n    py::class_<Vector2>(m, \"Vector2\")\n        .def(py::init<float, float>())\n        .def(py::self + py::self)\n        .def(py::self + float())\n        .def(py::self - py::self)\n        .def(py::self - float())\n        .def(py::self * float())\n        .def(py::self / float())\n        .def(py::self * py::self)\n        .def(py::self / py::self)\n        .def(py::self += py::self)\n        .def(py::self -= py::self)\n        .def(py::self *= float())\n        .def(py::self /= float())\n        .def(py::self *= py::self)\n        .def(py::self /= py::self)\n        .def(float() + py::self)\n        .def(float() - py::self)\n        .def(float() * py::self)\n        .def(float() / py::self)\n        .def(-py::self)\n        .def(\"__str__\", &Vector2::toString)\n        .def(\"__repr__\", &Vector2::toString)\n        .def(py::self == py::self)\n        .def(py::self != py::self)\n        .def(py::hash(py::self))\n        // N.B. See warning about usage of `py::detail::abs(py::self)` in\n        // `operators.h`.\n        .def(\"__abs__\", [](const Vector2 &v) { return abs(v); });\n\n    m.attr(\"Vector\") = m.attr(\"Vector2\");\n\n    // test_operators_notimplemented\n    // #393: need to return NotSupported to ensure correct arithmetic operator behavior\n    py::class_<C1>(m, \"C1\").def(py::init<>()).def(py::self + py::self);\n\n    py::class_<C2>(m, \"C2\")\n        .def(py::init<>())\n        .def(py::self + py::self)\n        .def(\"__add__\", [](const C2 &c2, const C1 &c1) { return c2 + c1; })\n        .def(\"__radd__\", [](const C2 &c2, const C1 &c1) { return c1 + c2; });\n\n    // test_nested\n    // #328: first member in a class can't be used in operators\n    struct NestABase {\n        int value = -2;\n    };\n    py::class_<NestABase>(m, \"NestABase\")\n        .def(py::init<>())\n        .def_readwrite(\"value\", &NestABase::value);\n\n    struct NestA : NestABase {\n        int value = 3;\n        NestA &operator+=(int i) {\n            value += i;\n            return *this;\n        }\n    };\n    py::class_<NestA>(m, \"NestA\")\n        .def(py::init<>())\n        .def(py::self += int())\n        .def(\n            \"as_base\",\n            [](NestA &a) -> NestABase & { return (NestABase &) a; },\n            py::return_value_policy::reference_internal);\n    m.def(\"get_NestA\", [](const NestA &a) { return a.value; });\n\n    struct NestB {\n        NestA a;\n        int value = 4;\n        NestB &operator-=(int i) {\n            value -= i;\n            return *this;\n        }\n    };\n    py::class_<NestB>(m, \"NestB\")\n        .def(py::init<>())\n        .def(py::self -= int())\n        .def_readwrite(\"a\", &NestB::a);\n    m.def(\"get_NestB\", [](const NestB &b) { return b.value; });\n\n    struct NestC {\n        NestB b;\n        int value = 5;\n        NestC &operator*=(int i) {\n            value *= i;\n            return *this;\n        }\n    };\n    py::class_<NestC>(m, \"NestC\")\n        .def(py::init<>())\n        .def(py::self *= int())\n        .def_readwrite(\"b\", &NestC::b);\n    m.def(\"get_NestC\", [](const NestC &c) { return c.value; });\n\n    // test_overriding_eq_reset_hash\n    // #2191 Overriding __eq__ should set __hash__ to None\n    struct Comparable {\n        int value;\n        bool operator==(const Comparable &rhs) const { return value == rhs.value; }\n    };\n\n    struct Hashable : Comparable {\n        explicit Hashable(int value) : Comparable{value} {};\n        size_t hash() const { return static_cast<size_t>(value); }\n    };\n\n    struct Hashable2 : Hashable {\n        using Hashable::Hashable;\n    };\n\n    py::class_<Comparable>(m, \"Comparable\").def(py::init<int>()).def(py::self == py::self);\n\n    py::class_<Hashable>(m, \"Hashable\")\n        .def(py::init<int>())\n        .def(py::self == py::self)\n        .def(\"__hash__\", &Hashable::hash);\n\n    // define __hash__ before __eq__\n    py::class_<Hashable2>(m, \"Hashable2\")\n        .def(\"__hash__\", &Hashable::hash)\n        .def(py::init<int>())\n        .def(py::self == py::self);\n\n    // define __eq__ but not __hash__\n    py::class_<HashMe>(m, \"HashMe\").def(py::self == py::self);\n\n    m.def(\"get_unhashable_HashMe_set\", []() { return std::unordered_set<HashMe>{{\"one\"}}; });\n}\n"
  },
  {
    "path": "tests/test_operator_overloading.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import operators as m\n\n\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should get fixed on GraalPy side\")\ndef test_operator_overloading():\n    v1 = m.Vector2(1, 2)\n    v2 = m.Vector(3, -1)\n    v3 = m.Vector2(1, 2)  # Same value as v1, but different instance.\n    assert v1 is not v3\n\n    assert str(v1) == \"[1.000000, 2.000000]\"\n    assert str(v2) == \"[3.000000, -1.000000]\"\n\n    assert str(-v2) == \"[-3.000000, 1.000000]\"\n\n    assert str(v1 + v2) == \"[4.000000, 1.000000]\"\n    assert str(v1 - v2) == \"[-2.000000, 3.000000]\"\n    assert str(v1 - 8) == \"[-7.000000, -6.000000]\"\n    assert str(v1 + 8) == \"[9.000000, 10.000000]\"\n    assert str(v1 * 8) == \"[8.000000, 16.000000]\"\n    assert str(v1 / 8) == \"[0.125000, 0.250000]\"\n    assert str(8 - v1) == \"[7.000000, 6.000000]\"\n    assert str(8 + v1) == \"[9.000000, 10.000000]\"\n    assert str(8 * v1) == \"[8.000000, 16.000000]\"\n    assert str(8 / v1) == \"[8.000000, 4.000000]\"\n    assert str(v1 * v2) == \"[3.000000, -2.000000]\"\n    assert str(v2 / v1) == \"[3.000000, -0.500000]\"\n\n    assert v1 == v3\n    assert v1 != v2\n    assert hash(v1) == 4\n    # TODO(eric.cousineau): Make this work.\n    # assert abs(v1) == \"abs(Vector2)\"\n\n    v1 += 2 * v2\n    assert str(v1) == \"[7.000000, 0.000000]\"\n    v1 -= v2\n    assert str(v1) == \"[4.000000, 1.000000]\"\n    v1 *= 2\n    assert str(v1) == \"[8.000000, 2.000000]\"\n    v1 /= 16\n    assert str(v1) == \"[0.500000, 0.125000]\"\n    v1 *= v2\n    assert str(v1) == \"[1.500000, -0.125000]\"\n    v2 /= v1\n    assert str(v2) == \"[2.000000, 8.000000]\"\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    cstats = ConstructorStats.get(m.Vector2)\n    assert cstats.alive() == 3\n    del v1\n    assert cstats.alive() == 2\n    del v2\n    assert cstats.alive() == 1\n    del v3\n    assert cstats.alive() == 0\n    assert cstats.values() == [\n        \"[1.000000, 2.000000]\",\n        \"[3.000000, -1.000000]\",\n        \"[1.000000, 2.000000]\",\n        \"[-3.000000, 1.000000]\",\n        \"[4.000000, 1.000000]\",\n        \"[-2.000000, 3.000000]\",\n        \"[-7.000000, -6.000000]\",\n        \"[9.000000, 10.000000]\",\n        \"[8.000000, 16.000000]\",\n        \"[0.125000, 0.250000]\",\n        \"[7.000000, 6.000000]\",\n        \"[9.000000, 10.000000]\",\n        \"[8.000000, 16.000000]\",\n        \"[8.000000, 4.000000]\",\n        \"[3.000000, -2.000000]\",\n        \"[3.000000, -0.500000]\",\n        \"[6.000000, -2.000000]\",\n    ]\n    assert cstats.default_constructions == 0\n    assert cstats.copy_constructions == 0\n    assert cstats.move_constructions >= 10\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n\n@pytest.mark.xfail(\n    env.GRAALPY and env.GRAALPY_VERSION < (24, 2), reason=\"Fixed in GraalPy 24.2\"\n)\ndef test_operators_notimplemented():\n    \"\"\"#393: need to return NotSupported to ensure correct arithmetic operator behavior\"\"\"\n\n    c1, c2 = m.C1(), m.C2()\n    assert c1 + c1 == 11\n    assert c2 + c2 == 22\n    assert c2 + c1 == 21\n    assert c1 + c2 == 12\n\n\ndef test_nested():\n    \"\"\"#328: first member in a class can't be used in operators\"\"\"\n\n    a = m.NestA()\n    b = m.NestB()\n    c = m.NestC()\n\n    a += 10\n    assert m.get_NestA(a) == 13\n    b.a += 100\n    assert m.get_NestA(b.a) == 103\n    c.b.a += 1000\n    assert m.get_NestA(c.b.a) == 1003\n    b -= 1\n    assert m.get_NestB(b) == 3\n    c.b -= 3\n    assert m.get_NestB(c.b) == 1\n    c *= 7\n    assert m.get_NestC(c) == 35\n\n    abase = a.as_base()\n    assert abase.value == -2\n    a.as_base().value += 44\n    assert abase.value == 42\n    assert c.b.a.as_base().value == -2\n    c.b.a.as_base().value += 44\n    assert c.b.a.as_base().value == 42\n\n    del c\n    pytest.gc_collect()\n    del a  # Shouldn't delete while abase is still alive\n    pytest.gc_collect()\n\n    assert abase.value == 42\n    del abase, b\n    pytest.gc_collect()\n\n\ndef test_overriding_eq_reset_hash():\n    assert m.Comparable(15) is not m.Comparable(15)\n    assert m.Comparable(15) == m.Comparable(15)\n\n    with pytest.raises(TypeError) as excinfo:\n        hash(m.Comparable(15))\n    assert str(excinfo.value).startswith(\"unhashable type:\")\n\n    for hashable in (m.Hashable, m.Hashable2):\n        assert hashable(15) is not hashable(15)\n        assert hashable(15) == hashable(15)\n\n        assert hash(hashable(15)) == 15\n        assert hash(hashable(15)) == hash(hashable(15))\n\n\ndef test_return_set_of_unhashable():\n    with pytest.raises(TypeError) as excinfo:\n        m.get_unhashable_HashMe_set()\n    assert \"unhashable type\" in str(excinfo.value.__cause__)\n"
  },
  {
    "path": "tests/test_pickling.cpp",
    "content": "/*\n    tests/test_pickling.cpp -- pickle support\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n    Copyright (c) 2021 The Pybind Development Team.\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\n#include <memory>\n#include <stdexcept>\n#include <utility>\n\nnamespace exercise_trampoline {\n\nstruct SimpleBase {\n    int num = 0;\n    virtual ~SimpleBase() = default;\n\n    // For compatibility with old clang versions:\n    SimpleBase() = default;\n    SimpleBase(const SimpleBase &) = default;\n};\n\nstruct SimpleBaseTrampoline : SimpleBase {};\n\nstruct SimpleCppDerived : SimpleBase {};\n\nvoid wrap(py::module m) {\n    py::class_<SimpleBase, SimpleBaseTrampoline>(m, \"SimpleBase\")\n        .def(py::init<>())\n        .def_readwrite(\"num\", &SimpleBase::num)\n        .def(py::pickle(\n            [](const py::object &self) {\n                py::dict d = py::getattr(self, \"__dict__\", py::dict());\n                return py::make_tuple(self.attr(\"num\"), d);\n            },\n            [](const py::tuple &t) {\n                if (t.size() != 2) {\n                    throw std::runtime_error(\"Invalid state!\");\n                }\n                auto cpp_state = std::unique_ptr<SimpleBase>(new SimpleBaseTrampoline);\n                cpp_state->num = t[0].cast<int>();\n                auto py_state = t[1].cast<py::dict>();\n                return std::make_pair(std::move(cpp_state), py_state);\n            }));\n\n    m.def(\"make_SimpleCppDerivedAsBase\",\n          []() { return std::unique_ptr<SimpleBase>(new SimpleCppDerived); });\n    m.def(\"check_dynamic_cast_SimpleCppDerived\", [](const SimpleBase *base_ptr) {\n        return dynamic_cast<const SimpleCppDerived *>(base_ptr) != nullptr;\n    });\n}\n\n} // namespace exercise_trampoline\n\nTEST_SUBMODULE(pickling, m) {\n    m.def(\"simple_callable\", []() { return 20220426; });\n\n    // test_roundtrip\n    class Pickleable {\n    public:\n        explicit Pickleable(const std::string &value) : m_value(value) {}\n        const std::string &value() const { return m_value; }\n\n        void setExtra1(int extra1) { m_extra1 = extra1; }\n        void setExtra2(int extra2) { m_extra2 = extra2; }\n        int extra1() const { return m_extra1; }\n        int extra2() const { return m_extra2; }\n\n    private:\n        std::string m_value;\n        int m_extra1 = 0;\n        int m_extra2 = 0;\n    };\n\n    class PickleableNew : public Pickleable {\n    public:\n        using Pickleable::Pickleable;\n    };\n\n    py::class_<Pickleable> pyPickleable(m, \"Pickleable\");\n    pyPickleable.def(py::init<std::string>())\n        .def(\"value\", &Pickleable::value)\n        .def(\"extra1\", &Pickleable::extra1)\n        .def(\"extra2\", &Pickleable::extra2)\n        .def(\"setExtra1\", &Pickleable::setExtra1)\n        .def(\"setExtra2\", &Pickleable::setExtra2)\n        // For details on the methods below, refer to\n        // http://docs.python.org/3/library/pickle.html#pickling-class-instances\n        .def(\"__getstate__\", [](const Pickleable &p) {\n            /* Return a tuple that fully encodes the state of the object */\n            return py::make_tuple(p.value(), p.extra1(), p.extra2());\n        });\n    ignoreOldStyleInitWarnings([&pyPickleable]() {\n        pyPickleable.def(\"__setstate__\", [](Pickleable &p, const py::tuple &t) {\n            if (t.size() != 3) {\n                throw std::runtime_error(\"Invalid state!\");\n            }\n            /* Invoke the constructor (need to use in-place version) */\n            new (&p) Pickleable(t[0].cast<std::string>());\n\n            /* Assign any additional state */\n            p.setExtra1(t[1].cast<int>());\n            p.setExtra2(t[2].cast<int>());\n        });\n    });\n\n    py::class_<PickleableNew, Pickleable>(m, \"PickleableNew\")\n        .def(py::init<std::string>())\n        .def(py::pickle(\n            [](const PickleableNew &p) {\n                return py::make_tuple(p.value(), p.extra1(), p.extra2());\n            },\n            [](const py::tuple &t) {\n                if (t.size() != 3) {\n                    throw std::runtime_error(\"Invalid state!\");\n                }\n                auto p = PickleableNew(t[0].cast<std::string>());\n\n                p.setExtra1(t[1].cast<int>());\n                p.setExtra2(t[2].cast<int>());\n                return p;\n            }));\n\n#if !defined(PYPY_VERSION)\n    // test_roundtrip_with_dict\n    class PickleableWithDict {\n    public:\n        explicit PickleableWithDict(const std::string &value) : value(value) {}\n\n        std::string value;\n        int extra;\n    };\n\n    class PickleableWithDictNew : public PickleableWithDict {\n    public:\n        using PickleableWithDict::PickleableWithDict;\n    };\n\n    py::class_<PickleableWithDict> pyPickleableWithDict(\n        m, \"PickleableWithDict\", py::dynamic_attr());\n    pyPickleableWithDict.def(py::init<std::string>())\n        .def_readwrite(\"value\", &PickleableWithDict::value)\n        .def_readwrite(\"extra\", &PickleableWithDict::extra)\n        .def(\"__getstate__\", [](const py::object &self) {\n            /* Also include __dict__ in state */\n            return py::make_tuple(self.attr(\"value\"), self.attr(\"extra\"), self.attr(\"__dict__\"));\n        });\n    ignoreOldStyleInitWarnings([&pyPickleableWithDict]() {\n        pyPickleableWithDict.def(\"__setstate__\", [](const py::object &self, const py::tuple &t) {\n            if (t.size() != 3) {\n                throw std::runtime_error(\"Invalid state!\");\n            }\n            /* Cast and construct */\n            auto &p = self.cast<PickleableWithDict &>();\n            new (&p) PickleableWithDict(t[0].cast<std::string>());\n\n            /* Assign C++ state */\n            p.extra = t[1].cast<int>();\n\n            /* Assign Python state */\n            self.attr(\"__dict__\") = t[2];\n        });\n    });\n\n    py::class_<PickleableWithDictNew, PickleableWithDict>(m, \"PickleableWithDictNew\")\n        .def(py::init<std::string>())\n        .def(py::pickle(\n            [](const py::object &self) {\n                return py::make_tuple(\n                    self.attr(\"value\"), self.attr(\"extra\"), self.attr(\"__dict__\"));\n            },\n            [](const py::tuple &t) {\n                if (t.size() != 3) {\n                    throw std::runtime_error(\"Invalid state!\");\n                }\n\n                auto cpp_state = PickleableWithDictNew(t[0].cast<std::string>());\n                cpp_state.extra = t[1].cast<int>();\n\n                auto py_state = t[2].cast<py::dict>();\n                return std::make_pair(cpp_state, py_state);\n            }));\n#endif\n\n    exercise_trampoline::wrap(m);\n}\n"
  },
  {
    "path": "tests/test_pickling.py",
    "content": "from __future__ import annotations\n\nimport pickle\nimport re\nimport sys\n\nimport pytest\n\nimport env\nfrom pybind11_tests import pickling as m\n\n\ndef all_pickle_protocols():\n    assert pickle.HIGHEST_PROTOCOL >= 0\n    return range(pickle.HIGHEST_PROTOCOL + 1)\n\n\n@pytest.mark.parametrize(\"protocol\", all_pickle_protocols())\ndef test_pickle_simple_callable(protocol):\n    assert m.simple_callable() == 20220426\n    serialized = pickle.dumps(m.simple_callable, protocol=protocol)\n    assert b\"pybind11_tests.pickling\" in serialized\n    assert b\"simple_callable\" in serialized\n    deserialized = pickle.loads(serialized)\n    assert deserialized() == 20220426\n    assert deserialized is m.simple_callable\n\n    # UNUSUAL: function record pickle roundtrip returns a module, not a function record object:\n    if not env.PYPY:\n        assert (\n            pickle.loads(pickle.dumps(m.simple_callable.__self__, protocol=protocol))\n            is m\n        )\n    # This is not expected to create issues because the only purpose of\n    # `m.simple_callable.__self__` is to enable pickling: the only method it has is\n    # `__reduce_ex__`. Direct access for any other purpose is not supported.\n    # Note that `repr(m.simple_callable.__self__)` shows, e.g.:\n    # `<pybind11_detail_function_record_v1__gcc_libstdcpp_cxxabi1018 object at 0x...>`\n    # It is considered to be as much an implementation detail as the\n    # `pybind11::detail::function_record` C++ type is.\n\n    # @rainwoodman suggested that the unusual pickle roundtrip behavior could be\n    # avoided by changing `reduce_ex_impl()` to produce, e.g.:\n    # `\"__import__('importlib').import_module('pybind11_tests.pickling').simple_callable.__self__\"`\n    # as the argument for the `eval()` function, and adding a getter to the\n    # `function_record_PyTypeObject` that returns `self`. However, the additional code complexity\n    # for this is deemed warranted only if the unusual pickle roundtrip behavior actually\n    # creates issues.\n\n\n@pytest.mark.parametrize(\"cls_name\", [\"Pickleable\", \"PickleableNew\"])\ndef test_roundtrip(cls_name):\n    cls = getattr(m, cls_name)\n    p = cls(\"test_value\")\n    p.setExtra1(15)\n    p.setExtra2(48)\n\n    data = pickle.dumps(p, 2)  # Must use pickle protocol >= 2\n    p2 = pickle.loads(data)\n    assert p2.value() == p.value()\n    assert p2.extra1() == p.extra1()\n    assert p2.extra2() == p.extra2()\n\n\n@pytest.mark.xfail(\"env.PYPY\")\n@pytest.mark.parametrize(\n    \"cls_name\",\n    [\n        pytest.param(\n            \"PickleableWithDict\",\n            marks=pytest.mark.skipif(\n                sys.version_info in ((3, 14, 0, \"beta\", 1), (3, 14, 0, \"beta\", 2)),\n                reason=\"3.14.0b1/2 managed dict bug: https://github.com/python/cpython/issues/133912\",\n            ),\n        ),\n        \"PickleableWithDictNew\",\n    ],\n)\ndef test_roundtrip_with_dict(cls_name):\n    cls = getattr(m, cls_name)\n    p = cls(\"test_value\")\n    p.extra = 15\n    p.dynamic = \"Attribute\"\n\n    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)\n    p2 = pickle.loads(data)\n    assert p2.value == p.value\n    assert p2.extra == p.extra\n    assert p2.dynamic == p.dynamic\n\n\ndef test_enum_pickle():\n    from pybind11_tests import enums as e\n\n    data = pickle.dumps(e.EOne, 2)\n    assert e.EOne == pickle.loads(data)\n\n\n#\n# exercise_trampoline\n#\nclass SimplePyDerived(m.SimpleBase):\n    pass\n\n\ndef test_roundtrip_simple_py_derived():\n    p = SimplePyDerived()\n    p.num = 202\n    p.stored_in_dict = 303\n    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)\n    p2 = pickle.loads(data)\n    assert isinstance(p2, SimplePyDerived)\n    assert p2.num == 202\n    assert p2.stored_in_dict == 303\n\n\ndef test_roundtrip_simple_cpp_derived():\n    p = m.make_SimpleCppDerivedAsBase()\n    assert m.check_dynamic_cast_SimpleCppDerived(p)\n    p.num = 404\n    if not env.PYPY:\n        # To ensure that this unit test is not accidentally invalidated.\n        with pytest.raises(AttributeError):\n            # Mimics the `setstate` C++ implementation.\n            setattr(p, \"__dict__\", {})  # noqa: B010\n    data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)\n    p2 = pickle.loads(data)\n    assert isinstance(p2, m.SimpleBase)\n    assert p2.num == 404\n    # Issue #3062: pickleable base C++ classes can incur object slicing\n    #              if derived typeid is not registered with pybind11\n    assert not m.check_dynamic_cast_SimpleCppDerived(p2)\n\n\ndef test_new_style_pickle_getstate_pos_only():\n    assert (\n        re.match(\n            r\"^__getstate__\\(self: [\\w\\.]+, /\\)\", m.PickleableNew.__getstate__.__doc__\n        )\n        is not None\n    )\n    if hasattr(m, \"PickleableWithDictNew\"):\n        assert (\n            re.match(\n                r\"^__getstate__\\(self: [\\w\\.]+, /\\)\",\n                m.PickleableWithDictNew.__getstate__.__doc__,\n            )\n            is not None\n        )\n"
  },
  {
    "path": "tests/test_potentially_slicing_weak_ptr.cpp",
    "content": "// Copyright (c) 2025 The pybind Community.\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n\n#include \"pybind11_tests.h\"\n\n#include <memory>\n\nnamespace pybind11_tests {\nnamespace potentially_slicing_weak_ptr {\n\ntemplate <int> // Using int as a trick to easily generate multiple types.\nstruct VirtBase {\n    VirtBase() = default;\n    virtual ~VirtBase() = default;\n    VirtBase(const VirtBase &) = delete;\n    virtual int get_code() { return 100; }\n};\n\nusing VirtBaseSH = VirtBase<0>; // for testing with py::smart_holder\nusing VirtBaseSP = VirtBase<1>; // for testing with std::shared_ptr as holder\n\n// Similar to trampoline_self_life_support\nstruct trampoline_is_alive_simple {\n    std::uint64_t magic_token = 197001010000u;\n\n    trampoline_is_alive_simple() = default;\n\n    ~trampoline_is_alive_simple() { magic_token = 20380118191407u; }\n\n    trampoline_is_alive_simple(const trampoline_is_alive_simple &other) = default;\n    trampoline_is_alive_simple(trampoline_is_alive_simple &&other) noexcept\n        : magic_token(other.magic_token) {\n        other.magic_token = 20380118191407u;\n    }\n\n    trampoline_is_alive_simple &operator=(const trampoline_is_alive_simple &) = delete;\n    trampoline_is_alive_simple &operator=(trampoline_is_alive_simple &&) = delete;\n};\n\ntemplate <typename VB>\nconst char *determine_trampoline_state(const std::shared_ptr<VB> &sp) {\n    if (!sp) {\n        return \"sp nullptr\";\n    }\n    auto *tias = dynamic_cast<trampoline_is_alive_simple *>(sp.get());\n    if (!tias) {\n        return \"dynamic_cast failed\";\n    }\n    if (tias->magic_token == 197001010000u) {\n        return \"trampoline alive\";\n    }\n    if (tias->magic_token == 20380118191407u) {\n        return \"trampoline DEAD\";\n    }\n    return \"UNDEFINED BEHAVIOR\";\n}\n\nstruct PyVirtBaseSH : VirtBaseSH, py::trampoline_self_life_support, trampoline_is_alive_simple {\n    using VirtBaseSH::VirtBaseSH;\n    int get_code() override { PYBIND11_OVERRIDE(int, VirtBaseSH, get_code); }\n};\n\nstruct PyVirtBaseSP : VirtBaseSP, trampoline_is_alive_simple { // self-life-support not available\n    using VirtBaseSP::VirtBaseSP;\n    int get_code() override { PYBIND11_OVERRIDE(int, VirtBaseSP, get_code); }\n};\n\ntemplate <typename VB>\nstd::shared_ptr<VB> rtrn_obj_cast_shared_ptr(py::handle obj) {\n    return obj.cast<std::shared_ptr<VB>>();\n}\n\n// There is no type_caster<std::weak_ptr<VB>>, and to minimize code complexity\n// we do not want to add one, therefore we have to return a shared_ptr here.\ntemplate <typename VB>\nstd::shared_ptr<VB> rtrn_potentially_slicing_shared_ptr(py::handle obj) {\n    return py::potentially_slicing_weak_ptr<VB>(obj).lock();\n}\n\ntemplate <typename VB>\nstruct SpOwner {\n    void set_sp(const std::shared_ptr<VB> &sp_) { sp = sp_; }\n\n    int get_code() const {\n        if (!sp) {\n            return -888;\n        }\n        return sp->get_code();\n    }\n\n    const char *get_trampoline_state() const { return determine_trampoline_state(sp); }\n\nprivate:\n    std::shared_ptr<VB> sp;\n};\n\ntemplate <typename VB>\nstruct WpOwner {\n    void set_wp(const std::weak_ptr<VB> &wp_) { wp = wp_; }\n\n    int get_code() const {\n        auto sp = wp.lock();\n        if (!sp) {\n            return -999;\n        }\n        return sp->get_code();\n    }\n\n    const char *get_trampoline_state() const { return determine_trampoline_state(wp.lock()); }\n\nprivate:\n    std::weak_ptr<VB> wp;\n};\n\ntemplate <typename VB>\nvoid wrap(py::module_ &m,\n          const char *roc_pyname,\n          const char *rps_pyname,\n          const char *spo_pyname,\n          const char *wpo_pyname) {\n    m.def(roc_pyname, rtrn_obj_cast_shared_ptr<VB>);\n    m.def(rps_pyname, rtrn_potentially_slicing_shared_ptr<VB>);\n\n    py::classh<SpOwner<VB>>(m, spo_pyname)\n        .def(py::init<>())\n        .def(\"set_sp\", &SpOwner<VB>::set_sp)\n        .def(\"get_code\", &SpOwner<VB>::get_code)\n        .def(\"get_trampoline_state\", &SpOwner<VB>::get_trampoline_state);\n\n    py::classh<WpOwner<VB>>(m, wpo_pyname)\n        .def(py::init<>())\n        .def(\"set_wp\",\n             [](WpOwner<VB> &self, py::handle obj) {\n                 self.set_wp(obj.cast<std::shared_ptr<VB>>());\n             })\n        .def(\"set_wp_potentially_slicing\",\n             [](WpOwner<VB> &self, py::handle obj) {\n                 self.set_wp(py::potentially_slicing_weak_ptr<VB>(obj));\n             })\n        .def(\"get_code\", &WpOwner<VB>::get_code)\n        .def(\"get_trampoline_state\", &WpOwner<VB>::get_trampoline_state);\n}\n\n} // namespace potentially_slicing_weak_ptr\n} // namespace pybind11_tests\n\nusing namespace pybind11_tests::potentially_slicing_weak_ptr;\n\nTEST_SUBMODULE(potentially_slicing_weak_ptr, m) {\n    py::classh<VirtBaseSH, PyVirtBaseSH>(m, \"VirtBaseSH\")\n        .def(py::init<>())\n        .def(\"get_code\", &VirtBaseSH::get_code);\n\n    py::class_<VirtBaseSP, std::shared_ptr<VirtBaseSP>, PyVirtBaseSP>(m, \"VirtBaseSP\")\n        .def(py::init<>())\n        .def(\"get_code\", &VirtBaseSP::get_code);\n\n    wrap<VirtBaseSH>(m,\n                     \"SH_rtrn_obj_cast_shared_ptr\",\n                     \"SH_rtrn_potentially_slicing_shared_ptr\",\n                     \"SH_SpOwner\",\n                     \"SH_WpOwner\");\n\n    wrap<VirtBaseSP>(m,\n                     \"SP_rtrn_obj_cast_shared_ptr\",\n                     \"SP_rtrn_potentially_slicing_shared_ptr\",\n                     \"SP_SpOwner\",\n                     \"SP_WpOwner\");\n}\n"
  },
  {
    "path": "tests/test_potentially_slicing_weak_ptr.py",
    "content": "# Copyright (c) 2025 The pybind Community.\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\n# This module tests the interaction of pybind11's shared_ptr and smart_holder\n# mechanisms with trampoline object lifetime management and inheritance slicing.\n#\n# The following combinations are covered:\n#\n# - Holder type: std::shared_ptr (class_ holder) vs.\n#                py::smart_holder\n# - Conversion function: obj.cast<std::shared_ptr<T>>() vs.\n#                        py::potentially_slicing_weak_ptr<T>(obj)\n# - Python object type: C++ base class vs.\n#                       Python-derived trampoline class\n#\n# The tests verify\n#\n# - that casting or passing Python objects into functions returns usable\n#   std::shared_ptr<T> instances.\n# - that inheritance slicing occurs as expected in controlled cases\n#   (issue #1333).\n# - that surprising weak_ptr behavior (issue #5623) can be reproduced when\n#   smart_holder is used.\n# - that the trampoline object remains alive in all situations\n#   (no use-after-free) as long as the C++ shared_ptr exists.\n#\n# Where applicable, trampoline state is introspected to confirm whether the\n# C++ object retains knowledge of the Python override or has fallen back to\n# the base implementation.\n\nfrom __future__ import annotations\n\nimport gc\nimport weakref\n\nimport pytest\n\nimport env\nimport pybind11_tests.potentially_slicing_weak_ptr as m\n\n\nclass PyDrvdSH(m.VirtBaseSH):\n    def get_code(self):\n        return 200\n\n\nclass PyDrvdSP(m.VirtBaseSP):\n    def get_code(self):\n        return 200\n\n\nVIRT_BASE_TYPES = {\n    \"SH\": {100: m.VirtBaseSH, 200: PyDrvdSH},\n    \"SP\": {100: m.VirtBaseSP, 200: PyDrvdSP},\n}\n\nRTRN_FUNCS = {\n    \"SH\": {\n        \"oc\": m.SH_rtrn_obj_cast_shared_ptr,\n        \"ps\": m.SH_rtrn_potentially_slicing_shared_ptr,\n    },\n    \"SP\": {\n        \"oc\": m.SP_rtrn_obj_cast_shared_ptr,\n        \"ps\": m.SP_rtrn_potentially_slicing_shared_ptr,\n    },\n}\n\nSP_OWNER_TYPES = {\n    \"SH\": m.SH_SpOwner,\n    \"SP\": m.SP_SpOwner,\n}\n\nWP_OWNER_TYPES = {\n    \"SH\": m.SH_WpOwner,\n    \"SP\": m.SP_WpOwner,\n}\n\nGC_IS_RELIABLE = not (env.PYPY or env.GRAALPY)\n\n\n@pytest.mark.parametrize(\"expected_code\", [100, 200])\n@pytest.mark.parametrize(\"rtrn_kind\", [\"oc\", \"ps\"])\n@pytest.mark.parametrize(\"holder_kind\", [\"SH\", \"SP\"])\ndef test_rtrn_obj_cast_shared_ptr(holder_kind, rtrn_kind, expected_code):\n    obj = VIRT_BASE_TYPES[holder_kind][expected_code]()\n    ptr = RTRN_FUNCS[holder_kind][rtrn_kind](obj)\n    assert ptr.get_code() == expected_code\n    objref = weakref.ref(obj)\n    del obj\n    gc.collect()\n    assert ptr.get_code() == expected_code  # the ptr Python object keeps obj alive\n    assert objref() is not None\n    del ptr\n    gc.collect()\n    if GC_IS_RELIABLE:\n        assert objref() is None\n\n\n@pytest.mark.parametrize(\"expected_code\", [100, 200])\n@pytest.mark.parametrize(\"holder_kind\", [\"SH\", \"SP\"])\ndef test_with_sp_owner(holder_kind, expected_code):\n    spo = SP_OWNER_TYPES[holder_kind]()\n    assert spo.get_code() == -888\n    assert spo.get_trampoline_state() == \"sp nullptr\"\n\n    obj = VIRT_BASE_TYPES[holder_kind][expected_code]()\n    assert obj.get_code() == expected_code\n\n    spo.set_sp(obj)\n    assert spo.get_code() == expected_code\n    expected_trampoline_state = (\n        \"dynamic_cast failed\" if expected_code == 100 else \"trampoline alive\"\n    )\n    assert spo.get_trampoline_state() == expected_trampoline_state\n\n    del obj\n    gc.collect()\n    if holder_kind == \"SH\":\n        assert spo.get_code() == expected_code\n    elif GC_IS_RELIABLE:\n        assert (\n            spo.get_code() == 100\n        )  # see issue #1333 (inheritance slicing) and PR #5624\n    assert spo.get_trampoline_state() == expected_trampoline_state\n\n\n@pytest.mark.parametrize(\"expected_code\", [100, 200])\n@pytest.mark.parametrize(\"set_meth\", [\"set_wp\", \"set_wp_potentially_slicing\"])\n@pytest.mark.parametrize(\"holder_kind\", [\"SH\", \"SP\"])\ndef test_with_wp_owner(holder_kind, set_meth, expected_code):\n    wpo = WP_OWNER_TYPES[holder_kind]()\n    assert wpo.get_code() == -999\n    assert wpo.get_trampoline_state() == \"sp nullptr\"\n\n    obj = VIRT_BASE_TYPES[holder_kind][expected_code]()\n    assert obj.get_code() == expected_code\n\n    getattr(wpo, set_meth)(obj)\n    if (\n        holder_kind == \"SP\"\n        or expected_code == 100\n        or set_meth == \"set_wp_potentially_slicing\"\n    ):\n        assert wpo.get_code() == expected_code\n    else:\n        assert wpo.get_code() == -999  # see issue #5623 (weak_ptr expired) and PR #5624\n    if expected_code == 100:\n        expected_trampoline_state = \"dynamic_cast failed\"\n    elif holder_kind == \"SH\" and set_meth == \"set_wp\":\n        expected_trampoline_state = \"sp nullptr\"\n    else:\n        expected_trampoline_state = \"trampoline alive\"\n    assert wpo.get_trampoline_state() == expected_trampoline_state\n\n    del obj\n    gc.collect()\n    if GC_IS_RELIABLE:\n        assert wpo.get_code() == -999\n\n\ndef test_potentially_slicing_weak_ptr_not_convertible_error():\n    with pytest.raises(Exception) as excinfo:\n        m.SH_rtrn_potentially_slicing_shared_ptr(\"\")\n    assert str(excinfo.value) == (\n        '\"str\" object is not convertible to std::weak_ptr<T>'\n        \" (with T = pybind11_tests::potentially_slicing_weak_ptr::VirtBase<0>)\"\n    )\n    with pytest.raises(Exception) as excinfo:\n        m.SP_rtrn_potentially_slicing_shared_ptr([])\n    assert str(excinfo.value) == (\n        '\"list\" object is not convertible to std::weak_ptr<T>'\n        \" (with T = pybind11_tests::potentially_slicing_weak_ptr::VirtBase<1>)\"\n    )\n"
  },
  {
    "path": "tests/test_python_multiple_inheritance.cpp",
    "content": "#include \"pybind11_tests.h\"\n\nnamespace test_python_multiple_inheritance {\n\n// Copied from:\n// https://github.com/google/clif/blob/5718e4d0807fd3b6a8187dde140069120b81ecef/clif/testing/python_multiple_inheritance.h\n\nstruct CppBase {\n    explicit CppBase(int value) : base_value(value) {}\n    int get_base_value() const { return base_value; }\n    void reset_base_value(int new_value) { base_value = new_value; }\n\nprivate:\n    int base_value;\n};\n\nstruct CppDrvd : CppBase {\n    explicit CppDrvd(int value) : CppBase(value), drvd_value(value * 3) {}\n    int get_drvd_value() const { return drvd_value; }\n    void reset_drvd_value(int new_value) { drvd_value = new_value; }\n\n    int get_base_value_from_drvd() const { return get_base_value(); }\n    void reset_base_value_from_drvd(int new_value) { reset_base_value(new_value); }\n\nprivate:\n    int drvd_value;\n};\n\n} // namespace test_python_multiple_inheritance\n\nTEST_SUBMODULE(python_multiple_inheritance, m) {\n    using namespace test_python_multiple_inheritance;\n\n    py::class_<CppBase>(m, \"CppBase\")\n        .def(py::init<int>())\n        .def(\"get_base_value\", &CppBase::get_base_value)\n        .def(\"reset_base_value\", &CppBase::reset_base_value);\n\n    py::class_<CppDrvd, CppBase>(m, \"CppDrvd\")\n        .def(py::init<int>())\n        .def(\"get_drvd_value\", &CppDrvd::get_drvd_value)\n        .def(\"reset_drvd_value\", &CppDrvd::reset_drvd_value)\n        .def(\"get_base_value_from_drvd\", &CppDrvd::get_base_value_from_drvd)\n        .def(\"reset_base_value_from_drvd\", &CppDrvd::reset_base_value_from_drvd);\n}\n"
  },
  {
    "path": "tests/test_python_multiple_inheritance.py",
    "content": "# Adapted from:\n# https://github.com/google/clif/blob/5718e4d0807fd3b6a8187dde140069120b81ecef/clif/testing/python/python_multiple_inheritance_test.py\nfrom __future__ import annotations\n\nfrom pybind11_tests import python_multiple_inheritance as m\n\n\nclass PC(m.CppBase):\n    pass\n\n\nclass PPCC(PC, m.CppDrvd):\n    pass\n\n\ndef test_PC():\n    d = PC(11)\n    assert d.get_base_value() == 11\n    d.reset_base_value(13)\n    assert d.get_base_value() == 13\n\n\ndef test_PPCC():\n    d = PPCC(11)\n    assert d.get_drvd_value() == 33\n    d.reset_drvd_value(55)\n    assert d.get_drvd_value() == 55\n\n    assert d.get_base_value() == 11\n    assert d.get_base_value_from_drvd() == 11\n    d.reset_base_value(20)\n    assert d.get_base_value() == 20\n    assert d.get_base_value_from_drvd() == 20\n    d.reset_base_value_from_drvd(30)\n    assert d.get_base_value() == 30\n    assert d.get_base_value_from_drvd() == 30\n"
  },
  {
    "path": "tests/test_pytypes.cpp",
    "content": "/*\n    tests/test_pytypes.cpp -- Python type casters\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n#include <pybind11/typing.h>\n\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\n//__has_include has been part of C++17, no need to check it\n#if defined(PYBIND11_CPP20) && __has_include(<ranges>)\n#    if !defined(PYBIND11_COMPILER_CLANG) || __clang_major__ >= 16 // llvm/llvm-project#52696\n#        define PYBIND11_TEST_PYTYPES_HAS_RANGES\n#        include <ranges>\n#    endif\n#endif\n\nnamespace external {\nnamespace detail {\nbool check(PyObject *o) { return PyFloat_Check(o) != 0; }\n\nPyObject *conv(PyObject *o) {\n    PyObject *ret = nullptr;\n    if (PyLong_Check(o)) {\n        double v = PyLong_AsDouble(o);\n        if (!(v == -1.0 && PyErr_Occurred())) {\n            ret = PyFloat_FromDouble(v);\n        }\n    } else {\n        py::set_error(PyExc_TypeError, \"Unexpected type\");\n    }\n    return ret;\n}\n\nPyObject *default_constructed() { return PyFloat_FromDouble(0.0); }\n} // namespace detail\nclass float_ : public py::object {\n    PYBIND11_OBJECT_CVT(float_, py::object, external::detail::check, external::detail::conv)\n\n    float_() : py::object(external::detail::default_constructed(), stolen_t{}) {}\n\n    double get_value() const { return PyFloat_AsDouble(this->ptr()); }\n};\n} // namespace external\n\nnamespace pybind11 {\nnamespace detail {\ntemplate <>\nstruct handle_type_name<external::float_> {\n    static constexpr auto name = const_name(\"float\");\n};\n} // namespace detail\n} // namespace pybind11\n\nnamespace implicit_conversion_from_0_to_handle {\n// Uncomment to trigger compiler error. Note: Before PR #4008 this used to compile successfully.\n// void expected_to_trigger_compiler_error() { py::handle(0); }\n} // namespace implicit_conversion_from_0_to_handle\n\n// Used to validate systematically that PR #4008 does/did NOT change the behavior.\nvoid pure_compile_tests_for_handle_from_PyObject_pointers() {\n    {\n        PyObject *ptr = Py_None;\n        py::handle{ptr};\n    }\n    {\n        PyObject *const ptr = Py_None;\n        py::handle{ptr};\n    }\n    // Uncomment to trigger compiler errors.\n    // PyObject const *               ptr = Py_None; py::handle{ptr};\n    // PyObject const *const          ptr = Py_None; py::handle{ptr};\n    // PyObject volatile *            ptr = Py_None; py::handle{ptr};\n    // PyObject volatile *const       ptr = Py_None; py::handle{ptr};\n    // PyObject const volatile *      ptr = Py_None; py::handle{ptr};\n    // PyObject const volatile *const ptr = Py_None; py::handle{ptr};\n}\n\nnamespace handle_from_move_only_type_with_operator_PyObject {\n\n// Reduced from\n// https://github.com/pytorch/pytorch/blob/279634f384662b7c3a9f8bf7ccc3a6afd2f05657/torch/csrc/utils/object_ptr.h\nstruct operator_ncnst {\n    operator_ncnst() = default;\n    operator_ncnst(operator_ncnst &&) = default;\n    operator PyObject *() /* */ { return Py_None; } // NOLINT(google-explicit-constructor)\n};\n\nstruct operator_const {\n    operator_const() = default;\n    operator_const(operator_const &&) = default;\n    operator PyObject *() const { return Py_None; } // NOLINT(google-explicit-constructor)\n};\n\nbool from_ncnst() {\n    operator_ncnst obj;\n    auto h = py::handle(obj);  // Critical part of test: does this compile?\n    return h.ptr() == Py_None; // Just something.\n}\n\nbool from_const() {\n    operator_const obj;\n    auto h = py::handle(obj);  // Critical part of test: does this compile?\n    return h.ptr() == Py_None; // Just something.\n}\n\nvoid m_defs(py::module_ &m) {\n    m.def(\"handle_from_move_only_type_with_operator_PyObject_ncnst\", from_ncnst);\n    m.def(\"handle_from_move_only_type_with_operator_PyObject_const\", from_const);\n}\n\n} // namespace handle_from_move_only_type_with_operator_PyObject\n\n#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)\nnamespace literals {\nenum Color { RED = 0, BLUE = 1 };\n\ntypedef py::typing::Literal<\"26\",\n                            \"0x1A\",\n                            \"\\\"hello world\\\"\",\n                            \"b\\\"hello world\\\"\",\n                            \"u\\\"hello world\\\"\",\n                            \"True\",\n                            \"Color.RED\",\n                            \"None\">\n    LiteralFoo;\n} // namespace literals\nnamespace typevar {\ntypedef py::typing::TypeVar<\"T\"> TypeVarT;\ntypedef py::typing::TypeVar<\"V\"> TypeVarV;\n} // namespace typevar\n#endif\n\n// Custom type for testing arg_name/return_name type hints\n// RealNumber:\n// * in arguments -> float | int\n// * in return -> float\n// The choice of types is not really useful, but just made different for testing purposes.\n// According to `PEP 484 – Type Hints` annotating with `float` also allows `int`,\n// so using `float | int` could be replaced by just `float`.\n\nstruct RealNumber {\n    double value;\n};\n\nnamespace pybind11 {\nnamespace detail {\n\ntemplate <>\nstruct type_caster<RealNumber> {\n    PYBIND11_TYPE_CASTER(RealNumber, io_name(\"float | int\", \"float\"));\n\n    static handle cast(const RealNumber &number, return_value_policy, handle) {\n        return py::float_(number.value).release();\n    }\n\n    bool load(handle src, bool convert) {\n        // If we're in no-convert mode, only load if given a float\n        if (!convert && !py::isinstance<py::float_>(src)) {\n            return false;\n        }\n        if (!py::isinstance<py::float_>(src) && !py::isinstance<py::int_>(src)) {\n            return false;\n        }\n        value.value = src.cast<double>();\n        return true;\n    }\n};\n\n} // namespace detail\n} // namespace pybind11\n\nTEST_SUBMODULE(pytypes, m) {\n    m.def(\"obj_class_name\", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });\n\n    handle_from_move_only_type_with_operator_PyObject::m_defs(m);\n\n    // test_bool\n    m.def(\"get_bool\", [] { return py::bool_(false); });\n    // test_int\n    m.def(\"get_int\", [] { return py::int_(0); });\n    // test_iterator\n    m.def(\"get_iterator\", [] { return py::iterator(); });\n    // test_iterable\n    m.def(\"get_iterable\", [] { return py::iterable(); });\n    m.def(\"get_first_item_from_iterable\", [](const py::iterable &iter) {\n        // This tests the postfix increment operator\n        py::iterator it = iter.begin();\n        py::iterator it2 = it++;\n        return *it2;\n    });\n    m.def(\"get_second_item_from_iterable\", [](const py::iterable &iter) {\n        // This tests the prefix increment operator\n        py::iterator it = iter.begin();\n        ++it;\n        return *it;\n    });\n    m.def(\"get_frozenset_from_iterable\",\n          [](const py::iterable &iter) { return py::frozenset(iter); });\n    m.def(\"get_list_from_iterable\", [](const py::iterable &iter) { return py::list(iter); });\n    m.def(\"get_set_from_iterable\", [](const py::iterable &iter) { return py::set(iter); });\n    m.def(\"get_tuple_from_iterable\", [](const py::iterable &iter) { return py::tuple(iter); });\n    // test_float\n    m.def(\"get_float\", [] { return py::float_(0.0f); });\n    m.def(\"float_roundtrip\", [](py::float_ f) { return f; });\n    // test_list\n    m.def(\"list_no_args\", []() { return py::list{}; });\n    m.def(\"list_ssize_t\", []() { return py::list{(py::ssize_t) 0}; });\n    m.def(\"list_size_t\", []() { return py::list{(py::size_t) 0}; });\n    m.def(\"list_insert_ssize_t\", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); });\n    m.def(\"list_insert_size_t\", [](py::list *l) { return l->insert((py::size_t) 3, 57); });\n    m.def(\"list_clear\", [](py::list *l) { l->clear(); });\n    m.def(\"get_list\", []() {\n        py::list list;\n        list.append(\"value\");\n        py::print(\"Entry at position 0:\", list[0]);\n        list[0] = py::str(\"overwritten\");\n        list.insert(0, \"inserted-0\");\n        list.insert(2, \"inserted-2\");\n        return list;\n    });\n    m.def(\"print_list\", [](const py::list &list) {\n        int index = 0;\n        for (auto item : list) {\n            py::print(\"list item {}: {}\"_s.format(index++, item));\n        }\n    });\n    // test_none\n    m.def(\"get_none\", [] { return py::none(); });\n    m.def(\"print_none\", [](const py::none &none) { py::print(\"none: {}\"_s.format(none)); });\n\n    // test_set, test_frozenset\n    m.def(\"get_set\", []() {\n        py::set set;\n        set.add(py::str(\"key1\"));\n        set.add(\"key2\");\n        set.add(std::string(\"key3\"));\n        return set;\n    });\n    m.def(\"get_frozenset\", []() {\n        py::set set;\n        set.add(py::str(\"key1\"));\n        set.add(\"key2\");\n        set.add(std::string(\"key3\"));\n        return py::frozenset(set);\n    });\n    m.def(\"print_anyset\", [](const py::anyset &set) {\n        for (auto item : set) {\n            py::print(\"key:\", item);\n        }\n    });\n    m.def(\"anyset_size\", [](const py::anyset &set) { return set.size(); });\n    m.def(\"anyset_empty\", [](const py::anyset &set) { return set.empty(); });\n    m.def(\"anyset_contains\",\n          [](const py::anyset &set, const py::object &key) { return set.contains(key); });\n    m.def(\"anyset_contains\",\n          [](const py::anyset &set, const char *key) { return set.contains(key); });\n    m.def(\"set_add\", [](py::set &set, const py::object &key) { set.add(key); });\n    m.def(\"set_clear\", [](py::set &set) { set.clear(); });\n\n    // test_dict\n    m.def(\"get_dict\", []() { return py::dict(\"key\"_a = \"value\"); });\n    m.def(\"print_dict\", [](const py::dict &dict) {\n        for (auto item : dict) {\n            py::print(\"key: {}, value={}\"_s.format(item.first, item.second));\n        }\n    });\n    m.def(\"dict_keyword_constructor\", []() {\n        auto d1 = py::dict(\"x\"_a = 1, \"y\"_a = 2);\n        auto d2 = py::dict(\"z\"_a = 3, **d1);\n        return d2;\n    });\n    m.def(\"dict_contains\",\n          [](const py::dict &dict, const py::object &val) { return dict.contains(val); });\n    m.def(\"dict_contains\",\n          [](const py::dict &dict, const char *val) { return dict.contains(val); });\n\n    // test_tuple\n    m.def(\"tuple_no_args\", []() { return py::tuple{}; });\n    m.def(\"tuple_ssize_t\", []() { return py::tuple{(py::ssize_t) 0}; });\n    m.def(\"tuple_size_t\", []() { return py::tuple{(py::size_t) 0}; });\n    m.def(\"get_tuple\", []() { return py::make_tuple(42, py::none(), \"spam\"); });\n\n    // test_simple_namespace\n    m.def(\"get_simple_namespace\", []() {\n        auto ns = py::module_::import(\"types\").attr(\"SimpleNamespace\")(\n            \"attr\"_a = 42, \"x\"_a = \"foo\", \"wrong\"_a = 1);\n        py::delattr(ns, \"wrong\");\n        py::setattr(ns, \"right\", py::int_(2));\n        return ns;\n    });\n\n    // test_str\n    m.def(\"str_from_char_ssize_t\", []() { return py::str{\"red\", (py::ssize_t) 3}; });\n    m.def(\"str_from_char_size_t\", []() { return py::str{\"blue\", (py::size_t) 4}; });\n    m.def(\"str_from_string\", []() { return py::str(std::string(\"baz\")); });\n    m.def(\"str_from_std_string_input\", [](const std::string &stri) { return py::str(stri); });\n    m.def(\"str_from_cstr_input\", [](const char *c_str) { return py::str(c_str); });\n    m.def(\"str_from_bytes\", []() { return py::str(py::bytes(\"boo\", 3)); });\n    m.def(\"str_from_bytes_input\",\n          [](const py::bytes &encoded_str) { return py::str(encoded_str); });\n\n    m.def(\"str_from_object\", [](const py::object &obj) { return py::str(obj); });\n    m.def(\"repr_from_object\", [](const py::object &obj) { return py::repr(obj); });\n    m.def(\"str_from_handle\", [](py::handle h) { return py::str(h); });\n    m.def(\"str_from_string_from_str\",\n          [](const py::str &obj) { return py::str(static_cast<std::string>(obj)); });\n\n    m.def(\"str_format\", []() {\n        auto s1 = \"{} + {} = {}\"_s.format(1, 2, 3);\n        auto s2 = \"{a} + {b} = {c}\"_s.format(\"a\"_a = 1, \"b\"_a = 2, \"c\"_a = 3);\n        return py::make_tuple(s1, s2);\n    });\n\n    // test_bytes\n    m.def(\"bytes_from_char_ssize_t\", []() { return py::bytes{\"green\", (py::ssize_t) 5}; });\n    m.def(\"bytes_from_char_size_t\", []() { return py::bytes{\"purple\", (py::size_t) 6}; });\n    m.def(\"bytes_from_string\", []() { return py::bytes(std::string(\"foo\")); });\n    m.def(\"bytes_from_str\", []() { return py::bytes(py::str(\"bar\", 3)); });\n\n    // test bytearray\n    m.def(\"bytearray_from_char_ssize_t\", []() { return py::bytearray{\"$%\", (py::ssize_t) 2}; });\n    m.def(\"bytearray_from_char_size_t\", []() { return py::bytearray{\"@$!\", (py::size_t) 3}; });\n    m.def(\"bytearray_from_string\", []() { return py::bytearray(std::string(\"foo\")); });\n    m.def(\"bytearray_size\", []() { return py::bytearray(\"foo\").size(); });\n\n    // test_capsule\n    m.def(\"return_capsule_with_destructor\", []() {\n        py::print(\"creating capsule\");\n        return py::capsule([]() { py::print(\"destructing capsule\"); });\n    });\n\n    m.def(\"return_renamed_capsule_with_destructor\", []() {\n        py::print(\"creating capsule\");\n        auto cap = py::capsule([]() { py::print(\"destructing capsule\"); });\n        static const char *capsule_name = \"test_name1\";\n        py::print(\"renaming capsule\");\n        cap.set_name(capsule_name);\n        return cap;\n    });\n\n    m.def(\"return_capsule_with_destructor_2\", []() {\n        py::print(\"creating capsule\");\n        return py::capsule((void *) 1234, [](void *ptr) {\n            py::print(\"destructing capsule: {}\"_s.format((size_t) ptr));\n        });\n    });\n\n    m.def(\"return_capsule_with_destructor_3\", []() {\n        py::print(\"creating capsule\");\n        auto cap = py::capsule((void *) 1233, \"oname\", [](void *ptr) {\n            py::print(\"destructing capsule: {}\"_s.format((size_t) ptr));\n        });\n        py::print(\"original name: {}\"_s.format(cap.name()));\n        return cap;\n    });\n\n    m.def(\"return_renamed_capsule_with_destructor_2\", []() {\n        py::print(\"creating capsule\");\n        auto cap = py::capsule((void *) 1234, [](void *ptr) {\n            py::print(\"destructing capsule: {}\"_s.format((size_t) ptr));\n        });\n        static const char *capsule_name = \"test_name2\";\n        py::print(\"renaming capsule\");\n        cap.set_name(capsule_name);\n        return cap;\n    });\n\n    m.def(\"return_capsule_with_name_and_destructor\", []() {\n        auto capsule = py::capsule((void *) 12345, \"pointer type description\", [](PyObject *ptr) {\n            if (ptr) {\n                const auto *name = PyCapsule_GetName(ptr);\n                py::print(\"destructing capsule ({}, '{}')\"_s.format(\n                    (size_t) PyCapsule_GetPointer(ptr, name), name));\n            }\n        });\n\n        capsule.set_pointer((void *) 1234);\n\n        // Using get_pointer<T>()\n        void *contents1 = static_cast<void *>(capsule);\n        void *contents2 = capsule.get_pointer();\n        void *contents3 = capsule.get_pointer<void>();\n\n        auto result1 = reinterpret_cast<size_t>(contents1);\n        auto result2 = reinterpret_cast<size_t>(contents2);\n        auto result3 = reinterpret_cast<size_t>(contents3);\n\n        py::print(\n            \"created capsule ({}, '{}')\"_s.format(result1 & result2 & result3, capsule.name()));\n        return capsule;\n    });\n\n    m.def(\"return_capsule_with_explicit_nullptr_dtor\", []() {\n        py::print(\"creating capsule with explicit nullptr dtor\");\n        return py::capsule(reinterpret_cast<void *>(1234),\n                           static_cast<void (*)(void *)>(nullptr)); // PR #4221\n    });\n\n    // test_accessors\n    m.def(\"accessor_api\", [](const py::object &o) {\n        auto d = py::dict();\n\n        d[\"basic_attr\"] = o.attr(\"basic_attr\");\n\n        auto l = py::list();\n        for (auto item : o.attr(\"begin_end\")) {\n            l.append(item);\n        }\n        d[\"begin_end\"] = l;\n\n        d[\"operator[object]\"] = o.attr(\"d\")[\"operator[object]\"_s];\n        d[\"operator[char *]\"] = o.attr(\"d\")[\"operator[char *]\"];\n\n        d[\"attr(object)\"] = o.attr(\"sub\").attr(\"attr_obj\");\n        d[\"attr(char *)\"] = o.attr(\"sub\").attr(\"attr_char\");\n        try {\n            o.attr(\"sub\").attr(\"missing\").ptr();\n        } catch (const py::error_already_set &) {\n            d[\"missing_attr_ptr\"] = \"raised\"_s;\n        }\n        try {\n            o.attr(\"missing\").attr(\"doesn't matter\");\n        } catch (const py::error_already_set &) {\n            d[\"missing_attr_chain\"] = \"raised\"_s;\n        }\n\n        d[\"is_none\"] = o.attr(\"basic_attr\").is_none();\n\n        d[\"operator()\"] = o.attr(\"func\")(1);\n        d[\"operator*\"] = o.attr(\"func\")(*o.attr(\"begin_end\"));\n\n        // Test implicit conversion\n        py::list implicit_list = o.attr(\"begin_end\");\n        d[\"implicit_list\"] = implicit_list;\n        py::dict implicit_dict = o.attr(\"__dict__\");\n        d[\"implicit_dict\"] = implicit_dict;\n\n        return d;\n    });\n\n    m.def(\"tuple_accessor\", [](const py::tuple &existing_t) {\n        try {\n            existing_t[0] = 1;\n        } catch (const py::error_already_set &) {\n            // --> Python system error\n            // Only new tuples (refcount == 1) are mutable\n            auto new_t = py::tuple(3);\n            for (size_t i = 0; i < new_t.size(); ++i) {\n                new_t[i] = i;\n            }\n            return new_t;\n        }\n        return py::tuple();\n    });\n\n    m.def(\"accessor_assignment\", []() {\n        auto l = py::list(1);\n        l[0] = 0;\n\n        auto d = py::dict();\n        d[\"get\"] = l[0];\n        auto var = l[0];\n        d[\"deferred_get\"] = var;\n        l[0] = 1;\n        d[\"set\"] = l[0];\n        var = 99; // this assignment should not overwrite l[0]\n        d[\"deferred_set\"] = l[0];\n        d[\"var\"] = var;\n\n        return d;\n    });\n\n    m.def(\"accessor_moves\", []() { // See PR #3970\n        py::list return_list;\n#ifdef PYBIND11_HANDLE_REF_DEBUG\n        py::int_ py_int_0(0);\n        py::int_ py_int_42(42);\n        py::str py_str_count(\"count\");\n\n        auto tup = py::make_tuple(0);\n\n        py::sequence seq(tup);\n\n        py::list lst;\n        lst.append(0);\n\n#    define PYBIND11_LOCAL_DEF(...)                                                               \\\n        {                                                                                         \\\n            std::size_t inc_refs = py::handle::inc_ref_counter();                                 \\\n            __VA_ARGS__;                                                                          \\\n            inc_refs = py::handle::inc_ref_counter() - inc_refs;                                  \\\n            return_list.append(inc_refs);                                                         \\\n        }\n\n        PYBIND11_LOCAL_DEF(tup[py_int_0])    // l-value (to have a control)\n        PYBIND11_LOCAL_DEF(tup[py::int_(0)]) // r-value\n\n        PYBIND11_LOCAL_DEF(tup.attr(py_str_count))     // l-value\n        PYBIND11_LOCAL_DEF(tup.attr(py::str(\"count\"))) // r-value\n\n        PYBIND11_LOCAL_DEF(seq[py_int_0])    // l-value\n        PYBIND11_LOCAL_DEF(seq[py::int_(0)]) // r-value\n\n        PYBIND11_LOCAL_DEF(seq.attr(py_str_count))     // l-value\n        PYBIND11_LOCAL_DEF(seq.attr(py::str(\"count\"))) // r-value\n\n        PYBIND11_LOCAL_DEF(lst[py_int_0])    // l-value\n        PYBIND11_LOCAL_DEF(lst[py::int_(0)]) // r-value\n\n        PYBIND11_LOCAL_DEF(lst.attr(py_str_count))     // l-value\n        PYBIND11_LOCAL_DEF(lst.attr(py::str(\"count\"))) // r-value\n\n        auto lst_acc = lst[py::int_(0)];\n        lst_acc = py::int_(42);                    // Detaches lst_acc from lst.\n        PYBIND11_LOCAL_DEF(lst_acc = py_int_42)    // l-value\n        PYBIND11_LOCAL_DEF(lst_acc = py::int_(42)) // r-value\n#    undef PYBIND11_LOCAL_DEF\n#endif\n        return return_list;\n    });\n\n    // test_constructors\n    m.def(\"default_constructors\", []() {\n        return py::dict(\"bytes\"_a = py::bytes(),\n                        \"bytearray\"_a = py::bytearray(),\n                        \"str\"_a = py::str(),\n                        \"bool\"_a = py::bool_(),\n                        \"int\"_a = py::int_(),\n                        \"float\"_a = py::float_(),\n                        \"tuple\"_a = py::tuple(),\n                        \"list\"_a = py::list(),\n                        \"dict\"_a = py::dict(),\n                        \"set\"_a = py::set());\n    });\n\n    m.def(\"converting_constructors\", [](const py::dict &d) {\n        return py::dict(\"bytes\"_a = py::bytes(d[\"bytes\"]),\n                        \"bytearray\"_a = py::bytearray(d[\"bytearray\"]),\n                        \"str\"_a = py::str(d[\"str\"]),\n                        \"bool\"_a = py::bool_(d[\"bool\"]),\n                        \"int\"_a = py::int_(d[\"int\"]),\n                        \"float\"_a = py::float_(d[\"float\"]),\n                        \"tuple\"_a = py::tuple(d[\"tuple\"]),\n                        \"list\"_a = py::list(d[\"list\"]),\n                        \"dict\"_a = py::dict(d[\"dict\"]),\n                        \"set\"_a = py::set(d[\"set\"]),\n                        \"frozenset\"_a = py::frozenset(d[\"frozenset\"]),\n                        \"memoryview\"_a = py::memoryview(d[\"memoryview\"]));\n    });\n\n    m.def(\"cast_functions\", [](const py::dict &d) {\n        // When converting between Python types, obj.cast<T>() should be the same as T(obj)\n        return py::dict(\"bytes\"_a = d[\"bytes\"].cast<py::bytes>(),\n                        \"bytearray\"_a = d[\"bytearray\"].cast<py::bytearray>(),\n                        \"str\"_a = d[\"str\"].cast<py::str>(),\n                        \"bool\"_a = d[\"bool\"].cast<py::bool_>(),\n                        \"int\"_a = d[\"int\"].cast<py::int_>(),\n                        \"float\"_a = d[\"float\"].cast<py::float_>(),\n                        \"tuple\"_a = d[\"tuple\"].cast<py::tuple>(),\n                        \"list\"_a = d[\"list\"].cast<py::list>(),\n                        \"dict\"_a = d[\"dict\"].cast<py::dict>(),\n                        \"set\"_a = d[\"set\"].cast<py::set>(),\n                        \"frozenset\"_a = d[\"frozenset\"].cast<py::frozenset>(),\n                        \"memoryview\"_a = d[\"memoryview\"].cast<py::memoryview>());\n    });\n\n    m.def(\"convert_to_pybind11_str\", [](const py::object &o) { return py::str(o); });\n\n    m.def(\"nonconverting_constructor\",\n          [](const std::string &type, py::object value, bool move) -> py::object {\n              if (type == \"bytes\") {\n                  return move ? py::bytes(std::move(value)) : py::bytes(value);\n              }\n              if (type == \"none\") {\n                  return move ? py::none(std::move(value)) : py::none(value);\n              }\n              if (type == \"ellipsis\") {\n                  return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);\n              }\n              if (type == \"type\") {\n                  return move ? py::type(std::move(value)) : py::type(value);\n              }\n              throw std::runtime_error(\"Invalid type\");\n          });\n\n    m.def(\"get_implicit_casting\", []() {\n        py::dict d;\n        d[\"char*_i1\"] = \"abc\";\n        const char *c2 = \"abc\";\n        d[\"char*_i2\"] = c2;\n        d[\"char*_e\"] = py::cast(c2);\n        d[\"char*_p\"] = py::str(c2);\n\n        d[\"int_i1\"] = 42;\n        int i = 42;\n        d[\"int_i2\"] = i;\n        i++;\n        d[\"int_e\"] = py::cast(i);\n        i++;\n        d[\"int_p\"] = py::int_(i);\n\n        d[\"str_i1\"] = std::string(\"str\");\n        std::string s2(\"str1\");\n        d[\"str_i2\"] = s2;\n        s2[3] = '2';\n        d[\"str_e\"] = py::cast(s2);\n        s2[3] = '3';\n        d[\"str_p\"] = py::str(s2);\n\n        py::list l(2);\n        l[0] = 3;\n        l[1] = py::cast(6);\n        l.append(9);\n        l.append(py::cast(12));\n        l.append(py::int_(15));\n\n        return py::dict(\"d\"_a = d, \"l\"_a = l);\n    });\n\n    // test_print\n    m.def(\"print_function\", []() {\n        py::print(\"Hello, World!\");\n        py::print(1, 2.0, \"three\", true, std::string(\"-- multiple args\"));\n        auto args = py::make_tuple(\"and\", \"a\", \"custom\", \"separator\");\n        py::print(\"*args\", *args, \"sep\"_a = \"-\");\n        py::print(\"no new line here\", \"end\"_a = \" -- \");\n        py::print(\"next print\");\n\n        auto py_stderr = py::module_::import(\"sys\").attr(\"stderr\");\n        py::print(\"this goes to stderr\", \"file\"_a = py_stderr);\n\n        py::print(\"flush\", \"flush\"_a = true);\n\n        py::print(\n            \"{a} + {b} = {c}\"_s.format(\"a\"_a = \"py::print\", \"b\"_a = \"str.format\", \"c\"_a = \"this\"));\n    });\n\n    m.def(\"print_failure\", []() { py::print(42, UnregisteredType()); });\n\n    m.def(\"hash_function\", [](py::object obj) { return py::hash(std::move(obj)); });\n\n    m.def(\"obj_contains\",\n          [](py::object &obj, const py::object &key) { return obj.contains(key); });\n\n    m.def(\"test_number_protocol\", [](const py::object &a, const py::object &b) {\n        py::list l;\n        l.append(a.equal(b));\n        l.append(a.not_equal(b));\n        l.append(a < b);\n        l.append(a <= b);\n        l.append(a > b);\n        l.append(a >= b);\n        l.append(a + b);\n        l.append(a - b);\n        l.append(a * b);\n        l.append(a / b);\n        l.append(a | b);\n        l.append(a & b);\n        l.append(a ^ b);\n        l.append(a >> b);\n        l.append(a << b);\n        return l;\n    });\n\n    m.def(\"test_list_slicing\", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });\n\n    m.def(\"test_list_slicing_default\", [](const py::list &a) { return a[py::slice()]; });\n\n    // See #2361\n    m.def(\"issue2361_str_implicit_copy_none\", []() {\n        py::str is_this_none = py::none();\n        return is_this_none;\n    });\n    m.def(\"issue2361_dict_implicit_copy_none\", []() {\n        py::dict is_this_none = py::none();\n        return is_this_none;\n    });\n\n    m.def(\"test_memoryview_object\", [](const py::buffer &b) { return py::memoryview(b); });\n\n    m.def(\"test_memoryview_buffer_info\",\n          [](const py::buffer &b) { return py::memoryview(b.request()); });\n\n    m.def(\"test_memoryview_from_buffer\", [](bool is_unsigned) {\n        static const int16_t si16[] = {3, 1, 4, 1, 5};\n        static const uint16_t ui16[] = {2, 7, 1, 8};\n        if (is_unsigned) {\n            return py::memoryview::from_buffer(ui16, {4}, {sizeof(uint16_t)});\n        }\n        return py::memoryview::from_buffer(si16, {5}, {sizeof(int16_t)});\n    });\n\n    m.def(\"test_memoryview_from_buffer_nativeformat\", []() {\n        static const char *format = \"@i\";\n        static const int32_t arr[] = {4, 7, 5};\n        return py::memoryview::from_buffer(arr, sizeof(int32_t), format, {3}, {sizeof(int32_t)});\n    });\n\n    m.def(\"test_memoryview_from_buffer_empty_shape\", []() {\n        static const char *buf = \"\";\n        return py::memoryview::from_buffer(buf, 1, \"B\", {}, {});\n    });\n\n    m.def(\"test_memoryview_from_buffer_invalid_strides\", []() {\n        static const char *buf = \"\\x02\\x03\\x04\";\n        return py::memoryview::from_buffer(buf, 1, \"B\", {3}, {});\n    });\n\n    m.def(\"test_memoryview_from_buffer_nullptr\", []() {\n        return py::memoryview::from_buffer(static_cast<void *>(nullptr), 1, \"B\", {}, {});\n    });\n\n    m.def(\"test_memoryview_from_memory\", []() {\n        const char *buf = \"\\xff\\xe1\\xab\\x37\";\n        return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));\n    });\n\n    // test_builtin_functions\n    m.def(\"get_len\", [](py::handle h) { return py::len(h); });\n\n#ifdef PYBIND11_STR_LEGACY_PERMISSIVE\n    m.attr(\"PYBIND11_STR_LEGACY_PERMISSIVE\") = true;\n#endif\n\n    m.def(\"isinstance_pybind11_bytes\",\n          [](py::object o) { return py::isinstance<py::bytes>(std::move(o)); });\n    m.def(\"isinstance_pybind11_str\",\n          [](py::object o) { return py::isinstance<py::str>(std::move(o)); });\n\n    m.def(\"pass_to_pybind11_bytes\", [](py::bytes b) { return py::len(std::move(b)); });\n    m.def(\"pass_to_pybind11_str\", [](py::str s) { return py::len(std::move(s)); });\n    m.def(\"pass_to_std_string\", [](const std::string &s) { return s.size(); });\n\n    // test_weakref\n    m.def(\"weakref_from_handle\", [](py::handle h) { return py::weakref(h); });\n    m.def(\"weakref_from_handle_and_function\",\n          [](py::handle h, py::function f) { return py::weakref(h, std::move(f)); });\n    m.def(\"weakref_from_object\", [](const py::object &o) { return py::weakref(o); });\n    m.def(\"weakref_from_object_and_function\",\n          [](py::object o, py::function f) { return py::weakref(std::move(o), std::move(f)); });\n\n// See PR #3263 for background (https://github.com/pybind/pybind11/pull/3263):\n// pytypes.h could be changed to enforce the \"most correct\" user code below, by removing\n// `const` from iterator `reference` using type aliases, but that will break existing\n// user code.\n#if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)\n// This is \"most correct\" and enforced on these platforms.\n#    define PYBIND11_AUTO_IT auto it\n#else\n    // This works on many platforms and is (unfortunately) reflective of existing user code.\n    // NOLINTNEXTLINE(bugprone-macro-parentheses)\n#    define PYBIND11_AUTO_IT auto &it\n#endif\n\n    m.def(\"tuple_iterator\", []() {\n        auto tup = py::make_tuple(5, 7);\n        int tup_sum = 0;\n        for (PYBIND11_AUTO_IT : tup) {\n            tup_sum += it.cast<int>();\n        }\n        return tup_sum;\n    });\n\n    m.def(\"dict_iterator\", []() {\n        py::dict dct;\n        dct[py::int_(3)] = 5;\n        dct[py::int_(7)] = 11;\n        int kv_sum = 0;\n        for (PYBIND11_AUTO_IT : dct) {\n            kv_sum += it.first.cast<int>() * 100 + it.second.cast<int>();\n        }\n        return kv_sum;\n    });\n\n    m.def(\"passed_iterator\", [](const py::iterator &py_it) {\n        int elem_sum = 0;\n        for (PYBIND11_AUTO_IT : py_it) {\n            elem_sum += it.cast<int>();\n        }\n        return elem_sum;\n    });\n\n#undef PYBIND11_AUTO_IT\n\n    // Tests below this line are for pybind11 IMPLEMENTATION DETAILS:\n\n    m.def(\"sequence_item_get_ssize_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::sequence_item::get(o, (py::ssize_t) 1);\n    });\n    m.def(\"sequence_item_set_ssize_t\", [](const py::object &o) {\n        auto s = py::str{\"peppa\", 5};\n        py::detail::accessor_policies::sequence_item::set(o, (py::ssize_t) 1, s);\n    });\n    m.def(\"sequence_item_get_size_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::sequence_item::get(o, (py::size_t) 2);\n    });\n    m.def(\"sequence_item_set_size_t\", [](const py::object &o) {\n        auto s = py::str{\"george\", 6};\n        py::detail::accessor_policies::sequence_item::set(o, (py::size_t) 2, s);\n    });\n    m.def(\"list_item_get_ssize_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::list_item::get(o, (py::ssize_t) 3);\n    });\n    m.def(\"list_item_set_ssize_t\", [](const py::object &o) {\n        auto s = py::str{\"rebecca\", 7};\n        py::detail::accessor_policies::list_item::set(o, (py::ssize_t) 3, s);\n    });\n    m.def(\"list_item_get_size_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::list_item::get(o, (py::size_t) 4);\n    });\n    m.def(\"list_item_set_size_t\", [](const py::object &o) {\n        auto s = py::str{\"richard\", 7};\n        py::detail::accessor_policies::list_item::set(o, (py::size_t) 4, s);\n    });\n    m.def(\"tuple_item_get_ssize_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::tuple_item::get(o, (py::ssize_t) 5);\n    });\n    m.def(\"tuple_item_set_ssize_t\", []() {\n        auto s0 = py::str{\"emely\", 5};\n        auto s1 = py::str{\"edmond\", 6};\n        auto o = py::tuple{2};\n        py::detail::accessor_policies::tuple_item::set(o, (py::ssize_t) 0, s0);\n        py::detail::accessor_policies::tuple_item::set(o, (py::ssize_t) 1, s1);\n        return o;\n    });\n    m.def(\"tuple_item_get_size_t\", [](const py::object &o) {\n        return py::detail::accessor_policies::tuple_item::get(o, (py::size_t) 6);\n    });\n    m.def(\"tuple_item_set_size_t\", []() {\n        auto s0 = py::str{\"candy\", 5};\n        auto s1 = py::str{\"cat\", 3};\n        auto o = py::tuple{2};\n        py::detail::accessor_policies::tuple_item::set(o, (py::size_t) 1, s1);\n        py::detail::accessor_policies::tuple_item::set(o, (py::size_t) 0, s0);\n        return o;\n    });\n\n    m.def(\"square_float_\", [](const external::float_ &x) -> double {\n        double v = x.get_value();\n        return v * v;\n    });\n\n    m.def(\"tuple_rvalue_getter\", [](const py::tuple &tup) {\n        // tests accessing tuple object with rvalue int\n        for (size_t i = 0; i < tup.size(); i++) {\n            auto o = py::handle(tup[py::int_(i)]);\n            if (!o) {\n                throw py::value_error(\"tuple is malformed\");\n            }\n        }\n        return tup;\n    });\n    m.def(\"list_rvalue_getter\", [](const py::list &l) {\n        // tests accessing list with rvalue int\n        for (size_t i = 0; i < l.size(); i++) {\n            auto o = py::handle(l[py::int_(i)]);\n            if (!o) {\n                throw py::value_error(\"list is malformed\");\n            }\n        }\n        return l;\n    });\n    m.def(\"populate_dict_rvalue\", [](int population) {\n        auto d = py::dict();\n        for (int i = 0; i < population; i++) {\n            d[py::int_(i)] = py::int_(i);\n        }\n        return d;\n    });\n    m.def(\"populate_obj_str_attrs\", [](py::object &o, int population) {\n        for (int i = 0; i < population; i++) {\n            o.attr(py::str(py::int_(i))) = py::str(py::int_(i));\n        }\n        return o;\n    });\n\n    // testing immutable object augmented assignment: #issue 3812\n    m.def(\"inplace_append\", [](py::object &a, const py::object &b) {\n        a += b;\n        return a;\n    });\n    m.def(\"inplace_subtract\", [](py::object &a, const py::object &b) {\n        a -= b;\n        return a;\n    });\n    m.def(\"inplace_multiply\", [](py::object &a, const py::object &b) {\n        a *= b;\n        return a;\n    });\n    m.def(\"inplace_divide\", [](py::object &a, const py::object &b) {\n        a /= b;\n        return a;\n    });\n    m.def(\"inplace_or\", [](py::object &a, const py::object &b) {\n        a |= b;\n        return a;\n    });\n    m.def(\"inplace_and\", [](py::object &a, const py::object &b) {\n        a &= b;\n        return a;\n    });\n    m.def(\"inplace_lshift\", [](py::object &a, const py::object &b) {\n        a <<= b;\n        return a;\n    });\n    m.def(\"inplace_rshift\", [](py::object &a, const py::object &b) {\n        a >>= b;\n        return a;\n    });\n\n    m.def(\"annotate_tuple_float_str\", [](const py::typing::Tuple<py::float_, py::str> &) {});\n    m.def(\"annotate_tuple_empty\", [](const py::typing::Tuple<> &) {});\n    m.def(\"annotate_tuple_variable_length\",\n          [](const py::typing::Tuple<py::float_, py::ellipsis> &) {});\n    m.def(\"annotate_dict_str_int\", [](const py::typing::Dict<py::str, int> &) {});\n    m.def(\"annotate_list_int\", [](const py::typing::List<int> &) {});\n    m.def(\"annotate_set_str\", [](const py::typing::Set<std::string> &) {});\n    m.def(\"annotate_iterable_str\", [](const py::typing::Iterable<std::string> &) {});\n    m.def(\"annotate_iterator_int\", [](const py::typing::Iterator<int> &) {});\n    m.def(\"annotate_fn\",\n          [](const py::typing::Callable<int(py::typing::List<py::str>, py::str)> &) {});\n\n    m.def(\"annotate_fn_only_return\", [](const py::typing::Callable<int(py::ellipsis)> &) {});\n    m.def(\"annotate_type\", [](const py::typing::Type<int> &t) -> py::type { return t; });\n\n    m.def(\"annotate_union\",\n          [](py::typing::List<py::typing::Union<py::str, py::int_, py::object>> l,\n             py::str a,\n             py::int_ b,\n             py::object c) -> py::typing::List<py::typing::Union<py::str, py::int_, py::object>> {\n              l.append(a);\n              l.append(b);\n              l.append(c);\n              return l;\n          });\n\n    m.def(\"union_typing_only\",\n          [](py::typing::List<py::typing::Union<py::str>> &l)\n              -> py::typing::List<py::typing::Union<py::int_>> { return l; });\n\n    m.def(\"annotate_union_to_object\",\n          [](py::typing::Union<int, py::str> &o) -> py::object { return o; });\n\n    m.def(\"annotate_optional\",\n          [](py::list &list) -> py::typing::List<py::typing::Optional<py::str>> {\n              list.append(py::str(\"hi\"));\n              list.append(py::none());\n              return list;\n          });\n\n    m.def(\"annotate_type_guard\", [](py::object &o) -> py::typing::TypeGuard<py::str> {\n        return py::isinstance<py::str>(o);\n    });\n    m.def(\"annotate_type_is\",\n          [](py::object &o) -> py::typing::TypeIs<py::str> { return py::isinstance<py::str>(o); });\n\n    m.def(\"annotate_no_return\", []() -> py::typing::NoReturn { throw 0; });\n    m.def(\"annotate_never\", []() -> py::typing::Never { throw 0; });\n\n    m.def(\"annotate_optional_to_object\",\n          [](py::typing::Optional<int> &o) -> py::object { return o; });\n\n#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)\n    py::enum_<literals::Color>(m, \"Color\")\n        .value(\"RED\", literals::Color::RED)\n        .value(\"BLUE\", literals::Color::BLUE);\n\n    m.def(\"annotate_literal\", [](literals::LiteralFoo &o) -> py::object { return o; });\n    // Literal with `@`, `%`, `{`, `}`, and `->`\n    m.def(\"identity_literal_exclamation\", [](const py::typing::Literal<\"\\\"!\\\"\"> &x) { return x; });\n    m.def(\"identity_literal_at\", [](const py::typing::Literal<\"\\\"@\\\"\"> &x) { return x; });\n    m.def(\"identity_literal_percent\", [](const py::typing::Literal<\"\\\"%\\\"\"> &x) { return x; });\n    m.def(\"identity_literal_curly_open\", [](const py::typing::Literal<\"\\\"{\\\"\"> &x) { return x; });\n    m.def(\"identity_literal_curly_close\", [](const py::typing::Literal<\"\\\"}\\\"\"> &x) { return x; });\n    m.def(\"identity_literal_arrow_with_io_name\",\n          [](const py::typing::Literal<\"\\\"->\\\"\"> &x, const RealNumber &) { return x; });\n    m.def(\"identity_literal_arrow_with_callable\",\n          [](const py::typing::Callable<RealNumber(const py::typing::Literal<\"\\\"->\\\"\"> &,\n                                                   const RealNumber &)> &x) { return x; });\n    m.def(\"identity_literal_all_special_chars\",\n          [](const py::typing::Literal<\"\\\"!@!!->{%}\\\"\"> &x) { return x; });\n    m.def(\"annotate_generic_containers\",\n          [](const py::typing::List<typevar::TypeVarT> &l) -> py::typing::List<typevar::TypeVarV> {\n              return l;\n          });\n\n    m.def(\"annotate_listT_to_T\",\n          [](const py::typing::List<typevar::TypeVarT> &l) -> typevar::TypeVarT { return l[0]; });\n    m.def(\"annotate_object_to_T\", [](const py::object &o) -> typevar::TypeVarT { return o; });\n    m.attr(\"defined_PYBIND11_TYPING_H_HAS_STRING_LITERAL\") = true;\n#else\n    m.attr(\"defined_PYBIND11_TYPING_H_HAS_STRING_LITERAL\") = false;\n#endif\n\n#if defined(PYBIND11_TEST_PYTYPES_HAS_RANGES)\n\n    // test_tuple_ranges\n    m.def(\"tuple_iterator_default_initialization\", []() {\n        using TupleIterator = decltype(std::declval<py::tuple>().begin());\n        static_assert(std::random_access_iterator<TupleIterator>);\n        return TupleIterator{} == TupleIterator{};\n    });\n\n    m.def(\"transform_tuple_plus_one\", [](py::tuple &tpl) {\n        py::list ret{};\n        for (auto &&it :\n             tpl | std::views::transform([](const auto &o) { return py::cast<int>(o) + 1; })) {\n            ret.append(py::int_(it));\n        }\n        return ret;\n    });\n\n    // test_list_ranges\n    m.def(\"list_iterator_default_initialization\", []() {\n        using ListIterator = decltype(std::declval<py::list>().begin());\n        static_assert(std::random_access_iterator<ListIterator>);\n        return ListIterator{} == ListIterator{};\n    });\n\n    m.def(\"transform_list_plus_one\", [](py::list &lst) {\n        py::list ret{};\n        for (auto &&it :\n             lst | std::views::transform([](const auto &o) { return py::cast<int>(o) + 1; })) {\n            ret.append(py::int_(it));\n        }\n        return ret;\n    });\n\n    // test_dict_ranges\n    m.def(\"dict_iterator_default_initialization\", []() {\n        using DictIterator = decltype(std::declval<py::dict>().begin());\n        static_assert(std::forward_iterator<DictIterator>);\n        return DictIterator{} == DictIterator{};\n    });\n\n    m.def(\"transform_dict_plus_one\", [](py::dict &dct) {\n        py::list ret{};\n        for (auto it : dct | std::views::transform([](auto &o) {\n                           return std::pair{py::cast<int>(o.first) + 1,\n                                            py::cast<int>(o.second) + 1};\n                       })) {\n            ret.append(py::make_tuple(py::int_(it.first), py::int_(it.second)));\n        }\n        return ret;\n    });\n\n    m.attr(\"defined_PYBIND11_TEST_PYTYPES_HAS_RANGES\") = true;\n#else\n    m.attr(\"defined_PYBIND11_TEST_PYTYPES_HAS_RANGES\") = false;\n#endif\n\n#if defined(__cpp_inline_variables)\n    // Exercises const char* overload:\n    m.attr_with_type_hint<py::typing::List<int>>(\"list_int\") = py::list();\n    // Exercises py::handle overload:\n    m.attr_with_type_hint<py::typing::Set<py::str>>(py::str(\"set_str\")) = py::set();\n\n    struct foo_t {};\n    struct foo2 {};\n    struct foo3 {};\n\n    pybind11::class_<foo_t>(m, \"foo\");\n    pybind11::class_<foo2>(m, \"foo2\");\n    pybind11::class_<foo3>(m, \"foo3\");\n    m.attr_with_type_hint<foo_t>(\"foo\") = foo_t{};\n\n    m.attr_with_type_hint<py::typing::Union<foo_t, foo2, foo3>>(\"foo_union\") = foo_t{};\n\n    // Include to ensure this does not crash\n    struct foo4 {};\n    m.attr_with_type_hint<foo4>(\"foo4\") = 3;\n\n    struct Empty {};\n    py::class_<Empty>(m, \"EmptyAnnotationClass\");\n\n    struct Static {};\n    auto static_class = py::class_<Static>(m, \"Static\");\n    static_class.def(py::init());\n    static_class.attr_with_type_hint<py::typing::ClassVar<float>>(\"x\") = 1.0;\n    static_class.attr_with_type_hint<py::typing::ClassVar<py::typing::Dict<py::str, int>>>(\n        \"dict_str_int\")\n        = py::dict();\n\n    struct Instance {};\n    auto instance = py::class_<Instance>(m, \"Instance\", py::dynamic_attr());\n    instance.def(py::init());\n    instance.attr_with_type_hint<float>(\"y\");\n\n    m.def(\"attr_with_type_hint_float_x\",\n          [](py::handle obj) { obj.attr_with_type_hint<float>(\"x\"); });\n\n    m.attr_with_type_hint<py::typing::Final<int>>(\"CONST_INT\") = 3;\n\n    m.attr(\"defined___cpp_inline_variables\") = true;\n#else\n    m.attr(\"defined___cpp_inline_variables\") = false;\n#endif\n    m.def(\"half_of_number\", [](const RealNumber &x) { return RealNumber{x.value / 2}; });\n    m.def(\n        \"half_of_number_convert\",\n        [](const RealNumber &x) { return RealNumber{x.value / 2}; },\n        py::arg(\"x\"));\n    m.def(\n        \"half_of_number_noconvert\",\n        [](const RealNumber &x) { return RealNumber{x.value / 2}; },\n        py::arg(\"x\").noconvert());\n    // std::vector<T>\n    m.def(\"half_of_number_vector\", [](const std::vector<RealNumber> &x) {\n        std::vector<RealNumber> result;\n        result.reserve(x.size());\n        for (auto num : x) {\n            result.push_back(RealNumber{num.value / 2});\n        }\n        return result;\n    });\n    // Tuple<T, T>\n    m.def(\"half_of_number_tuple\", [](const py::typing::Tuple<RealNumber, RealNumber> &x) {\n        py::typing::Tuple<RealNumber, RealNumber> result\n            = py::make_tuple(RealNumber{x[0].cast<RealNumber>().value / 2},\n                             RealNumber{x[1].cast<RealNumber>().value / 2});\n        return result;\n    });\n    // Tuple<T, ...>\n    m.def(\"half_of_number_tuple_ellipsis\",\n          [](const py::typing::Tuple<RealNumber, py::ellipsis> &x) {\n              py::typing::Tuple<RealNumber, py::ellipsis> result(x.size());\n              for (size_t i = 0; i < x.size(); ++i) {\n                  result[i] = x[i].cast<RealNumber>().value / 2;\n              }\n              return result;\n          });\n    // Dict<K, V>\n    m.def(\"half_of_number_dict\", [](const py::typing::Dict<std::string, RealNumber> &x) {\n        py::typing::Dict<std::string, RealNumber> result;\n        for (auto it : x) {\n            result[it.first] = RealNumber{it.second.cast<RealNumber>().value / 2};\n        }\n        return result;\n    });\n    // List<T>\n    m.def(\"half_of_number_list\", [](const py::typing::List<RealNumber> &x) {\n        py::typing::List<RealNumber> result;\n        for (auto num : x) {\n            result.append(RealNumber{num.cast<RealNumber>().value / 2});\n        }\n        return result;\n    });\n    // List<List<T>>\n    m.def(\"half_of_number_nested_list\",\n          [](const py::typing::List<py::typing::List<RealNumber>> &x) {\n              py::typing::List<py::typing::List<RealNumber>> result_lists;\n              for (auto nums : x) {\n                  py::typing::List<RealNumber> result;\n                  for (auto num : nums) {\n                      result.append(RealNumber{num.cast<RealNumber>().value / 2});\n                  }\n                  result_lists.append(result);\n              }\n              return result_lists;\n          });\n    // Set<T>\n    m.def(\"identity_set\", [](const py::typing::Set<RealNumber> &x) { return x; });\n    // Iterable<T>\n    m.def(\"identity_iterable\", [](const py::typing::Iterable<RealNumber> &x) { return x; });\n    // Iterator<T>\n    m.def(\"identity_iterator\", [](const py::typing::Iterator<RealNumber> &x) { return x; });\n    // Callable<R(A)> identity\n    m.def(\"identity_callable\",\n          [](const py::typing::Callable<RealNumber(const RealNumber &)> &x) { return x; });\n    // Callable<R(...)> identity\n    m.def(\"identity_callable_ellipsis\",\n          [](const py::typing::Callable<RealNumber(py::ellipsis)> &x) { return x; });\n    // Nested Callable<R(A)> identity\n    m.def(\"identity_nested_callable\",\n          [](const py::typing::Callable<py::typing::Callable<RealNumber(const RealNumber &)>(\n                 py::typing::Callable<RealNumber(const RealNumber &)>)> &x) { return x; });\n    // Callable<R(A)>\n    m.def(\"apply_callable\",\n          [](const RealNumber &x, const py::typing::Callable<RealNumber(const RealNumber &)> &f) {\n              return f(x).cast<RealNumber>();\n          });\n    // Callable<R(...)>\n    m.def(\"apply_callable_ellipsis\",\n          [](const RealNumber &x, const py::typing::Callable<RealNumber(py::ellipsis)> &f) {\n              return f(x).cast<RealNumber>();\n          });\n    // Union<T1, T2>\n    m.def(\"identity_union\", [](const py::typing::Union<RealNumber, std::string> &x) { return x; });\n    // Optional<T>\n    m.def(\"identity_optional\", [](const py::typing::Optional<RealNumber> &x) { return x; });\n    // TypeGuard<T>\n    m.def(\"check_type_guard\",\n          [](const py::typing::List<py::object> &x)\n              -> py::typing::TypeGuard<py::typing::List<RealNumber>> {\n              for (const auto &item : x) {\n                  if (!py::isinstance<RealNumber>(item)) {\n                      return false;\n                  }\n              }\n              return true;\n          });\n    // TypeIs<T>\n    m.def(\"check_type_is\", [](const py::object &x) -> py::typing::TypeIs<RealNumber> {\n        return py::isinstance<RealNumber>(x);\n    });\n\n    m.def(\"const_kwargs_ref_to_str\", [](const py::kwargs &kwargs) { return py::str(kwargs); });\n}\n"
  },
  {
    "path": "tests/test_pytypes.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport sys\nimport types\n\nimport pytest\n\nimport env\nfrom pybind11_tests import detailed_error_messages_enabled\nfrom pybind11_tests import pytypes as m\n\n\ndef test_obj_class_name():\n    assert m.obj_class_name(None) == \"NoneType\"\n    assert m.obj_class_name(list) == \"list\"\n    assert m.obj_class_name([]) == \"list\"\n\n\ndef test_handle_from_move_only_type_with_operator_PyObject():\n    assert m.handle_from_move_only_type_with_operator_PyObject_ncnst()\n    assert m.handle_from_move_only_type_with_operator_PyObject_const()\n\n\ndef test_bool(doc):\n    assert doc(m.get_bool) == \"get_bool() -> bool\"\n\n\ndef test_int(doc):\n    assert doc(m.get_int) == \"get_int() -> int\"\n\n\ndef test_iterator(doc):\n    assert doc(m.get_iterator) == \"get_iterator() -> collections.abc.Iterator\"\n\n\n@pytest.mark.parametrize(\n    (\"pytype\", \"from_iter_func\"),\n    [\n        (frozenset, m.get_frozenset_from_iterable),\n        (list, m.get_list_from_iterable),\n        (set, m.get_set_from_iterable),\n        (tuple, m.get_tuple_from_iterable),\n    ],\n)\ndef test_from_iterable(pytype, from_iter_func):\n    my_iter = iter(range(10))\n    s = from_iter_func(my_iter)\n    assert type(s) == pytype\n    assert s == pytype(range(10))\n\n\ndef test_iterable(doc):\n    assert doc(m.get_iterable) == \"get_iterable() -> collections.abc.Iterable\"\n    lst = [1, 2, 3]\n    i = m.get_first_item_from_iterable(lst)\n    assert i == 1\n    i = m.get_second_item_from_iterable(lst)\n    assert i == 2\n\n\ndef test_float(doc):\n    assert doc(m.get_float) == \"get_float() -> float\"\n    assert doc(m.float_roundtrip) == \"float_roundtrip(arg0: float) -> float\"\n    f1 = m.float_roundtrip(5.5)\n    assert isinstance(f1, float)\n    assert f1 == 5.5\n    f2 = m.float_roundtrip(5)\n    assert isinstance(f2, float)\n    assert f2 == 5.0\n\n\ndef test_list(capture, doc):\n    assert m.list_no_args() == []\n    assert m.list_ssize_t() == []\n    assert m.list_size_t() == []\n    lst = [1, 2]\n    m.list_insert_ssize_t(lst)\n    assert lst == [1, 83, 2]\n    m.list_insert_size_t(lst)\n    assert lst == [1, 83, 2, 57]\n    m.list_clear(lst)\n    assert lst == []\n\n    with capture:\n        lst = m.get_list()\n        assert lst == [\"inserted-0\", \"overwritten\", \"inserted-2\"]\n\n        lst.append(\"value2\")\n        m.print_list(lst)\n    assert (\n        capture.unordered\n        == \"\"\"\n        Entry at position 0: value\n        list item 0: inserted-0\n        list item 1: overwritten\n        list item 2: inserted-2\n        list item 3: value2\n    \"\"\"\n    )\n\n    assert doc(m.get_list) == \"get_list() -> list\"\n    assert doc(m.print_list) == \"print_list(arg0: list) -> None\"\n\n\ndef test_none(doc):\n    assert doc(m.get_none) == \"get_none() -> None\"\n    assert doc(m.print_none) == \"print_none(arg0: None) -> None\"\n\n\ndef test_set(capture, doc):\n    s = m.get_set()\n    assert isinstance(s, set)\n    assert s == {\"key1\", \"key2\", \"key3\"}\n\n    s.add(\"key4\")\n    with capture:\n        m.print_anyset(s)\n    assert (\n        capture.unordered\n        == \"\"\"\n        key: key1\n        key: key2\n        key: key3\n        key: key4\n    \"\"\"\n    )\n\n    m.set_add(s, \"key5\")\n    assert m.anyset_size(s) == 5\n\n    m.set_clear(s)\n    assert m.anyset_empty(s)\n\n    assert not m.anyset_contains(set(), 42)\n    assert m.anyset_contains({42}, 42)\n    assert m.anyset_contains({\"foo\"}, \"foo\")\n\n    assert doc(m.get_set) == \"get_set() -> set\"\n    assert doc(m.print_anyset) == \"print_anyset(arg0: set | frozenset) -> None\"\n\n\ndef test_frozenset(capture, doc):\n    s = m.get_frozenset()\n    assert isinstance(s, frozenset)\n    assert s == frozenset({\"key1\", \"key2\", \"key3\"})\n\n    with capture:\n        m.print_anyset(s)\n    assert (\n        capture.unordered\n        == \"\"\"\n        key: key1\n        key: key2\n        key: key3\n    \"\"\"\n    )\n    assert m.anyset_size(s) == 3\n    assert not m.anyset_empty(s)\n\n    assert not m.anyset_contains(frozenset(), 42)\n    assert m.anyset_contains(frozenset({42}), 42)\n    assert m.anyset_contains(frozenset({\"foo\"}), \"foo\")\n\n    assert doc(m.get_frozenset) == \"get_frozenset() -> frozenset\"\n\n\ndef test_dict(capture, doc):\n    d = m.get_dict()\n    assert d == {\"key\": \"value\"}\n\n    with capture:\n        d[\"key2\"] = \"value2\"\n        m.print_dict(d)\n    assert (\n        capture.unordered\n        == \"\"\"\n        key: key, value=value\n        key: key2, value=value2\n    \"\"\"\n    )\n\n    assert not m.dict_contains({}, 42)\n    assert m.dict_contains({42: None}, 42)\n    assert m.dict_contains({\"foo\": None}, \"foo\")\n\n    assert doc(m.get_dict) == \"get_dict() -> dict\"\n    assert doc(m.print_dict) == \"print_dict(arg0: dict) -> None\"\n\n    assert m.dict_keyword_constructor() == {\"x\": 1, \"y\": 2, \"z\": 3}\n\n\nclass CustomContains:\n    d = {\"key\": None}\n\n    def __contains__(self, m):\n        return m in self.d\n\n\n@pytest.mark.parametrize(\n    (\"arg\", \"func\"),\n    [\n        (set(), m.anyset_contains),\n        ({}, m.dict_contains),\n        (CustomContains(), m.obj_contains),\n    ],\n)\ndef test_unhashable_exceptions(arg, func):\n    class Unhashable:\n        __hash__ = None\n\n    with pytest.raises(TypeError) as exc_info:\n        func(arg, Unhashable())\n    assert \"unhashable type:\" in str(exc_info.value)\n\n\ndef test_tuple():\n    assert m.tuple_no_args() == ()\n    assert m.tuple_ssize_t() == ()\n    assert m.tuple_size_t() == ()\n    assert m.get_tuple() == (42, None, \"spam\")\n\n\ndef test_simple_namespace():\n    ns = m.get_simple_namespace()\n    assert ns.attr == 42\n    assert ns.x == \"foo\"\n    assert ns.right == 2\n    assert not hasattr(ns, \"wrong\")\n\n\ndef test_str(doc):\n    assert m.str_from_char_ssize_t().encode().decode() == \"red\"\n    assert m.str_from_char_size_t().encode().decode() == \"blue\"\n    assert m.str_from_string().encode().decode() == \"baz\"\n    assert m.str_from_bytes().encode().decode() == \"boo\"\n\n    assert doc(m.str_from_bytes) == \"str_from_bytes() -> str\"\n\n    class A:\n        def __str__(self):\n            return \"this is a str\"\n\n        def __repr__(self):\n            return \"this is a repr\"\n\n    assert m.str_from_object(A()) == \"this is a str\"\n    assert m.repr_from_object(A()) == \"this is a repr\"\n    assert m.str_from_handle(A()) == \"this is a str\"\n\n    s1, s2 = m.str_format()\n    assert s1 == \"1 + 2 = 3\"\n    assert s1 == s2\n\n    malformed_utf8 = b\"\\x80\"\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert m.str_from_object(malformed_utf8) is malformed_utf8\n    else:\n        assert m.str_from_object(malformed_utf8) == \"b'\\\\x80'\"\n    assert m.str_from_handle(malformed_utf8) == \"b'\\\\x80'\"\n\n    assert m.str_from_string_from_str(\"this is a str\") == \"this is a str\"\n    ucs_surrogates_str = \"\\udcc3\"\n    with pytest.raises(UnicodeEncodeError):\n        m.str_from_string_from_str(ucs_surrogates_str)\n\n\n@pytest.mark.parametrize(\n    \"func\",\n    [\n        m.str_from_bytes_input,\n        m.str_from_cstr_input,\n        m.str_from_std_string_input,\n    ],\n)\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should be fixed on GraalPy side\")\ndef test_surrogate_pairs_unicode_error(func):\n    input_str = \"\\ud83d\\ude4f\".encode(\"utf-8\", \"surrogatepass\")\n    with pytest.raises(UnicodeDecodeError):\n        func(input_str)\n\n\ndef test_bytes(doc):\n    assert m.bytes_from_char_ssize_t().decode() == \"green\"\n    assert m.bytes_from_char_size_t().decode() == \"purple\"\n    assert m.bytes_from_string().decode() == \"foo\"\n    assert m.bytes_from_str().decode() == \"bar\"\n\n    assert doc(m.bytes_from_str) == \"bytes_from_str() -> bytes\"\n\n\ndef test_bytearray():\n    assert m.bytearray_from_char_ssize_t().decode() == \"$%\"\n    assert m.bytearray_from_char_size_t().decode() == \"@$!\"\n    assert m.bytearray_from_string().decode() == \"foo\"\n    assert m.bytearray_size() == len(\"foo\")\n\n\ndef test_capsule(capture):\n    pytest.gc_collect()\n    with capture:\n        a = m.return_capsule_with_destructor()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule\n        destructing capsule\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_renamed_capsule_with_destructor()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule\n        renaming capsule\n        destructing capsule\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_capsule_with_destructor_2()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule\n        destructing capsule: 1234\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_capsule_with_destructor_3()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule\n        destructing capsule: 1233\n        original name: oname\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_renamed_capsule_with_destructor_2()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule\n        renaming capsule\n        destructing capsule: 1234\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_capsule_with_name_and_destructor()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        created capsule (1234, 'pointer type description')\n        destructing capsule (1234, 'pointer type description')\n    \"\"\"\n    )\n\n    with capture:\n        a = m.return_capsule_with_explicit_nullptr_dtor()\n        del a\n        pytest.gc_collect()\n    assert (\n        capture.unordered\n        == \"\"\"\n        creating capsule with explicit nullptr dtor\n    \"\"\"\n    )\n\n\ndef test_accessors():\n    class SubTestObject:\n        attr_obj = 1\n        attr_char = 2\n\n    class TestObject:\n        basic_attr = 1\n        begin_end = [1, 2, 3]\n        d = {\"operator[object]\": 1, \"operator[char *]\": 2}\n        sub = SubTestObject()\n\n        def func(self, x, *args):\n            return self.basic_attr + x + sum(args)\n\n    d = m.accessor_api(TestObject())\n    assert d[\"basic_attr\"] == 1\n    assert d[\"begin_end\"] == [1, 2, 3]\n    assert d[\"operator[object]\"] == 1\n    assert d[\"operator[char *]\"] == 2\n    assert d[\"attr(object)\"] == 1\n    assert d[\"attr(char *)\"] == 2\n    assert d[\"missing_attr_ptr\"] == \"raised\"\n    assert d[\"missing_attr_chain\"] == \"raised\"\n    assert d[\"is_none\"] is False\n    assert d[\"operator()\"] == 2\n    assert d[\"operator*\"] == 7\n    assert d[\"implicit_list\"] == [1, 2, 3]\n    assert all(x in TestObject.__dict__ for x in d[\"implicit_dict\"])\n\n    assert m.tuple_accessor(()) == (0, 1, 2)\n\n    d = m.accessor_assignment()\n    assert d[\"get\"] == 0\n    assert d[\"deferred_get\"] == 0\n    assert d[\"set\"] == 1\n    assert d[\"deferred_set\"] == 1\n    assert d[\"var\"] == 99\n\n\ndef test_accessor_moves():\n    inc_refs = m.accessor_moves()\n    if inc_refs:\n        assert inc_refs == [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n    else:\n        pytest.skip(\"Not defined: PYBIND11_HANDLE_REF_DEBUG\")\n\n\n@pytest.mark.xfail(\"env.GRAALPY\", reason=\"TODO should be fixed on GraalPy side\")\ndef test_constructors():\n    \"\"\"C++ default and converting constructors are equivalent to type calls in Python\"\"\"\n    types = [bytes, bytearray, str, bool, int, float, tuple, list, dict, set]\n    expected = {t.__name__: t() for t in types}\n    assert m.default_constructors() == expected\n\n    data = {\n        bytes: b\"41\",  # Currently no supported or working conversions.\n        bytearray: bytearray(b\"41\"),\n        str: 42,\n        bool: \"Not empty\",\n        int: \"42\",\n        float: \"+1e3\",\n        tuple: range(3),\n        list: range(3),\n        dict: [(\"two\", 2), (\"one\", 1), (\"three\", 3)],\n        set: [4, 4, 5, 6, 6, 6],\n        frozenset: [4, 4, 5, 6, 6, 6],\n        memoryview: b\"abc\",\n    }\n    inputs = {k.__name__: v for k, v in data.items()}\n    expected = {k.__name__: k(v) for k, v in data.items()}\n\n    assert m.converting_constructors(inputs) == expected\n    assert m.cast_functions(inputs) == expected\n\n    # Converting constructors and cast functions should just reference rather\n    # than copy when no conversion is needed:\n    noconv1 = m.converting_constructors(expected)\n    for k in noconv1:\n        assert noconv1[k] is expected[k]\n\n    noconv2 = m.cast_functions(expected)\n    for k in noconv2:\n        assert noconv2[k] is expected[k]\n\n\ndef test_non_converting_constructors():\n    non_converting_test_cases = [\n        (\"bytes\", range(10)),\n        (\"none\", 42),\n        (\"ellipsis\", 42),\n        (\"type\", 42),\n    ]\n    for t, v in non_converting_test_cases:\n        for move in [True, False]:\n            with pytest.raises(TypeError) as excinfo:\n                m.nonconverting_constructor(t, v, move)\n            expected_error = (\n                f\"Object of type '{type(v).__name__}' is not an instance of '{t}'\"\n            )\n            assert str(excinfo.value) == expected_error\n\n\ndef test_pybind11_str_raw_str():\n    # specifically to exercise pybind11::str::raw_str\n    cvt = m.convert_to_pybind11_str\n    assert cvt(\"Str\") == \"Str\"\n    assert cvt(b\"Bytes\") == \"b'Bytes'\"\n    assert cvt(None) == \"None\"\n    assert cvt(False) == \"False\"\n    assert cvt(True) == \"True\"\n    assert cvt(42) == \"42\"\n    assert cvt(2**65) == \"36893488147419103232\"\n    assert cvt(-1.50) == \"-1.5\"\n    assert cvt(()) == \"()\"\n    assert cvt((18,)) == \"(18,)\"\n    assert cvt([]) == \"[]\"\n    assert cvt([28]) == \"[28]\"\n    assert cvt({}) == \"{}\"\n    assert cvt({3: 4}) == \"{3: 4}\"\n    assert cvt(set()) == \"set()\"\n    assert cvt({3}) == \"{3}\"\n\n    valid_orig = \"Ǳ\"\n    valid_utf8 = valid_orig.encode(\"utf-8\")\n    valid_cvt = cvt(valid_utf8)\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert valid_cvt is valid_utf8\n    else:\n        assert type(valid_cvt) is str\n        assert valid_cvt == \"b'\\\\xc7\\\\xb1'\"\n\n    malformed_utf8 = b\"\\x80\"\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert cvt(malformed_utf8) is malformed_utf8\n    else:\n        malformed_cvt = cvt(malformed_utf8)\n        assert type(malformed_cvt) is str\n        assert malformed_cvt == \"b'\\\\x80'\"\n\n\ndef test_implicit_casting():\n    \"\"\"Tests implicit casting when assigning or appending to dicts and lists.\"\"\"\n    z = m.get_implicit_casting()\n    assert z[\"d\"] == {\n        \"char*_i1\": \"abc\",\n        \"char*_i2\": \"abc\",\n        \"char*_e\": \"abc\",\n        \"char*_p\": \"abc\",\n        \"str_i1\": \"str\",\n        \"str_i2\": \"str1\",\n        \"str_e\": \"str2\",\n        \"str_p\": \"str3\",\n        \"int_i1\": 42,\n        \"int_i2\": 42,\n        \"int_e\": 43,\n        \"int_p\": 44,\n    }\n    assert z[\"l\"] == [3, 6, 9, 12, 15]\n\n\ndef test_print(capture):\n    with capture:\n        m.print_function()\n    assert (\n        capture\n        == \"\"\"\n        Hello, World!\n        1 2.0 three True -- multiple args\n        *args-and-a-custom-separator\n        no new line here -- next print\n        flush\n        py::print + str.format = this\n    \"\"\"\n    )\n    assert capture.stderr == \"this goes to stderr\"\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.print_failure()\n    assert str(excinfo.value) == \"Unable to convert call argument \" + (\n        \"'1' of type 'UnregisteredType' to Python object\"\n        if detailed_error_messages_enabled\n        else \"'1' to Python object (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)\"\n    )\n\n\ndef test_hash():\n    class Hashable:\n        def __init__(self, value):\n            self.value = value\n\n        def __hash__(self):\n            return self.value\n\n    class Unhashable:\n        __hash__ = None\n\n    assert m.hash_function(Hashable(42)) == 42\n    with pytest.raises(TypeError):\n        m.hash_function(Unhashable())\n\n\ndef test_number_protocol():\n    for a, b in [(1, 1), (3, 5)]:\n        li = [\n            a == b,\n            a != b,\n            a < b,\n            a <= b,\n            a > b,\n            a >= b,\n            a + b,\n            a - b,\n            a * b,\n            a / b,\n            a | b,\n            a & b,\n            a ^ b,\n            a >> b,\n            a << b,\n        ]\n        assert m.test_number_protocol(a, b) == li\n\n\ndef test_list_slicing():\n    li = list(range(100))\n    assert li[0:-1:2] == m.test_list_slicing(li)\n    assert li[::] == m.test_list_slicing_default(li)\n\n\ndef test_issue2361():\n    # See issue #2361\n    assert m.issue2361_str_implicit_copy_none() == \"None\"\n    with pytest.raises(TypeError) as excinfo:\n        assert m.issue2361_dict_implicit_copy_none()\n    assert \"NoneType\" in str(excinfo.value)\n    assert \"iterable\" in str(excinfo.value)\n\n\n@pytest.mark.parametrize(\n    (\"method\", \"args\", \"fmt\", \"expected_view\"),\n    [\n        (m.test_memoryview_object, (b\"red\",), \"B\", b\"red\"),\n        (m.test_memoryview_buffer_info, (b\"green\",), \"B\", b\"green\"),\n        (m.test_memoryview_from_buffer, (False,), \"h\", [3, 1, 4, 1, 5]),\n        (m.test_memoryview_from_buffer, (True,), \"H\", [2, 7, 1, 8]),\n        (m.test_memoryview_from_buffer_nativeformat, (), \"@i\", [4, 7, 5]),\n    ],\n)\ndef test_memoryview(method, args, fmt, expected_view):\n    view = method(*args)\n    assert isinstance(view, memoryview)\n    assert view.format == fmt\n    assert list(view) == list(expected_view)\n\n\n@pytest.mark.xfail(\"env.PYPY\", reason=\"getrefcount is not available\")\n@pytest.mark.parametrize(\n    \"method\",\n    [\n        m.test_memoryview_object,\n        m.test_memoryview_buffer_info,\n    ],\n)\ndef test_memoryview_refcount(method):\n    # Avoiding a literal to avoid an immortal object in free-threaded builds\n    buf = \"\\x0a\\x0b\\x0c\\x0d\".encode(\"ascii\")\n    ref_before = sys.getrefcount(buf)\n    view = method(buf)\n    ref_after = sys.getrefcount(buf)\n    assert ref_before < ref_after\n    assert list(view) == list(buf)\n\n\ndef test_memoryview_from_buffer_empty_shape():\n    view = m.test_memoryview_from_buffer_empty_shape()\n    assert isinstance(view, memoryview)\n    assert view.format == \"B\"\n    assert bytes(view) == b\"\"\n\n\ndef test_test_memoryview_from_buffer_invalid_strides():\n    with pytest.raises(RuntimeError):\n        m.test_memoryview_from_buffer_invalid_strides()\n\n\ndef test_test_memoryview_from_buffer_nullptr():\n    with pytest.raises(ValueError):\n        m.test_memoryview_from_buffer_nullptr()\n\n\ndef test_memoryview_from_memory():\n    view = m.test_memoryview_from_memory()\n    assert isinstance(view, memoryview)\n    assert view.format == \"B\"\n    assert bytes(view) == b\"\\xff\\xe1\\xab\\x37\"\n\n\ndef test_builtin_functions():\n    assert m.get_len(list(range(42))) == 42\n    with pytest.raises(TypeError) as exc_info:\n        m.get_len(i for i in range(42))\n    assert str(exc_info.value) in [\n        \"object of type 'generator' has no len()\",\n        \"'generator' has no length\",\n    ]  # PyPy\n\n\ndef test_isinstance_string_types():\n    assert m.isinstance_pybind11_bytes(b\"\")\n    assert not m.isinstance_pybind11_bytes(\"\")\n\n    assert m.isinstance_pybind11_str(\"\")\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert m.isinstance_pybind11_str(b\"\")\n    else:\n        assert not m.isinstance_pybind11_str(b\"\")\n\n\ndef test_pass_bytes_or_unicode_to_string_types():\n    assert m.pass_to_pybind11_bytes(b\"Bytes\") == 5\n    with pytest.raises(TypeError):\n        m.pass_to_pybind11_bytes(\"Str\")\n\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert m.pass_to_pybind11_str(b\"Bytes\") == 5\n    else:\n        with pytest.raises(TypeError):\n            m.pass_to_pybind11_str(b\"Bytes\")\n    assert m.pass_to_pybind11_str(\"Str\") == 3\n\n    assert m.pass_to_std_string(b\"Bytes\") == 5\n    assert m.pass_to_std_string(\"Str\") == 3\n\n    malformed_utf8 = b\"\\x80\"\n    if hasattr(m, \"PYBIND11_STR_LEGACY_PERMISSIVE\"):\n        assert m.pass_to_pybind11_str(malformed_utf8) == 1\n    else:\n        with pytest.raises(TypeError):\n            m.pass_to_pybind11_str(malformed_utf8)\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\n@pytest.mark.parametrize(\n    (\"create_weakref\", \"create_weakref_with_callback\"),\n    [\n        (m.weakref_from_handle, m.weakref_from_handle_and_function),\n        (m.weakref_from_object, m.weakref_from_object_and_function),\n    ],\n)\ndef test_weakref(create_weakref, create_weakref_with_callback):\n    from weakref import getweakrefcount\n\n    # Apparently, you cannot weakly reference an object()\n    class WeaklyReferenced:\n        pass\n\n    callback_called = False\n\n    def callback(_):\n        nonlocal callback_called\n        callback_called = True\n\n    obj = WeaklyReferenced()\n    assert getweakrefcount(obj) == 0\n    wr = create_weakref(obj)\n    assert getweakrefcount(obj) == 1\n\n    obj = WeaklyReferenced()\n    assert getweakrefcount(obj) == 0\n    wr = create_weakref_with_callback(obj, callback)  # noqa: F841\n    assert getweakrefcount(obj) == 1\n    assert not callback_called\n    del obj\n    pytest.gc_collect()\n    assert callback_called\n\n\n@pytest.mark.parametrize(\n    (\"create_weakref\", \"has_callback\"),\n    [\n        (m.weakref_from_handle, False),\n        (m.weakref_from_object, False),\n        (m.weakref_from_handle_and_function, True),\n        (m.weakref_from_object_and_function, True),\n    ],\n)\ndef test_weakref_err(create_weakref, has_callback):\n    class C:\n        __slots__ = []\n\n    def callback(_):\n        pass\n\n    ob = C()\n    # Should raise TypeError on CPython\n    cm = pytest.raises(TypeError)\n    if env.PYPY or env.GRAALPY:\n        cm = contextlib.nullcontext()\n    with cm:\n        _ = create_weakref(ob, callback) if has_callback else create_weakref(ob)\n\n\ndef test_cpp_iterators():\n    assert m.tuple_iterator() == 12\n    assert m.dict_iterator() == 305 + 711\n    assert m.passed_iterator(iter((-7, 3))) == -4\n\n\ndef test_implementation_details():\n    lst = [39, 43, 92, 49, 22, 29, 93, 98, 26, 57, 8]\n    tup = tuple(lst)\n    assert m.sequence_item_get_ssize_t(lst) == 43\n    assert m.sequence_item_set_ssize_t(lst) is None\n    assert lst[1] == \"peppa\"\n    assert m.sequence_item_get_size_t(lst) == 92\n    assert m.sequence_item_set_size_t(lst) is None\n    assert lst[2] == \"george\"\n    assert m.list_item_get_ssize_t(lst) == 49\n    assert m.list_item_set_ssize_t(lst) is None\n    assert lst[3] == \"rebecca\"\n    assert m.list_item_get_size_t(lst) == 22\n    assert m.list_item_set_size_t(lst) is None\n    assert lst[4] == \"richard\"\n    assert m.tuple_item_get_ssize_t(tup) == 29\n    assert m.tuple_item_set_ssize_t() == (\"emely\", \"edmond\")\n    assert m.tuple_item_get_size_t(tup) == 93\n    assert m.tuple_item_set_size_t() == (\"candy\", \"cat\")\n\n\ndef test_external_float_():\n    r1 = m.square_float_(2.0)\n    assert r1 == 4.0\n\n\ndef test_tuple_rvalue_getter():\n    pop = 1000\n    tup = tuple(range(pop))\n    m.tuple_rvalue_getter(tup)\n\n\ndef test_list_rvalue_getter():\n    pop = 1000\n    my_list = list(range(pop))\n    m.list_rvalue_getter(my_list)\n\n\ndef test_populate_dict_rvalue():\n    pop = 1000\n    my_dict = {i: i for i in range(pop)}\n    assert m.populate_dict_rvalue(pop) == my_dict\n\n\ndef test_populate_obj_str_attrs():\n    pop = 1000\n    o = types.SimpleNamespace(**{str(i): i for i in range(pop)})\n    new_o = m.populate_obj_str_attrs(o, pop)\n    new_attrs = {k: v for k, v in new_o.__dict__.items() if not k.startswith(\"_\")}\n    assert all(isinstance(v, str) for v in new_attrs.values())\n    assert len(new_attrs) == pop\n\n\n@pytest.mark.parametrize(\n    (\"a\", \"b\"),\n    [(\"foo\", \"bar\"), (1, 2), (1.0, 2.0), (list(range(3)), list(range(3, 6)))],\n)\ndef test_inplace_append(a, b):\n    expected = a + b\n    assert m.inplace_append(a, b) == expected\n\n\n@pytest.mark.parametrize(\n    (\"a\", \"b\"), [(3, 2), (3.0, 2.0), (set(range(3)), set(range(2)))]\n)\ndef test_inplace_subtract(a, b):\n    expected = a - b\n    assert m.inplace_subtract(a, b) == expected\n\n\n@pytest.mark.parametrize((\"a\", \"b\"), [(3, 2), (3.0, 2.0), ([1], 3)])\ndef test_inplace_multiply(a, b):\n    expected = a * b\n    assert m.inplace_multiply(a, b) == expected\n\n\n@pytest.mark.parametrize((\"a\", \"b\"), [(6, 3), (6.0, 3.0)])\ndef test_inplace_divide(a, b):\n    expected = a / b\n    assert m.inplace_divide(a, b) == expected\n\n\n@pytest.mark.parametrize(\n    (\"a\", \"b\"),\n    [\n        (False, True),\n        (\n            set(),\n            {\n                1,\n            },\n        ),\n    ],\n)\ndef test_inplace_or(a, b):\n    expected = a | b\n    assert m.inplace_or(a, b) == expected\n\n\n@pytest.mark.parametrize(\n    (\"a\", \"b\"),\n    [\n        (True, False),\n        (\n            {1, 2, 3},\n            {\n                1,\n            },\n        ),\n    ],\n)\ndef test_inplace_and(a, b):\n    expected = a & b\n    assert m.inplace_and(a, b) == expected\n\n\n@pytest.mark.parametrize((\"a\", \"b\"), [(8, 1), (-3, 2)])\ndef test_inplace_lshift(a, b):\n    expected = a << b\n    assert m.inplace_lshift(a, b) == expected\n\n\n@pytest.mark.parametrize((\"a\", \"b\"), [(8, 1), (-2, 2)])\ndef test_inplace_rshift(a, b):\n    expected = a >> b\n    assert m.inplace_rshift(a, b) == expected\n\n\ndef test_tuple_nonempty_annotations(doc):\n    assert (\n        doc(m.annotate_tuple_float_str)\n        == \"annotate_tuple_float_str(arg0: tuple[float, str]) -> None\"\n    )\n\n\ndef test_tuple_empty_annotations(doc):\n    assert (\n        doc(m.annotate_tuple_empty) == \"annotate_tuple_empty(arg0: tuple[()]) -> None\"\n    )\n\n\ndef test_tuple_variable_length_annotations(doc):\n    assert (\n        doc(m.annotate_tuple_variable_length)\n        == \"annotate_tuple_variable_length(arg0: tuple[float, ...]) -> None\"\n    )\n\n\ndef test_dict_annotations(doc):\n    assert (\n        doc(m.annotate_dict_str_int)\n        == \"annotate_dict_str_int(arg0: dict[str, typing.SupportsInt | typing.SupportsIndex]) -> None\"\n    )\n\n\ndef test_list_annotations(doc):\n    assert (\n        doc(m.annotate_list_int)\n        == \"annotate_list_int(arg0: list[typing.SupportsInt | typing.SupportsIndex]) -> None\"\n    )\n\n\ndef test_set_annotations(doc):\n    assert doc(m.annotate_set_str) == \"annotate_set_str(arg0: set[str]) -> None\"\n\n\ndef test_iterable_annotations(doc):\n    assert (\n        doc(m.annotate_iterable_str)\n        == \"annotate_iterable_str(arg0: collections.abc.Iterable[str]) -> None\"\n    )\n\n\ndef test_iterator_annotations(doc):\n    assert (\n        doc(m.annotate_iterator_int)\n        == \"annotate_iterator_int(arg0: collections.abc.Iterator[typing.SupportsInt | typing.SupportsIndex]) -> None\"\n    )\n\n\ndef test_fn_annotations(doc):\n    assert (\n        doc(m.annotate_fn)\n        == \"annotate_fn(arg0: collections.abc.Callable[[list[str], str], int]) -> None\"\n    )\n\n\ndef test_fn_return_only(doc):\n    assert (\n        doc(m.annotate_fn_only_return)\n        == \"annotate_fn_only_return(arg0: collections.abc.Callable[..., int]) -> None\"\n    )\n\n\ndef test_type_annotation(doc):\n    assert (\n        doc(m.annotate_type)\n        == \"annotate_type(arg0: type[typing.SupportsInt | typing.SupportsIndex]) -> type\"\n    )\n\n\ndef test_union_annotations(doc):\n    assert (\n        doc(m.annotate_union)\n        == \"annotate_union(arg0: list[str | int | object], arg1: str, arg2: int, arg3: object) -> list[str | int | object]\"\n    )\n\n\ndef test_union_typing_only(doc):\n    assert doc(m.union_typing_only) == \"union_typing_only(arg0: list[str]) -> list[int]\"\n\n\ndef test_union_object_annotations(doc):\n    assert (\n        doc(m.annotate_union_to_object)\n        == \"annotate_union_to_object(arg0: typing.SupportsInt | typing.SupportsIndex | str) -> object\"\n    )\n\n\ndef test_optional_annotations(doc):\n    assert (\n        doc(m.annotate_optional) == \"annotate_optional(arg0: list) -> list[str | None]\"\n    )\n\n\ndef test_type_guard_annotations(doc, backport_typehints):\n    assert (\n        backport_typehints(doc(m.annotate_type_guard))\n        == \"annotate_type_guard(arg0: object) -> typing.TypeGuard[str]\"\n    )\n\n\ndef test_type_is_annotations(doc, backport_typehints):\n    assert (\n        backport_typehints(doc(m.annotate_type_is))\n        == \"annotate_type_is(arg0: object) -> typing.TypeIs[str]\"\n    )\n\n\ndef test_no_return_annotation(doc):\n    assert doc(m.annotate_no_return) == \"annotate_no_return() -> typing.NoReturn\"\n\n\ndef test_never_annotation(doc, backport_typehints):\n    assert (\n        backport_typehints(doc(m.annotate_never)) == \"annotate_never() -> typing.Never\"\n    )\n\n\ndef test_optional_object_annotations(doc):\n    assert (\n        doc(m.annotate_optional_to_object)\n        == \"annotate_optional_to_object(arg0: typing.SupportsInt | typing.SupportsIndex | None) -> object\"\n    )\n\n\n@pytest.mark.skipif(\n    not m.defined_PYBIND11_TYPING_H_HAS_STRING_LITERAL,\n    reason=\"C++20 non-type template args feature not available.\",\n)\ndef test_literal(doc):\n    assert (\n        doc(m.annotate_literal)\n        == 'annotate_literal(arg0: typing.Literal[26, 0x1A, \"hello world\", b\"hello world\", u\"hello world\", True, Color.RED, None]) -> object'\n    )\n    # The characters !, @, %, {, } and -> are used in the signature parser as special characters, but Literal should escape those for the parser to work.\n    assert (\n        doc(m.identity_literal_exclamation)\n        == 'identity_literal_exclamation(arg0: typing.Literal[\"!\"]) -> typing.Literal[\"!\"]'\n    )\n    assert (\n        doc(m.identity_literal_at)\n        == 'identity_literal_at(arg0: typing.Literal[\"@\"]) -> typing.Literal[\"@\"]'\n    )\n    assert (\n        doc(m.identity_literal_percent)\n        == 'identity_literal_percent(arg0: typing.Literal[\"%\"]) -> typing.Literal[\"%\"]'\n    )\n    assert (\n        doc(m.identity_literal_curly_open)\n        == 'identity_literal_curly_open(arg0: typing.Literal[\"{\"]) -> typing.Literal[\"{\"]'\n    )\n    assert (\n        doc(m.identity_literal_curly_close)\n        == 'identity_literal_curly_close(arg0: typing.Literal[\"}\"]) -> typing.Literal[\"}\"]'\n    )\n    assert (\n        doc(m.identity_literal_arrow_with_io_name)\n        == 'identity_literal_arrow_with_io_name(arg0: typing.Literal[\"->\"], arg1: float | int) -> typing.Literal[\"->\"]'\n    )\n    assert (\n        doc(m.identity_literal_arrow_with_callable)\n        == 'identity_literal_arrow_with_callable(arg0: collections.abc.Callable[[typing.Literal[\"->\"], float | int], float]) -> collections.abc.Callable[[typing.Literal[\"->\"], float | int], float]'\n    )\n    assert (\n        doc(m.identity_literal_all_special_chars)\n        == 'identity_literal_all_special_chars(arg0: typing.Literal[\"!@!!->{%}\"]) -> typing.Literal[\"!@!!->{%}\"]'\n    )\n\n\n@pytest.mark.skipif(\n    not m.defined_PYBIND11_TYPING_H_HAS_STRING_LITERAL,\n    reason=\"C++20 non-type template args feature not available.\",\n)\ndef test_typevar(doc):\n    assert (\n        doc(m.annotate_generic_containers)\n        == \"annotate_generic_containers(arg0: list[T]) -> list[V]\"\n    )\n\n    assert doc(m.annotate_listT_to_T) == \"annotate_listT_to_T(arg0: list[T]) -> T\"\n\n    assert doc(m.annotate_object_to_T) == \"annotate_object_to_T(arg0: object) -> T\"\n\n\n@pytest.mark.skipif(\n    not m.defined_PYBIND11_TEST_PYTYPES_HAS_RANGES,\n    reason=\"<ranges> not available.\",\n)\n@pytest.mark.parametrize(\n    (\"tested_tuple\", \"expected\"),\n    [((1,), [2]), ((3, 4), [4, 5]), ((7, 8, 9), [8, 9, 10])],\n)\ndef test_tuple_ranges(tested_tuple, expected):\n    assert m.tuple_iterator_default_initialization()\n    assert m.transform_tuple_plus_one(tested_tuple) == expected\n\n\n@pytest.mark.skipif(\n    not m.defined_PYBIND11_TEST_PYTYPES_HAS_RANGES,\n    reason=\"<ranges> not available.\",\n)\n@pytest.mark.parametrize(\n    (\"tested_list\", \"expected\"), [([1], [2]), ([3, 4], [4, 5]), ([7, 8, 9], [8, 9, 10])]\n)\ndef test_list_ranges(tested_list, expected):\n    assert m.list_iterator_default_initialization()\n    assert m.transform_list_plus_one(tested_list) == expected\n\n\n@pytest.mark.skipif(\n    not m.defined_PYBIND11_TEST_PYTYPES_HAS_RANGES,\n    reason=\"<ranges> not available.\",\n)\n@pytest.mark.parametrize(\n    (\"tested_dict\", \"expected\"),\n    [\n        ({1: 2}, [(2, 3)]),\n        ({3: 4, 5: 6}, [(4, 5), (6, 7)]),\n        ({7: 8, 9: 10, 11: 12}, [(8, 9), (10, 11), (12, 13)]),\n    ],\n)\ndef test_dict_ranges(tested_dict, expected):\n    assert m.dict_iterator_default_initialization()\n    assert m.transform_dict_plus_one(tested_dict) == expected\n\n\n# https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older\ndef get_annotations_helper(o):\n    if sys.version_info >= (3, 14):\n        import annotationlib\n\n        return annotationlib.get_annotations(o) or None\n    if isinstance(o, type):\n        return o.__dict__.get(\"__annotations__\", None)\n    return getattr(o, \"__annotations__\", None)\n\n\n@pytest.mark.skipif(\n    not m.defined___cpp_inline_variables,\n    reason=\"C++17 feature __cpp_inline_variables not available.\",\n)\ndef test_module_attribute_types() -> None:\n    module_annotations = get_annotations_helper(m)\n\n    assert (\n        module_annotations[\"list_int\"]\n        == \"list[typing.SupportsInt | typing.SupportsIndex]\"\n    )\n    assert module_annotations[\"set_str\"] == \"set[str]\"\n    assert module_annotations[\"foo\"] == \"pybind11_tests.pytypes.foo\"\n\n    assert (\n        module_annotations[\"foo_union\"]\n        == \"pybind11_tests.pytypes.foo | pybind11_tests.pytypes.foo2 | pybind11_tests.pytypes.foo3\"\n    )\n\n\n@pytest.mark.skipif(\n    not m.defined___cpp_inline_variables,\n    reason=\"C++17 feature __cpp_inline_variables not available.\",\n)\n@pytest.mark.skipif(\n    sys.version_info < (3, 10),\n    reason=\"get_annotations function does not exist until Python3.10\",\n)\ndef test_get_annotations_compliance() -> None:\n    from inspect import get_annotations\n\n    module_annotations = get_annotations(m)\n\n    assert (\n        module_annotations[\"list_int\"]\n        == \"list[typing.SupportsInt | typing.SupportsIndex]\"\n    )\n    assert module_annotations[\"set_str\"] == \"set[str]\"\n\n\n@pytest.mark.skipif(\n    not m.defined___cpp_inline_variables,\n    reason=\"C++17 feature __cpp_inline_variables not available.\",\n)\ndef test_class_attribute_types() -> None:\n    empty_annotations = get_annotations_helper(m.EmptyAnnotationClass)\n    static_annotations = get_annotations_helper(m.Static)\n    instance_annotations = get_annotations_helper(m.Instance)\n\n    assert empty_annotations is None\n    assert (\n        static_annotations[\"x\"]\n        == \"typing.ClassVar[typing.SupportsFloat | typing.SupportsIndex]\"\n    )\n    assert (\n        static_annotations[\"dict_str_int\"]\n        == \"typing.ClassVar[dict[str, typing.SupportsInt | typing.SupportsIndex]]\"\n    )\n\n    assert m.Static.x == 1.0\n\n    m.Static.x = 3.0\n    static = m.Static()\n    assert static.x == 3.0\n\n    static.dict_str_int[\"hi\"] = 3\n    assert m.Static().dict_str_int == {\"hi\": 3}\n\n    assert instance_annotations[\"y\"] == \"typing.SupportsFloat | typing.SupportsIndex\"\n    instance1 = m.Instance()\n    instance1.y = 4.0\n\n    instance2 = m.Instance()\n    instance2.y = 5.0\n\n    assert instance1.y != instance2.y\n\n\n@pytest.mark.skipif(\n    not m.defined___cpp_inline_variables,\n    reason=\"C++17 feature __cpp_inline_variables not available.\",\n)\ndef test_redeclaration_attr_with_type_hint() -> None:\n    obj = m.Instance()\n    m.attr_with_type_hint_float_x(obj)\n    assert (\n        get_annotations_helper(obj)[\"x\"]\n        == \"typing.SupportsFloat | typing.SupportsIndex\"\n    )\n    with pytest.raises(\n        RuntimeError, match=r'^__annotations__\\[\"x\"\\] was set already\\.$'\n    ):\n        m.attr_with_type_hint_float_x(obj)\n\n\n@pytest.mark.skipif(\n    not m.defined___cpp_inline_variables,\n    reason=\"C++17 feature __cpp_inline_variables not available.\",\n)\ndef test_final_annotation() -> None:\n    module_annotations = get_annotations_helper(m)\n    assert module_annotations[\"CONST_INT\"] == \"typing.Final[int]\"\n\n\ndef test_arg_return_type_hints(doc, backport_typehints):\n    assert doc(m.half_of_number) == \"half_of_number(arg0: float | int) -> float\"\n    assert (\n        doc(m.half_of_number_convert)\n        == \"half_of_number_convert(x: float | int) -> float\"\n    )\n    assert (\n        doc(m.half_of_number_noconvert) == \"half_of_number_noconvert(x: float) -> float\"\n    )\n    assert m.half_of_number(2.0) == 1.0\n    assert m.half_of_number(2) == 1.0\n    assert m.half_of_number(0) == 0\n    assert isinstance(m.half_of_number(0), float)\n    assert not isinstance(m.half_of_number(0), int)\n\n    # std::vector<T>\n    assert (\n        doc(m.half_of_number_vector)\n        == \"half_of_number_vector(arg0: collections.abc.Sequence[float | int]) -> list[float]\"\n    )\n    # Tuple<T, T>\n    assert (\n        doc(m.half_of_number_tuple)\n        == \"half_of_number_tuple(arg0: tuple[float | int, float | int]) -> tuple[float, float]\"\n    )\n    # Tuple<T, ...>\n    assert (\n        doc(m.half_of_number_tuple_ellipsis)\n        == \"half_of_number_tuple_ellipsis(arg0: tuple[float | int, ...]) -> tuple[float, ...]\"\n    )\n    # Dict<K, V>\n    assert (\n        doc(m.half_of_number_dict)\n        == \"half_of_number_dict(arg0: dict[str, float | int]) -> dict[str, float]\"\n    )\n    # List<T>\n    assert (\n        doc(m.half_of_number_list)\n        == \"half_of_number_list(arg0: list[float | int]) -> list[float]\"\n    )\n    # List<List<T>>\n    assert (\n        doc(m.half_of_number_nested_list)\n        == \"half_of_number_nested_list(arg0: list[list[float | int]]) -> list[list[float]]\"\n    )\n    # Set<T>\n    assert doc(m.identity_set) == \"identity_set(arg0: set[float | int]) -> set[float]\"\n    # Iterable<T>\n    assert (\n        doc(m.identity_iterable)\n        == \"identity_iterable(arg0: collections.abc.Iterable[float | int]) -> collections.abc.Iterable[float]\"\n    )\n    # Iterator<T>\n    assert (\n        doc(m.identity_iterator)\n        == \"identity_iterator(arg0: collections.abc.Iterator[float | int]) -> collections.abc.Iterator[float]\"\n    )\n    # Callable<R(A)> identity\n    assert (\n        doc(m.identity_callable)\n        == \"identity_callable(arg0: collections.abc.Callable[[float | int], float]) -> collections.abc.Callable[[float | int], float]\"\n    )\n    # Callable<R(...)> identity\n    assert (\n        doc(m.identity_callable_ellipsis)\n        == \"identity_callable_ellipsis(arg0: collections.abc.Callable[..., float]) -> collections.abc.Callable[..., float]\"\n    )\n    # Nested Callable<R(A)> identity\n    assert (\n        doc(m.identity_nested_callable)\n        == \"identity_nested_callable(arg0: collections.abc.Callable[[collections.abc.Callable[[float | int], float]], collections.abc.Callable[[float | int], float]]) -> collections.abc.Callable[[collections.abc.Callable[[float | int], float]], collections.abc.Callable[[float | int], float]]\"\n    )\n    # Callable<R(A)>\n    assert (\n        doc(m.apply_callable)\n        == \"apply_callable(arg0: float | int, arg1: collections.abc.Callable[[float | int], float]) -> float\"\n    )\n    # Callable<R(...)>\n    assert (\n        doc(m.apply_callable_ellipsis)\n        == \"apply_callable_ellipsis(arg0: float | int, arg1: collections.abc.Callable[..., float]) -> float\"\n    )\n    # Union<T1, T2>\n    assert (\n        doc(m.identity_union)\n        == \"identity_union(arg0: float | int | str) -> float | str\"\n    )\n    # Optional<T>\n    assert (\n        doc(m.identity_optional)\n        == \"identity_optional(arg0: float | int | None) -> float | None\"\n    )\n    # TypeIs<T>\n    assert (\n        backport_typehints(doc(m.check_type_is))\n        == \"check_type_is(arg0: object) -> typing.TypeIs[float]\"\n    )\n    # TypeGuard<T>\n    assert (\n        backport_typehints(doc(m.check_type_guard))\n        == \"check_type_guard(arg0: list[object]) -> typing.TypeGuard[list[float]]\"\n    )\n\n\ndef test_const_kwargs_ref_to_str():\n    assert m.const_kwargs_ref_to_str() == \"{}\"\n    assert m.const_kwargs_ref_to_str(a=1) == \"{'a': 1}\"\n"
  },
  {
    "path": "tests/test_scoped_critical_section.cpp",
    "content": "#include <pybind11/critical_section.h>\n\n#include \"pybind11_tests.h\"\n\n#include <atomic>\n#include <chrono>\n#include <thread>\n#include <utility>\n\n#if defined(PYBIND11_HAS_STD_BARRIER)\n#    include <barrier>\n#endif\n\nnamespace test_scoped_critical_section_ns {\n\nvoid test_one_nullptr() { py::scoped_critical_section lock{py::handle{}}; }\n\nvoid test_two_nullptrs() { py::scoped_critical_section lock{py::handle{}, py::handle{}}; }\n\nvoid test_first_nullptr() {\n    py::dict d;\n    py::scoped_critical_section lock{py::handle{}, d};\n}\n\nvoid test_second_nullptr() {\n    py::dict d;\n    py::scoped_critical_section lock{d, py::handle{}};\n}\n\n// Referenced test implementation: https://github.com/PyO3/pyo3/blob/v0.25.0/src/sync.rs#L874\nclass BoolWrapper {\npublic:\n    explicit BoolWrapper(bool value) : value_{value} {}\n    bool get() const { return value_.load(std::memory_order_acquire); }\n    void set(bool value) { value_.store(value, std::memory_order_release); }\n\nprivate:\n    std::atomic_bool value_{false};\n};\n\n#if defined(PYBIND11_HAS_STD_BARRIER)\n\n// Modifying the C/C++ members of a Python object from multiple threads requires a critical section\n// to ensure thread safety and data integrity.\n// These tests use a scoped critical section to ensure that the Python object is accessed in a\n// thread-safe manner.\n\nvoid test_scoped_critical_section(const py::handle &cls) {\n    auto barrier = std::barrier(2);\n    auto bool_wrapper = cls(false);\n    bool output = false;\n\n    {\n        // Release the GIL to allow run threads in parallel.\n        py::gil_scoped_release gil_release{};\n\n        std::thread t1([&]() {\n            // Use gil_scoped_acquire to ensure we have a valid Python thread state\n            // before entering the critical section. Otherwise, the critical section\n            // will cause a segmentation fault.\n            py::gil_scoped_acquire ensure_tstate{};\n            // Enter the critical section with the same object as the second thread.\n            py::scoped_critical_section lock{bool_wrapper};\n            // At this point, the object is locked by this thread via the scoped_critical_section.\n            // This barrier will ensure that the second thread waits until this thread has released\n            // the critical section before proceeding.\n            barrier.arrive_and_wait();\n            // Sleep for a short time to simulate some work in the critical section.\n            // This sleep is necessary to test the locking mechanism properly.\n            std::this_thread::sleep_for(std::chrono::milliseconds(10));\n            auto *bw = bool_wrapper.cast<BoolWrapper *>();\n            bw->set(true);\n        });\n\n        std::thread t2([&]() {\n            // This thread will wait until the first thread has entered the critical section due to\n            // the barrier.\n            barrier.arrive_and_wait();\n            {\n                // Use gil_scoped_acquire to ensure we have a valid Python thread state\n                // before entering the critical section. Otherwise, the critical section\n                // will cause a segmentation fault.\n                py::gil_scoped_acquire ensure_tstate{};\n                // Enter the critical section with the same object as the first thread.\n                py::scoped_critical_section lock{bool_wrapper};\n                // At this point, the critical section is released by the first thread, the value\n                // is set to true.\n                auto *bw = bool_wrapper.cast<BoolWrapper *>();\n                output = bw->get();\n            }\n        });\n\n        t1.join();\n        t2.join();\n    }\n\n    if (!output) {\n        throw std::runtime_error(\"Scoped critical section test failed: output is false\");\n    }\n}\n\nvoid test_scoped_critical_section2(const py::handle &cls) {\n    auto barrier = std::barrier(3);\n    auto bool_wrapper1 = cls(false);\n    auto bool_wrapper2 = cls(false);\n    std::pair<bool, bool> output{false, false};\n\n    {\n        // Release the GIL to allow run threads in parallel.\n        py::gil_scoped_release gil_release{};\n\n        std::thread t1([&]() {\n            // Use gil_scoped_acquire to ensure we have a valid Python thread state\n            // before entering the critical section. Otherwise, the critical section\n            // will cause a segmentation fault.\n            py::gil_scoped_acquire ensure_tstate{};\n            // Enter the critical section with two different objects.\n            // This will ensure that the critical section is locked for both objects.\n            py::scoped_critical_section lock{bool_wrapper1, bool_wrapper2};\n            // At this point, objects are locked by this thread via the scoped_critical_section.\n            // This barrier will ensure that other threads wait until this thread has released\n            // the critical section before proceeding.\n            barrier.arrive_and_wait();\n            // Sleep for a short time to simulate some work in the critical section.\n            // This sleep is necessary to test the locking mechanism properly.\n            std::this_thread::sleep_for(std::chrono::milliseconds(10));\n            auto *bw1 = bool_wrapper1.cast<BoolWrapper *>();\n            auto *bw2 = bool_wrapper2.cast<BoolWrapper *>();\n            bw1->set(true);\n            bw2->set(true);\n        });\n\n        std::thread t2([&]() {\n            // This thread will wait until the first thread has entered the critical section due to\n            // the barrier.\n            barrier.arrive_and_wait();\n            {\n                // Use gil_scoped_acquire to ensure we have a valid Python thread state\n                // before entering the critical section. Otherwise, the critical section\n                // will cause a segmentation fault.\n                py::gil_scoped_acquire ensure_tstate{};\n                // Enter the critical section with the same object as the first thread.\n                py::scoped_critical_section lock{bool_wrapper1};\n                // At this point, the critical section is released by the first thread, the value\n                // is set to true.\n                auto *bw1 = bool_wrapper1.cast<BoolWrapper *>();\n                output.first = bw1->get();\n            }\n        });\n\n        std::thread t3([&]() {\n            // This thread will wait until the first thread has entered the critical section due to\n            // the barrier.\n            barrier.arrive_and_wait();\n            {\n                // Use gil_scoped_acquire to ensure we have a valid Python thread state\n                // before entering the critical section. Otherwise, the critical section\n                // will cause a segmentation fault.\n                py::gil_scoped_acquire ensure_tstate{};\n                // Enter the critical section with the same object as the first thread.\n                py::scoped_critical_section lock{bool_wrapper2};\n                // At this point, the critical section is released by the first thread, the value\n                // is set to true.\n                auto *bw2 = bool_wrapper2.cast<BoolWrapper *>();\n                output.second = bw2->get();\n            }\n        });\n\n        t1.join();\n        t2.join();\n        t3.join();\n    }\n\n    if (!output.first || !output.second) {\n        throw std::runtime_error(\n            \"Scoped critical section test with two objects failed: output is false\");\n    }\n}\n\nvoid test_scoped_critical_section2_same_object_no_deadlock(const py::handle &cls) {\n    auto barrier = std::barrier(2);\n    auto bool_wrapper = cls(false);\n    bool output = false;\n\n    {\n        // Release the GIL to allow run threads in parallel.\n        py::gil_scoped_release gil_release{};\n\n        std::thread t1([&]() {\n            // Use gil_scoped_acquire to ensure we have a valid Python thread state\n            // before entering the critical section. Otherwise, the critical section\n            // will cause a segmentation fault.\n            py::gil_scoped_acquire ensure_tstate{};\n            // Enter the critical section with the same object as the second thread.\n            py::scoped_critical_section lock{bool_wrapper, bool_wrapper}; // same object used here\n            // At this point, the object is locked by this thread via the scoped_critical_section.\n            // This barrier will ensure that the second thread waits until this thread has released\n            // the critical section before proceeding.\n            barrier.arrive_and_wait();\n            // Sleep for a short time to simulate some work in the critical section.\n            // This sleep is necessary to test the locking mechanism properly.\n            std::this_thread::sleep_for(std::chrono::milliseconds(10));\n            auto *bw = bool_wrapper.cast<BoolWrapper *>();\n            bw->set(true);\n        });\n\n        std::thread t2([&]() {\n            // This thread will wait until the first thread has entered the critical section due to\n            // the barrier.\n            barrier.arrive_and_wait();\n            {\n                // Use gil_scoped_acquire to ensure we have a valid Python thread state\n                // before entering the critical section. Otherwise, the critical section\n                // will cause a segmentation fault.\n                py::gil_scoped_acquire ensure_tstate{};\n                // Enter the critical section with the same object as the first thread.\n                py::scoped_critical_section lock{bool_wrapper};\n                // At this point, the critical section is released by the first thread, the value\n                // is set to true.\n                auto *bw = bool_wrapper.cast<BoolWrapper *>();\n                output = bw->get();\n            }\n        });\n\n        t1.join();\n        t2.join();\n    }\n\n    if (!output) {\n        throw std::runtime_error(\n            \"Scoped critical section test with same object failed: output is false\");\n    }\n}\n\n#else\n\nvoid test_scoped_critical_section(const py::handle &) {}\nvoid test_scoped_critical_section2(const py::handle &) {}\nvoid test_scoped_critical_section2_same_object_no_deadlock(const py::handle &) {}\n\n#endif\n\n} // namespace test_scoped_critical_section_ns\n\nTEST_SUBMODULE(scoped_critical_section, m) {\n    using namespace test_scoped_critical_section_ns;\n\n    m.def(\"test_one_nullptr\", test_one_nullptr);\n    m.def(\"test_two_nullptrs\", test_two_nullptrs);\n    m.def(\"test_first_nullptr\", test_first_nullptr);\n    m.def(\"test_second_nullptr\", test_second_nullptr);\n\n    auto BoolWrapperClass = py::class_<BoolWrapper>(m, \"BoolWrapper\")\n                                .def(py::init<bool>())\n                                .def(\"get\", &BoolWrapper::get)\n                                .def(\"set\", &BoolWrapper::set);\n    auto BoolWrapperHandle = py::handle(BoolWrapperClass);\n    (void) BoolWrapperHandle.ptr(); // suppress unused variable warning\n\n    m.attr(\"has_barrier\") =\n#ifdef PYBIND11_HAS_STD_BARRIER\n        true;\n#else\n        false;\n#endif\n\n    m.def(\"test_scoped_critical_section\",\n          [BoolWrapperHandle]() -> void { test_scoped_critical_section(BoolWrapperHandle); });\n    m.def(\"test_scoped_critical_section2\",\n          [BoolWrapperHandle]() -> void { test_scoped_critical_section2(BoolWrapperHandle); });\n    m.def(\"test_scoped_critical_section2_same_object_no_deadlock\", [BoolWrapperHandle]() -> void {\n        test_scoped_critical_section2_same_object_no_deadlock(BoolWrapperHandle);\n    });\n}\n"
  },
  {
    "path": "tests/test_scoped_critical_section.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import scoped_critical_section as m\n\n\ndef test_nullptr_combinations():\n    m.test_one_nullptr()\n    m.test_two_nullptrs()\n    m.test_first_nullptr()\n    m.test_second_nullptr()\n\n\n@pytest.mark.skipif(not m.has_barrier, reason=\"no <barrier>\")\ndef test_scoped_critical_section() -> None:\n    for _ in range(64):\n        m.test_scoped_critical_section()\n\n\n@pytest.mark.skipif(not m.has_barrier, reason=\"no <barrier>\")\ndef test_scoped_critical_section2() -> None:\n    for _ in range(64):\n        m.test_scoped_critical_section2()\n\n\n@pytest.mark.skipif(not m.has_barrier, reason=\"no <barrier>\")\ndef test_scoped_critical_section2_same_object_no_deadlock() -> None:\n    for _ in range(64):\n        m.test_scoped_critical_section2_same_object_no_deadlock()\n"
  },
  {
    "path": "tests/test_sequences_and_iterators.cpp",
    "content": "/*\n    tests/test_sequences_and_iterators.cpp -- supporting Pythons' sequence protocol, iterators,\n    etc.\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/operators.h>\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <algorithm>\n#include <utility>\n#include <vector>\n\n#ifdef PYBIND11_HAS_OPTIONAL\n#    include <optional>\n#endif // PYBIND11_HAS_OPTIONAL\n\ntemplate <typename T>\nclass NonZeroIterator {\n    const T *ptr_;\n\npublic:\n    explicit NonZeroIterator(const T *ptr) : ptr_(ptr) {}\n\n    // Make the iterator non-copyable and movable\n    NonZeroIterator(const NonZeroIterator &) = delete;\n    NonZeroIterator(NonZeroIterator &&) noexcept = default;\n    NonZeroIterator &operator=(const NonZeroIterator &) = delete;\n    NonZeroIterator &operator=(NonZeroIterator &&) noexcept = default;\n\n    const T &operator*() const { return *ptr_; }\n    NonZeroIterator &operator++() {\n        ++ptr_;\n        return *this;\n    }\n};\n\nclass NonZeroSentinel {};\n\ntemplate <typename A, typename B>\nbool operator==(const NonZeroIterator<std::pair<A, B>> &it, const NonZeroSentinel &) {\n    return !(*it).first || !(*it).second;\n}\n\n/* Iterator where dereferencing returns prvalues instead of references. */\ntemplate <typename T>\nclass NonRefIterator {\n    const T *ptr_;\n\npublic:\n    explicit NonRefIterator(const T *ptr) : ptr_(ptr) {}\n    T operator*() const { return T(*ptr_); }\n    NonRefIterator &operator++() {\n        ++ptr_;\n        return *this;\n    }\n    bool operator==(const NonRefIterator &other) const { return ptr_ == other.ptr_; }\n};\n\nclass NonCopyableInt {\npublic:\n    explicit NonCopyableInt(int value) : value_(value) {}\n    NonCopyableInt(const NonCopyableInt &) = delete;\n    NonCopyableInt(NonCopyableInt &&other) noexcept : value_(other.value_) {\n        other.value_ = -1; // detect when an unwanted move occurs\n    }\n    NonCopyableInt &operator=(const NonCopyableInt &) = delete;\n    NonCopyableInt &operator=(NonCopyableInt &&other) noexcept {\n        value_ = other.value_;\n        other.value_ = -1; // detect when an unwanted move occurs\n        return *this;\n    }\n    int get() const { return value_; }\n    void set(int value) { value_ = value; }\n    ~NonCopyableInt() = default;\n\nprivate:\n    int value_;\n};\nusing NonCopyableIntPair = std::pair<NonCopyableInt, NonCopyableInt>;\n\nPYBIND11_MAKE_OPAQUE(std::vector<NonCopyableInt>)\nPYBIND11_MAKE_OPAQUE(std::vector<NonCopyableIntPair>)\n\ntemplate <typename PythonType>\npy::list test_random_access_iterator(const PythonType &x) {\n    if (x.size() < 5) {\n        throw py::value_error(\"Please provide at least 5 elements for testing.\");\n    }\n\n    auto checks = py::list();\n    auto assert_equal = [&checks](py::handle a, py::handle b) {\n        auto result = PyObject_RichCompareBool(a.ptr(), b.ptr(), Py_EQ);\n        if (result == -1) {\n            throw py::error_already_set();\n        }\n        checks.append(result != 0);\n    };\n\n    auto it = x.begin();\n    assert_equal(x[0], *it);\n    assert_equal(x[0], it[0]);\n    assert_equal(x[1], it[1]);\n\n    assert_equal(x[1], *(++it));\n    assert_equal(x[1], *(it++));\n    assert_equal(x[2], *it);\n    assert_equal(x[3], *(it += 1));\n    assert_equal(x[2], *(--it));\n    assert_equal(x[2], *(it--));\n    assert_equal(x[1], *it);\n    assert_equal(x[0], *(it -= 1));\n\n    assert_equal(it->attr(\"real\"), x[0].attr(\"real\"));\n    assert_equal((it + 1)->attr(\"real\"), x[1].attr(\"real\"));\n\n    assert_equal(x[1], *(it + 1));\n    assert_equal(x[1], *(1 + it));\n    it += 3;\n    assert_equal(x[1], *(it - 2));\n\n    checks.append(static_cast<std::size_t>(x.end() - x.begin()) == x.size());\n    checks.append((x.begin() + static_cast<std::ptrdiff_t>(x.size())) == x.end());\n    checks.append(x.begin() < x.end());\n\n    return checks;\n}\n\nTEST_SUBMODULE(sequences_and_iterators, m) {\n    // test_sliceable\n    class Sliceable {\n    public:\n        explicit Sliceable(int n) : size(n) {}\n        int start, stop, step;\n        int size;\n    };\n    py::class_<Sliceable>(m, \"Sliceable\")\n        .def(py::init<int>())\n        .def(\"__getitem__\", [](const Sliceable &s, const py::slice &slice) {\n            py::ssize_t start = 0, stop = 0, step = 0, slicelength = 0;\n            if (!slice.compute(s.size, &start, &stop, &step, &slicelength)) {\n                throw py::error_already_set();\n            }\n            int istart = static_cast<int>(start);\n            int istop = static_cast<int>(stop);\n            int istep = static_cast<int>(step);\n            return std::make_tuple(istart, istop, istep);\n        });\n\n    m.def(\"make_forward_slice_size_t\", []() { return py::slice(0, -1, 1); });\n    m.def(\"make_reversed_slice_object\",\n          []() { return py::slice(py::none(), py::none(), py::int_(-1)); });\n#ifdef PYBIND11_HAS_OPTIONAL\n    m.attr(\"has_optional\") = true;\n    m.def(\"make_reversed_slice_size_t_optional_verbose\",\n          []() { return py::slice(std::nullopt, std::nullopt, -1); });\n    // Warning: The following spelling may still compile if optional<> is not present and give\n    // wrong answers. Please use with caution.\n    m.def(\"make_reversed_slice_size_t_optional\", []() { return py::slice({}, {}, -1); });\n#else\n    m.attr(\"has_optional\") = false;\n#endif\n\n    // test_sequence\n    class Sequence {\n    public:\n        explicit Sequence(size_t size) : m_size(size) {\n            print_created(this, \"of size\", m_size);\n            // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n            m_data = new float[size];\n            memset(m_data, 0, sizeof(float) * size);\n        }\n        explicit Sequence(const std::vector<float> &value) : m_size(value.size()) {\n            print_created(this, \"of size\", m_size, \"from std::vector\");\n            // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n            m_data = new float[m_size];\n            memcpy(m_data, &value[0], sizeof(float) * m_size);\n        }\n        Sequence(const Sequence &s) : m_size(s.m_size) {\n            print_copy_created(this);\n            // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)\n            m_data = new float[m_size];\n            memcpy(m_data, s.m_data, sizeof(float) * m_size);\n        }\n        Sequence(Sequence &&s) noexcept : m_size(s.m_size), m_data(s.m_data) {\n            print_move_created(this);\n            s.m_size = 0;\n            s.m_data = nullptr;\n        }\n\n        ~Sequence() {\n            print_destroyed(this);\n            delete[] m_data;\n        }\n\n        Sequence &operator=(const Sequence &s) {\n            if (&s != this) {\n                delete[] m_data;\n                m_size = s.m_size;\n                m_data = new float[m_size];\n                memcpy(m_data, s.m_data, sizeof(float) * m_size);\n            }\n            print_copy_assigned(this);\n            return *this;\n        }\n\n        Sequence &operator=(Sequence &&s) noexcept {\n            if (&s != this) {\n                delete[] m_data;\n                m_size = s.m_size;\n                m_data = s.m_data;\n                s.m_size = 0;\n                s.m_data = nullptr;\n            }\n            print_move_assigned(this);\n            return *this;\n        }\n\n        bool operator==(const Sequence &s) const {\n            if (m_size != s.size()) {\n                return false;\n            }\n            for (size_t i = 0; i < m_size; ++i) {\n                if (m_data[i] != s[i]) {\n                    return false;\n                }\n            }\n            return true;\n        }\n        bool operator!=(const Sequence &s) const { return !operator==(s); }\n\n        float operator[](size_t index) const { return m_data[index]; }\n        float &operator[](size_t index) { return m_data[index]; }\n\n        bool contains(float v) const {\n            for (size_t i = 0; i < m_size; ++i) {\n                if (v == m_data[i]) {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        Sequence reversed() const {\n            Sequence result(m_size);\n            for (size_t i = 0; i < m_size; ++i) {\n                result[m_size - i - 1] = m_data[i];\n            }\n            return result;\n        }\n\n        size_t size() const { return m_size; }\n\n        const float *begin() const { return m_data; }\n        const float *end() const { return m_data + m_size; }\n\n    private:\n        size_t m_size;\n        float *m_data;\n    };\n    py::class_<Sequence>(m, \"Sequence\")\n        .def(py::init<size_t>())\n        .def(py::init<const std::vector<float> &>())\n        /// Bare bones interface\n        .def(\"__getitem__\",\n             [](const Sequence &s, size_t i) {\n                 if (i >= s.size()) {\n                     throw py::index_error();\n                 }\n                 return s[i];\n             })\n        .def(\"__setitem__\",\n             [](Sequence &s, size_t i, float v) {\n                 if (i >= s.size()) {\n                     throw py::index_error();\n                 }\n                 s[i] = v;\n             })\n        .def(\"__len__\", &Sequence::size)\n        /// Optional sequence protocol operations\n        .def(\n            \"__iter__\",\n            [](const Sequence &s) { return py::make_iterator(s.begin(), s.end()); },\n            py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)\n        .def(\"__contains__\", [](const Sequence &s, float v) { return s.contains(v); })\n        .def(\"__reversed__\", [](const Sequence &s) -> Sequence { return s.reversed(); })\n        /// Slicing protocol (optional)\n        .def(\"__getitem__\",\n             [](const Sequence &s, const py::slice &slice) -> Sequence * {\n                 size_t start = 0, stop = 0, step = 0, slicelength = 0;\n                 if (!slice.compute(s.size(), &start, &stop, &step, &slicelength)) {\n                     throw py::error_already_set();\n                 }\n                 auto *seq = new Sequence(slicelength);\n                 for (size_t i = 0; i < slicelength; ++i) {\n                     (*seq)[i] = s[start];\n                     start += step;\n                 }\n                 return seq;\n             })\n        .def(\"__setitem__\",\n             [](Sequence &s, const py::slice &slice, const Sequence &value) {\n                 size_t start = 0, stop = 0, step = 0, slicelength = 0;\n                 if (!slice.compute(s.size(), &start, &stop, &step, &slicelength)) {\n                     throw py::error_already_set();\n                 }\n                 if (slicelength != value.size()) {\n                     throw std::runtime_error(\n                         \"Left and right hand size of slice assignment have different sizes!\");\n                 }\n                 for (size_t i = 0; i < slicelength; ++i) {\n                     s[start] = value[i];\n                     start += step;\n                 }\n             })\n        /// Comparisons\n        .def(py::self == py::self)\n        .def(py::self != py::self)\n        // Could also define py::self + py::self for concatenation, etc.\n        ;\n\n    // test_map_iterator\n    // Interface of a map-like object that isn't (directly) an unordered_map, but provides some\n    // basic map-like functionality.\n    class StringMap {\n    public:\n        StringMap() = default;\n        explicit StringMap(std::unordered_map<std::string, std::string> init)\n            : map(std::move(init)) {}\n\n        void set(const std::string &key, std::string val) { map[key] = std::move(val); }\n        std::string get(const std::string &key) const { return map.at(key); }\n        size_t size() const { return map.size(); }\n\n    private:\n        std::unordered_map<std::string, std::string> map;\n\n    public:\n        decltype(map.cbegin()) begin() const { return map.cbegin(); }\n        decltype(map.cend()) end() const { return map.cend(); }\n    };\n    py::class_<StringMap>(m, \"StringMap\")\n        .def(py::init<>())\n        .def(py::init<std::unordered_map<std::string, std::string>>())\n        .def(\"__getitem__\",\n             [](const StringMap &map, const std::string &key) {\n                 try {\n                     return map.get(key);\n                 } catch (const std::out_of_range &) {\n                     throw py::key_error(\"key '\" + key + \"' does not exist\");\n                 }\n             })\n        .def(\"__setitem__\", &StringMap::set)\n        .def(\"__len__\", &StringMap::size)\n        .def(\n            \"__iter__\",\n            [](const StringMap &map) { return py::make_key_iterator(map.begin(), map.end()); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"items\",\n            [](const StringMap &map) { return py::make_iterator(map.begin(), map.end()); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"values\",\n            [](const StringMap &map) { return py::make_value_iterator(map.begin(), map.end()); },\n            py::keep_alive<0, 1>());\n\n    // test_generalized_iterators\n    class IntPairs {\n    public:\n        explicit IntPairs(std::vector<std::pair<int, int>> data) : data_(std::move(data)) {}\n        const std::pair<int, int> *begin() const { return data_.data(); }\n        // .end() only required for py::make_iterator(self) overload\n        const std::pair<int, int> *end() const { return data_.data() + data_.size(); }\n\n    private:\n        std::vector<std::pair<int, int>> data_;\n    };\n\n    {\n        // #4383 : Make sure `py::make_*iterator` functions work with move-only iterators\n        using iterator_t = NonZeroIterator<std::pair<int, int>>;\n\n        static_assert(std::is_move_assignable<iterator_t>::value, \"\");\n        static_assert(std::is_move_constructible<iterator_t>::value, \"\");\n        static_assert(!std::is_copy_assignable<iterator_t>::value, \"\");\n        static_assert(!std::is_copy_constructible<iterator_t>::value, \"\");\n    }\n\n    py::class_<IntPairs>(m, \"IntPairs\")\n        .def(py::init<std::vector<std::pair<int, int>>>())\n        .def(\n            \"nonzero\",\n            [](const IntPairs &s) {\n                return py::make_iterator(NonZeroIterator<std::pair<int, int>>(s.begin()),\n                                         NonZeroSentinel());\n            },\n            py::keep_alive<0, 1>())\n        .def(\n            \"nonzero_keys\",\n            [](const IntPairs &s) {\n                return py::make_key_iterator(NonZeroIterator<std::pair<int, int>>(s.begin()),\n                                             NonZeroSentinel());\n            },\n            py::keep_alive<0, 1>())\n        .def(\n            \"nonzero_values\",\n            [](const IntPairs &s) {\n                return py::make_value_iterator(NonZeroIterator<std::pair<int, int>>(s.begin()),\n                                               NonZeroSentinel());\n            },\n            py::keep_alive<0, 1>())\n\n        // test iterator that returns values instead of references\n        .def(\n            \"nonref\",\n            [](const IntPairs &s) {\n                return py::make_iterator(NonRefIterator<std::pair<int, int>>(s.begin()),\n                                         NonRefIterator<std::pair<int, int>>(s.end()));\n            },\n            py::keep_alive<0, 1>())\n        .def(\n            \"nonref_keys\",\n            [](const IntPairs &s) {\n                return py::make_key_iterator(NonRefIterator<std::pair<int, int>>(s.begin()),\n                                             NonRefIterator<std::pair<int, int>>(s.end()));\n            },\n            py::keep_alive<0, 1>())\n        .def(\n            \"nonref_values\",\n            [](const IntPairs &s) {\n                return py::make_value_iterator(NonRefIterator<std::pair<int, int>>(s.begin()),\n                                               NonRefIterator<std::pair<int, int>>(s.end()));\n            },\n            py::keep_alive<0, 1>())\n\n        // test single-argument make_iterator\n        .def(\n            \"simple_iterator\",\n            [](IntPairs &self) { return py::make_iterator(self); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"simple_keys\",\n            [](IntPairs &self) { return py::make_key_iterator(self); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"simple_values\",\n            [](IntPairs &self) { return py::make_value_iterator(self); },\n            py::keep_alive<0, 1>())\n\n        // Test iterator with an Extra (doesn't do anything useful, so not used\n        // at runtime, but tests need to be able to compile with the correct\n        // overload. See PR #3293.\n        .def(\n            \"_make_iterator_extras\",\n            [](IntPairs &self) { return py::make_iterator(self, py::call_guard<int>()); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"_make_key_extras\",\n            [](IntPairs &self) { return py::make_key_iterator(self, py::call_guard<int>()); },\n            py::keep_alive<0, 1>())\n        .def(\n            \"_make_value_extras\",\n            [](IntPairs &self) { return py::make_value_iterator(self, py::call_guard<int>()); },\n            py::keep_alive<0, 1>());\n\n    // test_iterator_referencing\n    py::class_<NonCopyableInt>(m, \"NonCopyableInt\")\n        .def(py::init<int>())\n        .def(\"set\", &NonCopyableInt::set)\n        .def(\"__int__\", &NonCopyableInt::get);\n    py::class_<std::vector<NonCopyableInt>>(m, \"VectorNonCopyableInt\")\n        .def(py::init<>())\n        .def(\"append\",\n             [](std::vector<NonCopyableInt> &vec, int value) { vec.emplace_back(value); })\n        .def(\"__iter__\", [](std::vector<NonCopyableInt> &vec) {\n            return py::make_iterator(vec.begin(), vec.end());\n        });\n    py::class_<std::vector<NonCopyableIntPair>>(m, \"VectorNonCopyableIntPair\")\n        .def(py::init<>())\n        .def(\"append\",\n             [](std::vector<NonCopyableIntPair> &vec, const std::pair<int, int> &value) {\n                 vec.emplace_back(NonCopyableInt(value.first), NonCopyableInt(value.second));\n             })\n        .def(\"keys\",\n             [](std::vector<NonCopyableIntPair> &vec) {\n                 return py::make_key_iterator(vec.begin(), vec.end());\n             })\n        .def(\"values\", [](std::vector<NonCopyableIntPair> &vec) {\n            return py::make_value_iterator(vec.begin(), vec.end());\n        });\n\n#if 0\n    // Obsolete: special data structure for exposing custom iterator types to python\n    // kept here for illustrative purposes because there might be some use cases which\n    // are not covered by the much simpler py::make_iterator\n\n    struct PySequenceIterator {\n        PySequenceIterator(const Sequence &seq, py::object ref) : seq(seq), ref(ref) { }\n\n        float next() {\n            if (index == seq.size())\n                throw py::stop_iteration();\n            return seq[index++];\n        }\n\n        const Sequence &seq;\n        py::object ref; // keep a reference\n        size_t index = 0;\n    };\n\n    py::class_<PySequenceIterator>(seq, \"Iterator\")\n        .def(\"__iter__\", [](PySequenceIterator &it) -> PySequenceIterator& { return it; })\n        .def(\"__next__\", &PySequenceIterator::next);\n\n    On the actual Sequence object, the iterator would be constructed as follows:\n    .def(\"__iter__\", [](py::object s) { return PySequenceIterator(s.cast<const Sequence &>(), s); })\n#endif\n\n    // test_python_iterator_in_cpp\n    m.def(\"object_to_list\", [](const py::object &o) {\n        auto l = py::list();\n        for (auto item : o) {\n            l.append(item);\n        }\n        return l;\n    });\n\n    m.def(\"iterator_to_list\", [](py::iterator it) {\n        auto l = py::list();\n        while (it != py::iterator::sentinel()) {\n            l.append(*it);\n            ++it;\n        }\n        return l;\n    });\n\n    // test_sequence_length: check that Python sequences can be converted to py::sequence.\n    m.def(\"sequence_length\", [](const py::sequence &seq) { return seq.size(); });\n\n    // Make sure that py::iterator works with std algorithms\n    m.def(\"count_none\", [](const py::object &o) {\n        return std::count_if(o.begin(), o.end(), [](py::handle h) { return h.is_none(); });\n    });\n\n    m.def(\"find_none\", [](const py::object &o) {\n        auto it = std::find_if(o.begin(), o.end(), [](py::handle h) { return h.is_none(); });\n        return it->is_none();\n    });\n\n    m.def(\"count_nonzeros\", [](const py::dict &d) {\n        return std::count_if(d.begin(), d.end(), [](const std::pair<py::handle, py::handle> &p) {\n            return p.second.cast<int>() != 0;\n        });\n    });\n\n    m.def(\"tuple_iterator\", &test_random_access_iterator<py::tuple>);\n    m.def(\"list_iterator\", &test_random_access_iterator<py::list>);\n    m.def(\"sequence_iterator\", &test_random_access_iterator<py::sequence>);\n\n    // test_iterator_passthrough\n    // #181: iterator passthrough did not compile\n    m.def(\"iterator_passthrough\", [](py::iterator s) -> py::iterator {\n        return py::make_iterator(std::begin(s), std::end(s));\n    });\n\n    // test_iterator_rvp\n    // #388: Can't make iterators via make_iterator() with different r/v policies\n    static std::vector<int> list = {1, 2, 3};\n    m.def(\"make_iterator_1\",\n          []() { return py::make_iterator<py::return_value_policy::copy>(list); });\n    m.def(\"make_iterator_2\",\n          []() { return py::make_iterator<py::return_value_policy::automatic>(list); });\n\n    // test_iterator on c arrays\n    // #4100: ensure lvalue required as increment operand\n    class CArrayHolder {\n    public:\n        CArrayHolder(double x, double y, double z) {\n            values[0] = x;\n            values[1] = y;\n            values[2] = z;\n        };\n        double values[3];\n    };\n\n    py::class_<CArrayHolder>(m, \"CArrayHolder\")\n        .def(py::init<double, double, double>())\n        .def(\n            \"__iter__\",\n            [](const CArrayHolder &v) { return py::make_iterator(v.values, v.values + 3); },\n            py::keep_alive<0, 1>());\n}\n"
  },
  {
    "path": "tests/test_sequences_and_iterators.py",
    "content": "from __future__ import annotations\n\nimport re\n\nimport pytest\nfrom pytest import approx  # noqa: PT013\n\nimport env\nfrom pybind11_tests import ConstructorStats\nfrom pybind11_tests import sequences_and_iterators as m\n\n\ndef test_slice_constructors():\n    assert m.make_forward_slice_size_t() == slice(0, -1, 1)\n    assert m.make_reversed_slice_object() == slice(None, None, -1)\n\n\n@pytest.mark.skipif(not m.has_optional, reason=\"no <optional>\")\ndef test_slice_constructors_explicit_optional():\n    assert m.make_reversed_slice_size_t_optional() == slice(None, None, -1)\n    assert m.make_reversed_slice_size_t_optional_verbose() == slice(None, None, -1)\n\n\ndef test_generalized_iterators():\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)]\n    assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)]\n    assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == []\n\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3]\n    assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1]\n    assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == []\n\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_values()) == [2, 4]\n    assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_values()) == [2]\n    assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_values()) == []\n\n    # __next__ must continue to raise StopIteration\n    it = m.IntPairs([(0, 0)]).nonzero()\n    for _ in range(3):\n        with pytest.raises(StopIteration):\n            next(it)\n\n    it = m.IntPairs([(0, 0)]).nonzero_keys()\n    for _ in range(3):\n        with pytest.raises(StopIteration):\n            next(it)\n\n\ndef test_nonref_iterators():\n    pairs = m.IntPairs([(1, 2), (3, 4), (0, 5)])\n    assert list(pairs.nonref()) == [(1, 2), (3, 4), (0, 5)]\n    assert list(pairs.nonref_keys()) == [1, 3, 0]\n    assert list(pairs.nonref_values()) == [2, 4, 5]\n\n\ndef test_generalized_iterators_simple():\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_iterator()) == [\n        (1, 2),\n        (3, 4),\n        (0, 5),\n    ]\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_keys()) == [1, 3, 0]\n    assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_values()) == [2, 4, 5]\n\n\ndef test_iterator_doc_annotations():\n    assert m.IntPairs.nonref.__doc__.endswith(\n        \"-> collections.abc.Iterator[tuple[int, int]]\\n\"\n    )\n    assert m.IntPairs.nonref_keys.__doc__.endswith(\"-> collections.abc.Iterator[int]\\n\")\n    assert m.IntPairs.nonref_values.__doc__.endswith(\n        \"-> collections.abc.Iterator[int]\\n\"\n    )\n    assert m.IntPairs.simple_iterator.__doc__.endswith(\n        \"-> collections.abc.Iterator[tuple[int, int]]\\n\"\n    )\n    assert m.IntPairs.simple_keys.__doc__.endswith(\"-> collections.abc.Iterator[int]\\n\")\n    assert m.IntPairs.simple_values.__doc__.endswith(\n        \"-> collections.abc.Iterator[int]\\n\"\n    )\n\n\ndef test_iterator_referencing():\n    \"\"\"Test that iterators reference rather than copy their referents.\"\"\"\n    vec = m.VectorNonCopyableInt()\n    vec.append(3)\n    vec.append(5)\n    assert [int(x) for x in vec] == [3, 5]\n    # Increment everything to make sure the referents can be mutated\n    for x in vec:\n        x.set(int(x) + 1)\n    assert [int(x) for x in vec] == [4, 6]\n\n    vec = m.VectorNonCopyableIntPair()\n    vec.append([3, 4])\n    vec.append([5, 7])\n    assert [int(x) for x in vec.keys()] == [3, 5]\n    assert [int(x) for x in vec.values()] == [4, 7]\n    for x in vec.keys():\n        x.set(int(x) + 1)\n    for x in vec.values():\n        x.set(int(x) + 10)\n    assert [int(x) for x in vec.keys()] == [4, 6]\n    assert [int(x) for x in vec.values()] == [14, 17]\n\n\ndef test_sliceable():\n    sliceable = m.Sliceable(100)\n    assert sliceable[::] == (0, 100, 1)\n    assert sliceable[10::] == (10, 100, 1)\n    assert sliceable[:10:] == (0, 10, 1)\n    assert sliceable[::10] == (0, 100, 10)\n    assert sliceable[-10::] == (90, 100, 1)\n    assert sliceable[:-10:] == (0, 90, 1)\n    assert sliceable[::-10] == (99, -1, -10)\n    assert sliceable[50:60:1] == (50, 60, 1)\n    assert sliceable[50:60:-1] == (50, 60, -1)\n\n\ndef test_sequence():\n    cstats = ConstructorStats.get(m.Sequence)\n\n    s = m.Sequence(5)\n    if not env.GRAALPY:\n        assert cstats.values() == [\"of size\", \"5\"]\n\n    assert \"Sequence\" in repr(s)\n    assert len(s) == 5\n    assert s[0] == 0\n    assert s[3] == 0\n    assert 12.34 not in s\n    s[0], s[3] = 12.34, 56.78\n    assert 12.34 in s\n    assert s[0] == approx(12.34, rel=1e-05)\n    assert s[3] == approx(56.78, rel=1e-05)\n\n    rev = reversed(s)\n    if not env.GRAALPY:\n        assert cstats.values() == [\"of size\", \"5\"]\n\n    rev2 = s[::-1]\n    if not env.GRAALPY:\n        assert cstats.values() == [\"of size\", \"5\"]\n\n    it = iter(m.Sequence(0))\n    for _ in range(3):  # __next__ must continue to raise StopIteration\n        with pytest.raises(StopIteration):\n            next(it)\n    if not env.GRAALPY:\n        assert cstats.values() == [\"of size\", \"0\"]\n\n    expected = [0, 56.78, 0, 0, 12.34]\n    assert rev == approx(expected, rel=1e-05)\n    assert rev2 == approx(expected, rel=1e-05)\n    assert rev == rev2\n\n    rev[0::2] = m.Sequence([2.0, 2.0, 2.0])\n    if not env.GRAALPY:\n        assert cstats.values() == [\"of size\", \"3\", \"from std::vector\"]\n\n    assert rev == approx([2, 56.78, 2, 0, 2], rel=1e-05)\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    assert cstats.alive() == 4\n    del it\n    assert cstats.alive() == 3\n    del s\n    assert cstats.alive() == 2\n    del rev\n    assert cstats.alive() == 1\n    del rev2\n    assert cstats.alive() == 0\n\n    assert cstats.values() == []\n    assert cstats.default_constructions == 0\n    assert cstats.copy_constructions == 0\n    assert cstats.move_constructions >= 1\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n\ndef test_sequence_length():\n    \"\"\"#2076: Exception raised by len(arg) should be propagated\"\"\"\n\n    class BadLen(RuntimeError):\n        pass\n\n    class SequenceLike:\n        def __getitem__(self, i):\n            return None\n\n        def __len__(self):\n            raise BadLen()\n\n    with pytest.raises(BadLen):\n        m.sequence_length(SequenceLike())\n\n    assert m.sequence_length([1, 2, 3]) == 3\n    assert m.sequence_length(\"hello\") == 5\n\n\ndef test_sequence_doc():\n    assert (\n        m.sequence_length.__doc__.strip()\n        == \"sequence_length(arg0: collections.abc.Sequence) -> int\"\n    )\n\n\ndef test_map_iterator():\n    sm = m.StringMap({\"hi\": \"bye\", \"black\": \"white\"})\n    assert sm[\"hi\"] == \"bye\"\n    assert len(sm) == 2\n    assert sm[\"black\"] == \"white\"\n\n    with pytest.raises(KeyError):\n        assert sm[\"orange\"]\n    sm[\"orange\"] = \"banana\"\n    assert sm[\"orange\"] == \"banana\"\n\n    expected = {\"hi\": \"bye\", \"black\": \"white\", \"orange\": \"banana\"}\n    for k in sm:\n        assert sm[k] == expected[k]\n    for k, v in sm.items():\n        assert v == expected[k]\n    assert list(sm.values()) == [expected[k] for k in sm]\n\n    it = iter(m.StringMap({}))\n    for _ in range(3):  # __next__ must continue to raise StopIteration\n        with pytest.raises(StopIteration):\n            next(it)\n\n\ndef test_python_iterator_in_cpp():\n    t = (1, 2, 3)\n    assert m.object_to_list(t) == [1, 2, 3]\n    assert m.object_to_list(iter(t)) == [1, 2, 3]\n    assert m.iterator_to_list(iter(t)) == [1, 2, 3]\n\n    with pytest.raises(TypeError) as excinfo:\n        m.object_to_list(1)\n    assert \"object is not iterable\" in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        m.iterator_to_list(1)\n    assert \"incompatible function arguments\" in str(excinfo.value)\n\n    def bad_next_call():\n        raise RuntimeError(\"py::iterator::advance() should propagate errors\")\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.iterator_to_list(iter(bad_next_call, None))\n    assert str(excinfo.value) == \"py::iterator::advance() should propagate errors\"\n\n    lst = [1, None, 0, None]\n    assert m.count_none(lst) == 2\n    assert m.find_none(lst) is True\n    assert m.count_nonzeros({\"a\": 0, \"b\": 1, \"c\": 2}) == 2\n\n    r = range(5)\n    assert all(m.tuple_iterator(tuple(r)))\n    assert all(m.list_iterator(list(r)))\n    assert all(m.sequence_iterator(r))\n\n\ndef test_iterator_passthrough():\n    \"\"\"#181: iterator passthrough did not compile\"\"\"\n    values = [3, 5, 7, 9, 11, 13, 15]\n    assert list(m.iterator_passthrough(iter(values))) == values\n\n\ndef test_iterator_rvp():\n    \"\"\"#388: Can't make iterators via make_iterator() with different r/v policies\"\"\"\n    assert list(m.make_iterator_1()) == [1, 2, 3]\n    assert list(m.make_iterator_2()) == [1, 2, 3]\n    assert not isinstance(m.make_iterator_1(), type(m.make_iterator_2()))\n\n\ndef test_carray_iterator():\n    \"\"\"#4100: Check for proper iterator overload with C-Arrays\"\"\"\n    args_gt = [float(i) for i in range(3)]\n    arr_h = m.CArrayHolder(*args_gt)\n    args = list(arr_h)\n    assert args_gt == args\n\n\ndef test_generated_dunder_methods_pos_only():\n    string_map = m.StringMap({\"hi\": \"bye\", \"black\": \"white\"})\n    for it in (\n        m.make_iterator_1(),\n        m.make_iterator_2(),\n        m.iterator_passthrough(iter([3, 5, 7])),\n        iter(m.Sequence(5)),\n        iter(string_map),\n        string_map.items(),\n        string_map.values(),\n        iter(m.CArrayHolder(*[float(i) for i in range(3)])),\n    ):\n        assert (\n            re.match(r\"^__iter__\\(self: [\\w\\.]+, /\\)\", type(it).__iter__.__doc__)\n            is not None\n        )\n        assert (\n            re.match(r\"^__next__\\(self: [\\w\\.]+, /\\)\", type(it).__next__.__doc__)\n            is not None\n        )\n"
  },
  {
    "path": "tests/test_smart_ptr.cpp",
    "content": "/*\n    tests/test_smart_ptr.cpp -- binding classes with custom reference counting,\n    implicit conversions between types\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"object.h\"\n#include \"pybind11_tests.h\"\n\n// This breaks on PYBIND11_DECLARE_HOLDER_TYPE\nPYBIND11_WARNING_DISABLE_GCC(\"-Wpedantic\")\n\nnamespace {\n\n// This is just a wrapper around unique_ptr, but with extra fields to deliberately bloat up the\n// holder size to trigger the non-simple-layout internal instance layout for single inheritance\n// with large holder type:\ntemplate <typename T>\nclass huge_unique_ptr {\n    std::unique_ptr<T> ptr;\n    uint64_t padding[10];\n\npublic:\n    explicit huge_unique_ptr(T *p) : ptr(p) {}\n    T *get() { return ptr.get(); }\n};\n\n// Simple custom holder that works like unique_ptr\ntemplate <typename T>\nclass custom_unique_ptr {\n    std::unique_ptr<T> impl;\n\npublic:\n    explicit custom_unique_ptr(T *p) : impl(p) {}\n    T *get() const { return impl.get(); }\n    T *release_ptr() { return impl.release(); }\n};\n\n// Simple custom holder that works like shared_ptr and has operator& overload\n// To obtain address of an instance of this holder pybind should use std::addressof\n// Attempt to get address via operator& may leads to segmentation fault\ntemplate <typename T>\nclass shared_ptr_with_addressof_operator {\n    std::shared_ptr<T> impl;\n\npublic:\n    shared_ptr_with_addressof_operator() = default;\n    explicit shared_ptr_with_addressof_operator(T *p) : impl(p) {}\n    T *get() const { return impl.get(); }\n    T **operator&() { throw std::logic_error(\"Call of overloaded operator& is not expected\"); }\n};\n\n// Simple custom holder that works like unique_ptr and has operator& overload\n// To obtain address of an instance of this holder pybind should use std::addressof\n// Attempt to get address via operator& may leads to segmentation fault\ntemplate <typename T>\nclass unique_ptr_with_addressof_operator {\n    std::unique_ptr<T> impl;\n\npublic:\n    unique_ptr_with_addressof_operator() = default;\n    explicit unique_ptr_with_addressof_operator(T *p) : impl(p) {}\n    T *get() const { return impl.get(); }\n    T *release_ptr() { return impl.release(); }\n    T **operator&() { throw std::logic_error(\"Call of overloaded operator& is not expected\"); }\n};\n\n// Simple custom holder that imitates smart pointer, that always stores cpointer to const\ntemplate <class T>\nclass const_only_shared_ptr {\n    std::shared_ptr<const T> ptr_;\n\npublic:\n    const_only_shared_ptr() = default;\n    explicit const_only_shared_ptr(const T *ptr) : ptr_(ptr) {}\n    const T *get() const { return ptr_.get(); }\n\nprivate:\n    // for demonstration purpose only, this imitates smart pointer with a const-only pointer\n};\n\n// Custom object with builtin reference counting (see 'object.h' for the implementation)\nclass MyObject1 : public Object {\npublic:\n    explicit MyObject1(int value) : value(value) { print_created(this, toString()); }\n    std::string toString() const override { return \"MyObject1[\" + std::to_string(value) + \"]\"; }\n\nprotected:\n    ~MyObject1() override { print_destroyed(this); }\n\nprivate:\n    int value;\n};\n\n// Object managed by a std::shared_ptr<>\nclass MyObject2 {\npublic:\n    MyObject2(const MyObject2 &) = default;\n    explicit MyObject2(int value) : value(value) { print_created(this, toString()); }\n    std::string toString() const { return \"MyObject2[\" + std::to_string(value) + \"]\"; }\n    virtual ~MyObject2() { print_destroyed(this); }\n\nprivate:\n    int value;\n};\n\n// Object managed by a std::shared_ptr<>, additionally derives from std::enable_shared_from_this<>\nclass MyObject3 : public std::enable_shared_from_this<MyObject3> {\npublic:\n    MyObject3(const MyObject3 &) = default;\n    explicit MyObject3(int value) : value(value) { print_created(this, toString()); }\n    std::string toString() const { return \"MyObject3[\" + std::to_string(value) + \"]\"; }\n    virtual ~MyObject3() { print_destroyed(this); }\n\nprivate:\n    int value;\n};\n\ntemplate <typename T>\nstd::unordered_set<T *> &pointer_set() {\n    // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables\n    static auto singleton = new std::unordered_set<T *>();\n    return *singleton;\n}\n\n// test_unique_nodelete\n// Object with a private destructor\nclass MyObject4 {\npublic:\n    explicit MyObject4(int value) : value{value} {\n        print_created(this);\n        pointer_set<MyObject4>().insert(this);\n    }\n    int value;\n\n    static void cleanupAllInstances() {\n        auto tmp = std::move(pointer_set<MyObject4>());\n        pointer_set<MyObject4>().clear();\n        for (auto *o : tmp) {\n            delete o;\n        }\n    }\n\nprivate:\n    ~MyObject4() {\n        pointer_set<MyObject4>().erase(this);\n        print_destroyed(this);\n    }\n};\n\n// test_unique_deleter\n// Object with std::unique_ptr<T, D> where D is not matching the base class\n// Object with a protected destructor\nclass MyObject4a {\npublic:\n    explicit MyObject4a(int i) : value{i} {\n        print_created(this);\n        pointer_set<MyObject4a>().insert(this);\n    };\n    MyObject4a(const MyObject4a &) = delete;\n\n    int value;\n\n    static void cleanupAllInstances() {\n        auto tmp = std::move(pointer_set<MyObject4a>());\n        pointer_set<MyObject4a>().clear();\n        for (auto *o : tmp) {\n            delete o;\n        }\n    }\n\nprotected:\n    virtual ~MyObject4a() {\n        pointer_set<MyObject4a>().erase(this);\n        print_destroyed(this);\n    }\n};\n\n// Object derived but with public destructor and no Deleter in default holder\nclass MyObject4b : public MyObject4a {\npublic:\n    explicit MyObject4b(int i) : MyObject4a(i) { print_created(this); }\n    MyObject4b(const MyObject4b &) = delete;\n    ~MyObject4b() override { print_destroyed(this); }\n};\n\n// test_large_holder\nclass MyObject5 { // managed by huge_unique_ptr\npublic:\n    explicit MyObject5(int value) : value{value} { print_created(this); }\n    MyObject5(const MyObject5 &) = delete;\n    ~MyObject5() { print_destroyed(this); }\n    int value;\n};\n\n// test const_only_shared_ptr\nclass MyObject6 {\npublic:\n    static const_only_shared_ptr<MyObject6> createObject(std::string value) {\n        return const_only_shared_ptr<MyObject6>(new MyObject6(std::move(value)));\n    }\n\n    const std::string &value() const { return value_; }\n\nprivate:\n    explicit MyObject6(std::string &&value) : value_{std::move(value)} {}\n    std::string value_;\n};\n\n// test_shared_ptr_and_references\nstruct SharedPtrRef {\n    struct A {\n        A() { print_created(this); }\n        A(const A &) { print_copy_created(this); }\n        A(A &&) noexcept { print_move_created(this); }\n        ~A() { print_destroyed(this); }\n    };\n\n    A value;\n    std::shared_ptr<A> shared = std::make_shared<A>();\n};\n\n// test_shared_ptr_from_this_and_references\nstruct SharedFromThisRef {\n    struct B : std::enable_shared_from_this<B> {\n        B() { print_created(this); }\n        // NOLINTNEXTLINE(bugprone-copy-constructor-init, readability-redundant-member-init)\n        B(const B &) : std::enable_shared_from_this<B>() { print_copy_created(this); }\n        // NOLINTNEXTLINE(readability-redundant-member-init)\n        B(B &&) noexcept : std::enable_shared_from_this<B>() { print_move_created(this); }\n        ~B() { print_destroyed(this); }\n    };\n\n    B value;\n    std::shared_ptr<B> shared = std::make_shared<B>();\n};\n\n// Issue #865: shared_from_this doesn't work with virtual inheritance\nstruct SharedFromThisVBase : std::enable_shared_from_this<SharedFromThisVBase> {\n    SharedFromThisVBase() = default;\n    SharedFromThisVBase(const SharedFromThisVBase &) = default;\n    virtual ~SharedFromThisVBase() = default;\n};\nstruct SharedFromThisVirt : virtual SharedFromThisVBase {};\n\n// test_move_only_holder\nstruct C {\n    C() { print_created(this); }\n    C(const C &) = delete;\n    ~C() { print_destroyed(this); }\n};\n\n// test_holder_with_addressof_operator\nstruct TypeForHolderWithAddressOf {\n    TypeForHolderWithAddressOf() { print_created(this); }\n    TypeForHolderWithAddressOf(const TypeForHolderWithAddressOf &) { print_copy_created(this); }\n    TypeForHolderWithAddressOf(TypeForHolderWithAddressOf &&) noexcept {\n        print_move_created(this);\n    }\n    ~TypeForHolderWithAddressOf() { print_destroyed(this); }\n    std::string toString() const {\n        return \"TypeForHolderWithAddressOf[\" + std::to_string(value) + \"]\";\n    }\n    int value = 42;\n};\n\n// test_move_only_holder_with_addressof_operator\nstruct TypeForMoveOnlyHolderWithAddressOf {\n    explicit TypeForMoveOnlyHolderWithAddressOf(int value) : value{value} { print_created(this); }\n    TypeForMoveOnlyHolderWithAddressOf(const TypeForMoveOnlyHolderWithAddressOf &) = delete;\n    ~TypeForMoveOnlyHolderWithAddressOf() { print_destroyed(this); }\n    std::string toString() const {\n        return \"MoveOnlyHolderWithAddressOf[\" + std::to_string(value) + \"]\";\n    }\n    int value;\n};\n\n// test_smart_ptr_from_default\nstruct HeldByDefaultHolder {};\n\n// test_shared_ptr_gc\n// #187: issue involving std::shared_ptr<> return value policy & garbage collection\nstruct ElementBase {\n    virtual ~ElementBase() = default; /* Force creation of virtual table */\n    ElementBase() = default;\n    ElementBase(const ElementBase &) = delete;\n};\n\nstruct ElementA : ElementBase {\n    explicit ElementA(int v) : v(v) {}\n    int value() const { return v; }\n    int v;\n};\n\nstruct ElementList {\n    void add(const std::shared_ptr<ElementBase> &e) { l.push_back(e); }\n    std::vector<std::shared_ptr<ElementBase>> l;\n};\n\n} // namespace\n\n// ref<T> is a wrapper for 'Object' which uses intrusive reference counting\n// It is always possible to construct a ref<T> from an Object* pointer without\n// possible inconsistencies, hence the 'true' argument at the end.\n// Make pybind11 aware of the non-standard getter member function\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <typename T>\nstruct holder_helper<ref<T>> {\n    static const T *get(const ref<T> &p) { return p.get_ptr(); }\n};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n\n// Make pybind aware of the ref-counted wrapper type (s):\nPYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>, true)\nPYBIND11_DECLARE_HOLDER_TYPE(T, const_only_shared_ptr<T>, true)\n// The following is not required anymore for std::shared_ptr, but it should compile without error:\nPYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)\nPYBIND11_DECLARE_HOLDER_TYPE(T, huge_unique_ptr<T>)\nPYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>)\nPYBIND11_DECLARE_HOLDER_TYPE(T, shared_ptr_with_addressof_operator<T>)\nPYBIND11_DECLARE_HOLDER_TYPE(T, unique_ptr_with_addressof_operator<T>)\n\nnamespace holder_caster_traits_test {\nstruct example_base {};\n} // namespace holder_caster_traits_test\n\nPYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)\nPYBIND11_NAMESPACE_BEGIN(detail)\n\n// Negate this condition to demonstrate \"ambiguous template instantiation\" compilation error:\n#if defined(PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT)\ntemplate <typename ExampleType>\nstruct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<\n    ExampleType,\n    enable_if_t<std::is_base_of<holder_caster_traits_test::example_base, ExampleType>::value>>\n    : std::false_type {};\n#endif\n\ntemplate <typename ExampleType, typename HolderType>\nstruct copyable_holder_caster<\n    ExampleType,\n    HolderType,\n    enable_if_t<std::is_base_of<holder_caster_traits_test::example_base, ExampleType>::value>> {\n    static constexpr auto name = const_name<ExampleType>();\n\n    static handle cast(const HolderType &, return_value_policy, handle) {\n        return str(\"copyable_holder_caster_traits_test\").release();\n    }\n};\n\n// Negate this condition to demonstrate \"ambiguous template instantiation\" compilation error:\n#if defined(PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT)\ntemplate <typename ExampleType>\nstruct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<\n    ExampleType,\n    enable_if_t<std::is_base_of<holder_caster_traits_test::example_base, ExampleType>::value>>\n    : std::false_type {};\n#endif\n\ntemplate <typename ExampleType, typename HolderType>\nstruct move_only_holder_caster<\n    ExampleType,\n    HolderType,\n    enable_if_t<std::is_base_of<holder_caster_traits_test::example_base, ExampleType>::value>> {\n    static constexpr auto name = const_name<ExampleType>();\n\n    static handle cast(const HolderType &, return_value_policy, handle) {\n        return str(\"move_only_holder_caster_traits_test\").release();\n    }\n};\n\nPYBIND11_NAMESPACE_END(detail)\nPYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)\n\nnamespace holder_caster_traits_test {\n\nstruct example_drvd : example_base {};\n\nvoid wrap(py::module_ &m) {\n    m.def(\"return_std_shared_ptr_example_drvd\",\n          // NOLINTNEXTLINE(modernize-make-shared)\n          []() { return std::shared_ptr<example_drvd>(new example_drvd()); });\n    m.def(\"return_std_unique_ptr_example_drvd\",\n          []() { return std::unique_ptr<example_drvd>(new example_drvd()); });\n}\n\n} // namespace holder_caster_traits_test\n\nTEST_SUBMODULE(smart_ptr, m) {\n    // Please do not interleave `struct` and `class` definitions with bindings code,\n    // but implement `struct`s and `class`es in the anonymous namespace above.\n    // This helps keeping the smart_holder branch in sync with master.\n\n    // test_smart_ptr\n\n    // Object implementation in `object.h`\n    py::class_<Object, ref<Object>> obj(m, \"Object\");\n    obj.def(\"getRefCount\", &Object::getRefCount);\n\n    py::class_<MyObject1, ref<MyObject1>>(m, \"MyObject1\", obj).def(py::init<int>());\n    py::implicitly_convertible<py::int_, MyObject1>();\n\n    m.def(\"make_object_1\", []() -> Object * { return new MyObject1(1); });\n    m.def(\"make_object_2\", []() -> ref<Object> { return ref<Object>(new MyObject1(2)); });\n    m.def(\"make_myobject1_1\", []() -> MyObject1 * { return new MyObject1(4); });\n    m.def(\"make_myobject1_2\", []() -> ref<MyObject1> { return ref<MyObject1>(new MyObject1(5)); });\n    m.def(\"print_object_1\", [](const Object *obj) { py::print(obj->toString()); });\n    m.def(\"print_object_2\", [](ref<Object> obj) { py::print(obj->toString()); });\n    m.def(\"print_object_3\", [](const ref<Object> &obj) { py::print(obj->toString()); });\n    m.def(\"print_object_4\", [](const ref<Object> *obj) { py::print((*obj)->toString()); });\n    m.def(\"print_myobject1_1\", [](const MyObject1 *obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject1_2\", [](ref<MyObject1> obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject1_3\", [](const ref<MyObject1> &obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject1_4\", [](const ref<MyObject1> *obj) { py::print((*obj)->toString()); });\n\n    // Expose constructor stats for the ref type\n    m.def(\"cstats_ref\", &ConstructorStats::get<ref_tag>);\n\n    py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, \"MyObject2\").def(py::init<int>());\n    m.def(\"make_myobject2_1\", []() { return new MyObject2(6); });\n    m.def(\"make_myobject2_2\", []() { return std::make_shared<MyObject2>(7); });\n    m.def(\"print_myobject2_1\", [](const MyObject2 *obj) { py::print(obj->toString()); });\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    m.def(\"print_myobject2_2\", [](std::shared_ptr<MyObject2> obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject2_3\",\n          [](const std::shared_ptr<MyObject2> &obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject2_4\",\n          [](const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); });\n\n    py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, \"MyObject3\").def(py::init<int>());\n    m.def(\"make_myobject3_1\", []() { return new MyObject3(8); });\n    m.def(\"make_myobject3_2\", []() { return std::make_shared<MyObject3>(9); });\n    m.def(\"print_myobject3_1\", [](const MyObject3 *obj) { py::print(obj->toString()); });\n    // NOLINTNEXTLINE(performance-unnecessary-value-param)\n    m.def(\"print_myobject3_2\", [](std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject3_3\",\n          [](const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); });\n    m.def(\"print_myobject3_4\",\n          [](const std::shared_ptr<MyObject3> *obj) { py::print((*obj)->toString()); });\n\n    // test_smart_ptr_refcounting\n    m.def(\"test_object1_refcounting\", []() {\n        auto o = ref<MyObject1>(new MyObject1(0));\n        bool good = o->getRefCount() == 1;\n        py::object o2 = py::cast(o, py::return_value_policy::reference);\n        // always request (partial) ownership for objects with intrusive\n        // reference counting even when using the 'reference' RVP\n        good &= o->getRefCount() == 2;\n        return good;\n    });\n\n    // test_unique_nodelete\n    py::class_<MyObject4, std::unique_ptr<MyObject4, py::nodelete>>(m, \"MyObject4\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &MyObject4::value)\n        .def_static(\"cleanup_all_instances\", &MyObject4::cleanupAllInstances);\n\n    // test_unique_deleter\n    py::class_<MyObject4a, std::unique_ptr<MyObject4a, py::nodelete>>(m, \"MyObject4a\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &MyObject4a::value)\n        .def_static(\"cleanup_all_instances\", &MyObject4a::cleanupAllInstances);\n\n    py::class_<MyObject4b, MyObject4a, std::unique_ptr<MyObject4b>>(m, \"MyObject4b\")\n        .def(py::init<int>());\n\n    // test_large_holder\n    py::class_<MyObject5, huge_unique_ptr<MyObject5>>(m, \"MyObject5\")\n        .def(py::init<int>())\n        .def_readwrite(\"value\", &MyObject5::value);\n\n    py::class_<MyObject6, const_only_shared_ptr<MyObject6>>(m, \"MyObject6\")\n        .def(py::init([](const std::string &value) { return MyObject6::createObject(value); }))\n        .def_property_readonly(\"value\", &MyObject6::value);\n\n    // test_shared_ptr_and_references\n    using A = SharedPtrRef::A;\n    py::class_<A, std::shared_ptr<A>>(m, \"A\");\n    py::class_<SharedPtrRef, std::unique_ptr<SharedPtrRef>>(m, \"SharedPtrRef\")\n        .def(py::init<>())\n        .def_readonly(\"ref\", &SharedPtrRef::value)\n        .def_property_readonly(\n            \"copy\", [](const SharedPtrRef &s) { return s.value; }, py::return_value_policy::copy)\n        .def_readonly(\"holder_ref\", &SharedPtrRef::shared)\n        .def_property_readonly(\n            \"holder_copy\",\n            [](const SharedPtrRef &s) { return s.shared; },\n            py::return_value_policy::copy)\n        .def(\"set_ref\", [](SharedPtrRef &, const A &) { return true; })\n        // NOLINTNEXTLINE(performance-unnecessary-value-param)\n        .def(\"set_holder\", [](SharedPtrRef &, std::shared_ptr<A>) { return true; });\n\n    // test_shared_ptr_from_this_and_references\n    using B = SharedFromThisRef::B;\n    py::class_<B, std::shared_ptr<B>>(m, \"B\");\n    py::class_<SharedFromThisRef, std::unique_ptr<SharedFromThisRef>>(m, \"SharedFromThisRef\")\n        .def(py::init<>())\n        .def_readonly(\"bad_wp\", &SharedFromThisRef::value)\n        .def_property_readonly(\"ref\",\n                               [](const SharedFromThisRef &s) -> const B & { return *s.shared; })\n        .def_property_readonly(\n            \"copy\",\n            [](const SharedFromThisRef &s) { return s.value; },\n            py::return_value_policy::copy)\n        .def_readonly(\"holder_ref\", &SharedFromThisRef::shared)\n        .def_property_readonly(\n            \"holder_copy\",\n            [](const SharedFromThisRef &s) { return s.shared; },\n            py::return_value_policy::copy)\n        .def(\"set_ref\", [](SharedFromThisRef &, const B &) { return true; })\n        // NOLINTNEXTLINE(performance-unnecessary-value-param)\n        .def(\"set_holder\", [](SharedFromThisRef &, std::shared_ptr<B>) { return true; });\n\n    // Issue #865: shared_from_this doesn't work with virtual inheritance\n    static std::shared_ptr<SharedFromThisVirt> sft(new SharedFromThisVirt());\n    py::class_<SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>>(m, \"SharedFromThisVirt\")\n        .def_static(\"get\", []() { return sft.get(); });\n\n    // test_move_only_holder\n    py::class_<C, custom_unique_ptr<C>>(m, \"TypeWithMoveOnlyHolder\")\n        .def_static(\"make\", []() { return custom_unique_ptr<C>(new C); })\n        .def_static(\"make_as_object\", []() { return py::cast(custom_unique_ptr<C>(new C)); });\n\n    // test_holder_with_addressof_operator\n    using HolderWithAddressOf = shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>;\n    py::class_<TypeForHolderWithAddressOf, HolderWithAddressOf>(m, \"TypeForHolderWithAddressOf\")\n        .def_static(\"make\", []() { return HolderWithAddressOf(new TypeForHolderWithAddressOf); })\n        .def(\"get\", [](const HolderWithAddressOf &self) { return self.get(); })\n        .def(\"print_object_1\",\n             [](const TypeForHolderWithAddressOf *obj) { py::print(obj->toString()); })\n        // NOLINTNEXTLINE(performance-unnecessary-value-param)\n        .def(\"print_object_2\", [](HolderWithAddressOf obj) { py::print(obj.get()->toString()); })\n        .def(\"print_object_3\",\n             [](const HolderWithAddressOf &obj) { py::print(obj.get()->toString()); })\n        .def(\"print_object_4\",\n             [](const HolderWithAddressOf *obj) { py::print((*obj).get()->toString()); });\n\n    // test_move_only_holder_with_addressof_operator\n    using MoveOnlyHolderWithAddressOf\n        = unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>;\n    py::class_<TypeForMoveOnlyHolderWithAddressOf, MoveOnlyHolderWithAddressOf>(\n        m, \"TypeForMoveOnlyHolderWithAddressOf\")\n        .def_static(\"make\",\n                    []() {\n                        return MoveOnlyHolderWithAddressOf(\n                            new TypeForMoveOnlyHolderWithAddressOf(0));\n                    })\n        .def_readwrite(\"value\", &TypeForMoveOnlyHolderWithAddressOf::value)\n        .def(\"print_object\",\n             [](const TypeForMoveOnlyHolderWithAddressOf *obj) { py::print(obj->toString()); });\n\n    // test_smart_ptr_from_default\n    py::class_<HeldByDefaultHolder, std::unique_ptr<HeldByDefaultHolder>>(m, \"HeldByDefaultHolder\")\n        .def(py::init<>())\n        // NOLINTNEXTLINE(performance-unnecessary-value-param)\n        .def_static(\"load_shared_ptr\", [](std::shared_ptr<HeldByDefaultHolder>) {});\n\n    // test_shared_ptr_gc\n    // #187: issue involving std::shared_ptr<> return value policy & garbage collection\n    py::class_<ElementBase, std::shared_ptr<ElementBase>>(m, \"ElementBase\");\n\n    py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m, \"ElementA\")\n        .def(py::init<int>())\n        .def(\"value\", &ElementA::value);\n\n    py::class_<ElementList, std::shared_ptr<ElementList>>(m, \"ElementList\")\n        .def(py::init<>())\n        .def(\"add\", &ElementList::add)\n        .def(\"get\", [](ElementList &el) {\n            py::list list;\n            for (auto &e : el.l) {\n                list.append(py::cast(e));\n            }\n            return list;\n        });\n\n    // NOLINTNEXTLINE(bugprone-incorrect-enable-shared-from-this)\n    class PrivateESFT : /* implicit private */ std::enable_shared_from_this<PrivateESFT> {};\n    struct ContainerUsingPrivateESFT {\n        std::shared_ptr<PrivateESFT> ptr;\n    };\n    py::class_<ContainerUsingPrivateESFT>(m, \"ContainerUsingPrivateESFT\")\n        .def(py::init<>())\n        .def_readwrite(\"ptr\",\n                       &ContainerUsingPrivateESFT::ptr); // <- access ESFT through shared_ptr\n\n    holder_caster_traits_test::wrap(m);\n}\n"
  },
  {
    "path": "tests/test_smart_ptr.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\n\nm = pytest.importorskip(\"pybind11_tests.smart_ptr\")\nfrom pybind11_tests import ConstructorStats  # noqa: E402\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_smart_ptr(capture):\n    # Object1\n    for i, o in enumerate(\n        [m.make_object_1(), m.make_object_2(), m.MyObject1(3)], start=1\n    ):\n        assert o.getRefCount() == 1\n        with capture:\n            m.print_object_1(o)\n            m.print_object_2(o)\n            m.print_object_3(o)\n            m.print_object_4(o)\n        assert capture == f\"MyObject1[{i}]\\n\" * 4\n\n    for i, o in enumerate(\n        [m.make_myobject1_1(), m.make_myobject1_2(), m.MyObject1(6), 7], start=4\n    ):\n        print(o)\n        with capture:\n            if not isinstance(o, int):\n                m.print_object_1(o)\n                m.print_object_2(o)\n                m.print_object_3(o)\n                m.print_object_4(o)\n            m.print_myobject1_1(o)\n            m.print_myobject1_2(o)\n            m.print_myobject1_3(o)\n            m.print_myobject1_4(o)\n\n        times = 4 if isinstance(o, int) else 8\n        assert capture == f\"MyObject1[{i}]\\n\" * times\n\n    cstats = ConstructorStats.get(m.MyObject1)\n    assert cstats.alive() == 0\n    expected_values = [f\"MyObject1[{i}]\" for i in range(1, 7)] + [\"MyObject1[7]\"] * 4\n    assert cstats.values() == expected_values\n    assert cstats.default_constructions == 0\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0 # Doesn't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n    # Object2\n    for i, o in zip(\n        [8, 6, 7], [m.MyObject2(8), m.make_myobject2_1(), m.make_myobject2_2()]\n    ):\n        print(o)\n        with capture:\n            m.print_myobject2_1(o)\n            m.print_myobject2_2(o)\n            m.print_myobject2_3(o)\n            m.print_myobject2_4(o)\n        assert capture == f\"MyObject2[{i}]\\n\" * 4\n\n    cstats = ConstructorStats.get(m.MyObject2)\n    assert cstats.alive() == 1\n    o = None\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"MyObject2[8]\", \"MyObject2[6]\", \"MyObject2[7]\"]\n    assert cstats.default_constructions == 0\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0 # Doesn't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n    # Object3\n    for i, o in zip(\n        [9, 8, 9], [m.MyObject3(9), m.make_myobject3_1(), m.make_myobject3_2()]\n    ):\n        print(o)\n        with capture:\n            m.print_myobject3_1(o)\n            m.print_myobject3_2(o)\n            m.print_myobject3_3(o)\n            m.print_myobject3_4(o)\n        assert capture == f\"MyObject3[{i}]\\n\" * 4\n\n    cstats = ConstructorStats.get(m.MyObject3)\n    assert cstats.alive() == 1\n    o = None\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"MyObject3[9]\", \"MyObject3[8]\", \"MyObject3[9]\"]\n    assert cstats.default_constructions == 0\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0 # Doesn't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n    # Object\n    cstats = ConstructorStats.get(m.Object)\n    assert cstats.alive() == 0\n    assert cstats.values() == []\n    assert cstats.default_constructions == 10\n    assert cstats.copy_constructions == 0\n    # assert cstats.move_constructions >= 0 # Doesn't invoke any\n    assert cstats.copy_assignments == 0\n    assert cstats.move_assignments == 0\n\n    # ref<>\n    cstats = m.cstats_ref()\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"from pointer\"] * 10\n    assert cstats.default_constructions == 30\n    assert cstats.copy_constructions == 12\n    # assert cstats.move_constructions >= 0 # Doesn't invoke any\n    assert cstats.copy_assignments == 30\n    assert cstats.move_assignments == 0\n\n\ndef test_smart_ptr_refcounting():\n    assert m.test_object1_refcounting()\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_unique_nodelete():\n    o = m.MyObject4(23)\n    assert o.value == 23\n    cstats = ConstructorStats.get(m.MyObject4)\n    assert cstats.alive() == 1\n    del o\n    assert cstats.alive() == 1\n    m.MyObject4.cleanup_all_instances()\n    assert cstats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_unique_nodelete4a():\n    o = m.MyObject4a(23)\n    assert o.value == 23\n    cstats = ConstructorStats.get(m.MyObject4a)\n    assert cstats.alive() == 1\n    del o\n    assert cstats.alive() == 1\n    m.MyObject4a.cleanup_all_instances()\n    assert cstats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_unique_deleter():\n    m.MyObject4a(0)\n    o = m.MyObject4b(23)\n    assert o.value == 23\n    cstats4a = ConstructorStats.get(m.MyObject4a)\n    assert cstats4a.alive() == 2\n    cstats4b = ConstructorStats.get(m.MyObject4b)\n    assert cstats4b.alive() == 1\n    del o\n    assert cstats4a.alive() == 1  # Should now only be one leftover\n    assert cstats4b.alive() == 0  # Should be deleted\n    m.MyObject4a.cleanup_all_instances()\n    assert cstats4a.alive() == 0\n    assert cstats4b.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_large_holder():\n    o = m.MyObject5(5)\n    assert o.value == 5\n    cstats = ConstructorStats.get(m.MyObject5)\n    assert cstats.alive() == 1\n    del o\n    assert cstats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_and_references():\n    s = m.SharedPtrRef()\n    stats = ConstructorStats.get(m.A)\n    assert stats.alive() == 2\n\n    ref = s.ref  # init_holder_helper(holder_ptr=false, owned=false)\n    assert stats.alive() == 2\n    assert s.set_ref(ref)\n    with pytest.raises(RuntimeError) as excinfo:\n        assert s.set_holder(ref)\n    assert \"Unable to cast from non-held to held instance\" in str(excinfo.value)\n\n    copy = s.copy  # init_holder_helper(holder_ptr=false, owned=true)\n    assert stats.alive() == 3\n    assert s.set_ref(copy)\n    assert s.set_holder(copy)\n\n    holder_ref = s.holder_ref  # init_holder_helper(holder_ptr=true, owned=false)\n    assert stats.alive() == 3\n    assert s.set_ref(holder_ref)\n    assert s.set_holder(holder_ref)\n\n    holder_copy = s.holder_copy  # init_holder_helper(holder_ptr=true, owned=true)\n    assert stats.alive() == 3\n    assert s.set_ref(holder_copy)\n    assert s.set_holder(holder_copy)\n\n    del ref, copy, holder_ref, holder_copy, s\n    assert stats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_shared_ptr_from_this_and_references():\n    s = m.SharedFromThisRef()\n    stats = ConstructorStats.get(m.B)\n    assert stats.alive() == 2\n\n    ref = s.ref  # init_holder_helper(holder_ptr=false, owned=false, bad_wp=false)\n    assert stats.alive() == 2\n    assert s.set_ref(ref)\n    assert s.set_holder(\n        ref\n    )  # std::enable_shared_from_this can create a holder from a reference\n\n    bad_wp = s.bad_wp  # init_holder_helper(holder_ptr=false, owned=false, bad_wp=true)\n    assert stats.alive() == 2\n    assert s.set_ref(bad_wp)\n    with pytest.raises(RuntimeError) as excinfo:\n        assert s.set_holder(bad_wp)\n    assert \"Unable to cast from non-held to held instance\" in str(excinfo.value)\n\n    copy = s.copy  # init_holder_helper(holder_ptr=false, owned=true, bad_wp=false)\n    assert stats.alive() == 3\n    assert s.set_ref(copy)\n    assert s.set_holder(copy)\n\n    holder_ref = (\n        s.holder_ref\n    )  # init_holder_helper(holder_ptr=true, owned=false, bad_wp=false)\n    assert stats.alive() == 3\n    assert s.set_ref(holder_ref)\n    assert s.set_holder(holder_ref)\n\n    holder_copy = (\n        s.holder_copy\n    )  # init_holder_helper(holder_ptr=true, owned=true, bad_wp=false)\n    assert stats.alive() == 3\n    assert s.set_ref(holder_copy)\n    assert s.set_holder(holder_copy)\n\n    del ref, bad_wp, copy, holder_ref, holder_copy, s\n    assert stats.alive() == 0\n\n    z = m.SharedFromThisVirt.get()\n    y = m.SharedFromThisVirt.get()\n    assert y is z\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_move_only_holder():\n    a = m.TypeWithMoveOnlyHolder.make()\n    b = m.TypeWithMoveOnlyHolder.make_as_object()\n    stats = ConstructorStats.get(m.TypeWithMoveOnlyHolder)\n    assert stats.alive() == 2\n    del b\n    assert stats.alive() == 1\n    del a\n    assert stats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_holder_with_addressof_operator():\n    # this test must not throw exception from c++\n    a = m.TypeForHolderWithAddressOf.make()\n    a.print_object_1()\n    a.print_object_2()\n    a.print_object_3()\n    a.print_object_4()\n\n    stats = ConstructorStats.get(m.TypeForHolderWithAddressOf)\n    assert stats.alive() == 1\n\n    np = m.TypeForHolderWithAddressOf.make()\n    assert stats.alive() == 2\n    del a\n    assert stats.alive() == 1\n    del np\n    assert stats.alive() == 0\n\n    b = m.TypeForHolderWithAddressOf.make()\n    c = b\n    assert b.get() is c.get()\n    assert stats.alive() == 1\n\n    del b\n    assert stats.alive() == 1\n\n    del c\n    assert stats.alive() == 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_move_only_holder_with_addressof_operator():\n    a = m.TypeForMoveOnlyHolderWithAddressOf.make()\n    a.print_object()\n\n    stats = ConstructorStats.get(m.TypeForMoveOnlyHolderWithAddressOf)\n    assert stats.alive() == 1\n\n    a.value = 42\n    assert a.value == 42\n\n    del a\n    assert stats.alive() == 0\n\n\ndef test_smart_ptr_from_default():\n    instance = m.HeldByDefaultHolder()\n    with pytest.raises(RuntimeError) as excinfo:\n        m.HeldByDefaultHolder.load_shared_ptr(instance)\n    assert \"Unable to load a custom holder type from a default-holder instance\" in str(\n        excinfo.value\n    )\n\n\ndef test_shared_ptr_gc():\n    \"\"\"#187: issue involving std::shared_ptr<> return value policy & garbage collection\"\"\"\n    el = m.ElementList()\n    for i in range(10):\n        el.add(m.ElementA(i))\n    pytest.gc_collect()\n    for i, v in enumerate(el.get()):\n        assert i == v.value()\n\n\ndef test_private_esft_tolerance():\n    # Regression test: binding a shared_ptr<T> member where T privately inherits\n    # enable_shared_from_this<T> must not cause a C++ compile error.\n    c = m.ContainerUsingPrivateESFT()\n    # The ptr member is not actually usable in any way, but this is how the\n    # pybind11 v2 release series worked.\n    with pytest.raises(TypeError):\n        _ = c.ptr  # getattr\n    with pytest.raises(TypeError):\n        c.ptr = None  # setattr\n\n\ndef test_copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled():\n    assert (\n        m.return_std_shared_ptr_example_drvd() == \"copyable_holder_caster_traits_test\"\n    )\n\n\ndef test_move_only_holder_caster_shared_ptr_with_smart_holder_support_enabled():\n    assert (\n        m.return_std_unique_ptr_example_drvd() == \"move_only_holder_caster_traits_test\"\n    )\n\n\ndef test_const_only_holder():\n    o = m.MyObject6(\"my_data\")\n    assert o.value == \"my_data\"\n"
  },
  {
    "path": "tests/test_stl.cpp",
    "content": "/*\n    tests/test_stl.cpp -- STL type casters\n\n    Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#if defined(PYBIND11_HAS_FILESYSTEM) || defined(PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM)\n#    include <pybind11/stl/filesystem.h>\n#endif\n\n#include <pybind11/typing.h>\n\n#include <string>\n#include <vector>\n\n#if defined(PYBIND11_TEST_BOOST)\n#    include <boost/optional.hpp>\n\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <typename T>\nstruct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};\n\ntemplate <>\nstruct type_caster<boost::none_t> : void_caster<boost::none_t> {};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n#endif\n\n// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14\n#if defined(PYBIND11_HAS_VARIANT)\nusing std::variant;\n#    define PYBIND11_TEST_VARIANT 1\n#elif defined(PYBIND11_TEST_BOOST)\n#    include <boost/variant.hpp>\n#    define PYBIND11_TEST_VARIANT 1\nusing boost::variant;\n\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <typename... Ts>\nstruct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};\n\ntemplate <>\nstruct visit_helper<boost::variant> {\n    template <typename... Args>\n    static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {\n        return boost::apply_visitor(args...);\n    }\n};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n#endif\n\nPYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>)\n\n/// Issue #528: templated constructor\nstruct TplCtorClass {\n    template <typename T>\n    explicit TplCtorClass(const T &) {}\n    bool operator==(const TplCtorClass &) const { return true; }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<TplCtorClass> {\n    size_t operator()(const TplCtorClass &) const { return 0; }\n};\n} // namespace std\n\ntemplate <template <typename> class OptionalImpl, typename T>\nstruct OptionalHolder {\n    // NOLINTNEXTLINE(modernize-use-equals-default): breaks GCC 4.8\n    OptionalHolder() {};\n    bool member_initialized() const { return member && member->initialized; }\n    OptionalImpl<T> member = T{};\n};\n\nenum class EnumType {\n    kSet = 42,\n    kUnset = 85,\n};\n\n// This is used to test that return-by-ref and return-by-copy policies are\n// handled properly for optional types. This is a regression test for a dangling\n// reference issue. The issue seemed to require the enum value type to\n// reproduce - it didn't seem to happen if the value type is just an integer.\ntemplate <template <typename> class OptionalImpl>\nclass OptionalProperties {\npublic:\n    using OptionalEnumValue = OptionalImpl<EnumType>;\n\n    OptionalProperties() : value(EnumType::kSet) {}\n    OptionalProperties(const OptionalProperties &) = default;\n    ~OptionalProperties() {\n        // Reset value to detect use-after-destruction.\n        // This is set to a specific value rather than nullopt to ensure that\n        // the memory that contains the value gets re-written.\n        value = EnumType::kUnset;\n    }\n\n    OptionalEnumValue &access_by_ref() { return value; }\n    OptionalEnumValue access_by_copy() { return value; }\n\nprivate:\n    OptionalEnumValue value;\n};\n\n// This type mimics aspects of boost::optional from old versions of Boost,\n// which exposed a dangling reference bug in Pybind11. Recent versions of\n// boost::optional, as well as libstdc++'s std::optional, don't seem to be\n// affected by the same issue. This is meant to be a minimal implementation\n// required to reproduce the issue, not fully standard-compliant.\n// See issue #3330 for more details.\ntemplate <typename T>\nclass ReferenceSensitiveOptional {\npublic:\n    using value_type = T;\n\n    ReferenceSensitiveOptional() = default;\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    ReferenceSensitiveOptional(const T &value) : storage{value} {}\n    // NOLINTNEXTLINE(google-explicit-constructor)\n    ReferenceSensitiveOptional(T &&value) : storage{std::move(value)} {}\n    ReferenceSensitiveOptional &operator=(const T &value) {\n        storage = {value};\n        return *this;\n    }\n    ReferenceSensitiveOptional &operator=(T &&value) {\n        storage = {std::move(value)};\n        return *this;\n    }\n\n    template <typename... Args>\n    T &emplace(Args &&...args) {\n        storage.clear();\n        storage.emplace_back(std::forward<Args>(args)...);\n        return storage.back();\n    }\n\n    const T &value() const noexcept {\n        assert(!storage.empty());\n        return storage[0];\n    }\n\n    const T &operator*() const noexcept { return value(); }\n\n    const T *operator->() const noexcept { return &value(); }\n\n    explicit operator bool() const noexcept { return !storage.empty(); }\n\nprivate:\n    std::vector<T> storage;\n};\n\nnamespace PYBIND11_NAMESPACE {\nnamespace detail {\ntemplate <typename T>\nstruct type_caster<ReferenceSensitiveOptional<T>>\n    : optional_caster<ReferenceSensitiveOptional<T>> {};\n} // namespace detail\n} // namespace PYBIND11_NAMESPACE\n\nint pass_std_vector_int(const std::vector<int> &v) {\n    int zum = 100;\n    for (const int i : v) {\n        zum += 2 * i;\n    }\n    return zum;\n}\n\nTEST_SUBMODULE(stl, m) {\n    // test_vector\n    m.def(\"cast_vector\", []() { return std::vector<int>{1}; });\n    m.def(\"load_vector\", [](const std::vector<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });\n    // `std::vector<bool>` is special because it returns proxy objects instead of references\n    m.def(\"cast_bool_vector\", []() { return std::vector<bool>{true, false}; });\n    m.def(\"load_bool_vector\",\n          [](const std::vector<bool> &v) { return v.at(0) == true && v.at(1) == false; });\n    // Unnumbered regression (caused by #936): pointers to stl containers aren't castable\n    m.def(\n        \"cast_ptr_vector\",\n        []() {\n            // Using no-destructor idiom to side-step warnings from overzealous compilers.\n            static auto *v = new std::vector<RValueCaster>{2};\n            return v;\n        },\n        py::return_value_policy::reference);\n\n    // test_deque\n    m.def(\"cast_deque\", []() { return std::deque<int>{1}; });\n    m.def(\"load_deque\", [](const std::deque<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });\n\n    // test_array\n    m.def(\"cast_array\", []() { return std::array<int, 2>{{1, 2}}; });\n    m.def(\"load_array\", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });\n\n    struct NoDefaultCtor {\n        explicit constexpr NoDefaultCtor(int val) : val{val} {}\n        int val;\n    };\n\n    struct NoDefaultCtorArray {\n        explicit constexpr NoDefaultCtorArray(int i)\n            : arr{{NoDefaultCtor(10 + i), NoDefaultCtor(20 + i)}} {}\n        std::array<NoDefaultCtor, 2> arr;\n    };\n\n    // test_array_no_default_ctor\n    py::class_<NoDefaultCtor>(m, \"NoDefaultCtor\").def_readonly(\"val\", &NoDefaultCtor::val);\n    py::class_<NoDefaultCtorArray>(m, \"NoDefaultCtorArray\")\n        .def(py::init<int>())\n        .def_readwrite(\"arr\", &NoDefaultCtorArray::arr);\n\n    // test_valarray\n    m.def(\"cast_valarray\", []() { return std::valarray<int>{1, 4, 9}; });\n    m.def(\"load_valarray\", [](const std::valarray<int> &v) {\n        return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;\n    });\n\n    // test_map\n    m.def(\"cast_map\", []() { return std::map<std::string, std::string>{{\"key\", \"value\"}}; });\n    m.def(\"load_map\", [](const std::map<std::string, std::string> &map) {\n        return map.at(\"key\") == \"value\" && map.at(\"key2\") == \"value2\";\n    });\n\n    // test_set\n    m.def(\"cast_set\", []() { return std::set<std::string>{\"key1\", \"key2\"}; });\n    m.def(\"load_set\", [](const std::set<std::string> &set) {\n        return (set.count(\"key1\") != 0u) && (set.count(\"key2\") != 0u) && (set.count(\"key3\") != 0u);\n    });\n\n    // test_recursive_casting\n    m.def(\"cast_rv_vector\", []() { return std::vector<RValueCaster>{2}; });\n    m.def(\"cast_rv_array\", []() { return std::array<RValueCaster, 3>(); });\n    // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),\n    // casters don't typically do anything with that, which means they fall to the `const Type &`\n    // caster.\n    m.def(\"cast_rv_map\",\n          []() { return std::unordered_map<std::string, RValueCaster>{{\"a\", RValueCaster{}}}; });\n    m.def(\"cast_rv_nested\", []() {\n        std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;\n        v.emplace_back();           // add an array\n        v.back()[0].emplace_back(); // add a map to the array\n        v.back()[0].back().emplace(\"b\", RValueCaster{});\n        v.back()[0].back().emplace(\"c\", RValueCaster{});\n        v.back()[1].emplace_back(); // add a map to the array\n        v.back()[1].back().emplace(\"a\", RValueCaster{});\n        return v;\n    });\n    static std::array<RValueCaster, 2> lva;\n    static std::unordered_map<std::string, RValueCaster> lvm{{\"a\", RValueCaster{}},\n                                                             {\"b\", RValueCaster{}}};\n    static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>>\n        lvn;\n    lvn[\"a\"].emplace_back();        // add a list\n    lvn[\"a\"].back().emplace_back(); // add an array\n    lvn[\"a\"].emplace_back();        // another list\n    lvn[\"a\"].back().emplace_back(); // add an array\n    lvn[\"b\"].emplace_back();        // add a list\n    lvn[\"b\"].back().emplace_back(); // add an array\n    lvn[\"b\"].back().emplace_back(); // add another array\n    static std::vector<RValueCaster> lvv{2};\n    m.def(\"cast_lv_vector\", []() -> const decltype(lvv) & { return lvv; });\n    m.def(\"cast_lv_array\", []() -> const decltype(lva) & { return lva; });\n    m.def(\"cast_lv_map\", []() -> const decltype(lvm) & { return lvm; });\n    m.def(\"cast_lv_nested\", []() -> const decltype(lvn) & { return lvn; });\n    // #853:\n    m.def(\"cast_unique_ptr_vector\", []() {\n        std::vector<std::unique_ptr<UserType>> v;\n        v.emplace_back(new UserType{7});\n        v.emplace_back(new UserType{42});\n        return v;\n    });\n\n    pybind11::enum_<EnumType>(m, \"EnumType\")\n        .value(\"kSet\", EnumType::kSet)\n        .value(\"kUnset\", EnumType::kUnset);\n\n    // test_move_out_container\n    struct MoveOutContainer {\n        struct Value {\n            int value;\n        };\n        std::list<Value> move_list() const { return {{0}, {1}, {2}}; }\n    };\n    py::class_<MoveOutContainer::Value>(m, \"MoveOutContainerValue\")\n        .def_readonly(\"value\", &MoveOutContainer::Value::value);\n    py::class_<MoveOutContainer>(m, \"MoveOutContainer\")\n        .def(py::init<>())\n        .def_property_readonly(\"move_list\", &MoveOutContainer::move_list);\n\n    // Class that can be move- and copy-constructed, but not assigned\n    struct NoAssign {\n        int value;\n\n        explicit NoAssign(int value = 0) : value(value) {}\n        NoAssign(const NoAssign &) = default;\n        NoAssign(NoAssign &&) = default;\n\n        NoAssign &operator=(const NoAssign &) = delete;\n        NoAssign &operator=(NoAssign &&) = delete;\n    };\n    py::class_<NoAssign>(m, \"NoAssign\", \"Class with no C++ assignment operators\")\n        .def(py::init<>())\n        .def(py::init<int>());\n\n    struct MoveOutDetector {\n        MoveOutDetector() = default;\n        MoveOutDetector(const MoveOutDetector &) = default;\n        MoveOutDetector(MoveOutDetector &&other) noexcept : initialized(other.initialized) {\n            // steal underlying resource\n            other.initialized = false;\n        }\n        bool initialized = true;\n    };\n    py::class_<MoveOutDetector>(m, \"MoveOutDetector\", \"Class with move tracking\")\n        .def(py::init<>())\n        .def_readonly(\"initialized\", &MoveOutDetector::initialized);\n\n#ifdef PYBIND11_HAS_OPTIONAL\n    // test_optional\n    m.attr(\"has_optional\") = true;\n\n    using opt_int = std::optional<int>;\n    using opt_no_assign = std::optional<NoAssign>;\n    m.def(\"double_or_zero\", [](const opt_int &x) -> int { return x.value_or(0) * 2; });\n    m.def(\"half_or_none\", [](int x) -> opt_int { return x != 0 ? opt_int(x / 2) : opt_int(); });\n    m.def(\n        \"test_nullopt\",\n        [](opt_int x) { return x.value_or(42); },\n        py::arg_v(\"x\", std::nullopt, \"None\"));\n    m.def(\n        \"test_no_assign\",\n        [](const opt_no_assign &x) { return x ? x->value : 42; },\n        py::arg_v(\"x\", std::nullopt, \"None\"));\n\n    m.def(\"nodefer_none_optional\", [](std::optional<int>) { return true; });\n    m.def(\"nodefer_none_optional\", [](const py::none &) { return false; });\n\n    using opt_holder = OptionalHolder<std::optional, MoveOutDetector>;\n    py::class_<opt_holder>(m, \"OptionalHolder\", \"Class with optional member\")\n        .def(py::init<>())\n        .def_readonly(\"member\", &opt_holder::member)\n        .def(\"member_initialized\", &opt_holder::member_initialized);\n\n    using opt_props = OptionalProperties<std::optional>;\n    pybind11::class_<opt_props>(m, \"OptionalProperties\")\n        .def(pybind11::init<>())\n        .def_property_readonly(\"access_by_ref\", &opt_props::access_by_ref)\n        .def_property_readonly(\"access_by_copy\", &opt_props::access_by_copy);\n#endif\n\n#ifdef PYBIND11_HAS_EXP_OPTIONAL\n    // test_exp_optional\n    m.attr(\"has_exp_optional\") = true;\n\n    using exp_opt_int = std::experimental::optional<int>;\n    using exp_opt_no_assign = std::experimental::optional<NoAssign>;\n    m.def(\"double_or_zero_exp\", [](const exp_opt_int &x) -> int { return x.value_or(0) * 2; });\n    m.def(\"half_or_none_exp\",\n          [](int x) -> exp_opt_int { return x ? exp_opt_int(x / 2) : exp_opt_int(); });\n    m.def(\n        \"test_nullopt_exp\",\n        [](exp_opt_int x) { return x.value_or(42); },\n        py::arg_v(\"x\", std::experimental::nullopt, \"None\"));\n    m.def(\n        \"test_no_assign_exp\",\n        [](const exp_opt_no_assign &x) { return x ? x->value : 42; },\n        py::arg_v(\"x\", std::experimental::nullopt, \"None\"));\n\n    using opt_exp_holder = OptionalHolder<std::experimental::optional, MoveOutDetector>;\n    py::class_<opt_exp_holder>(m, \"OptionalExpHolder\", \"Class with optional member\")\n        .def(py::init<>())\n        .def_readonly(\"member\", &opt_exp_holder::member)\n        .def(\"member_initialized\", &opt_exp_holder::member_initialized);\n\n    using opt_exp_props = OptionalProperties<std::experimental::optional>;\n    pybind11::class_<opt_exp_props>(m, \"OptionalExpProperties\")\n        .def(pybind11::init<>())\n        .def_property_readonly(\"access_by_ref\", &opt_exp_props::access_by_ref)\n        .def_property_readonly(\"access_by_copy\", &opt_exp_props::access_by_copy);\n#endif\n\n#if defined(PYBIND11_TEST_BOOST)\n    // test_boost_optional\n    m.attr(\"has_boost_optional\") = true;\n\n    using boost_opt_int = boost::optional<int>;\n    using boost_opt_no_assign = boost::optional<NoAssign>;\n    m.def(\"double_or_zero_boost\", [](const boost_opt_int &x) -> int { return x.value_or(0) * 2; });\n    m.def(\"half_or_none_boost\",\n          [](int x) -> boost_opt_int { return x != 0 ? boost_opt_int(x / 2) : boost_opt_int(); });\n    m.def(\n        \"test_nullopt_boost\",\n        [](boost_opt_int x) { return x.value_or(42); },\n        py::arg_v(\"x\", boost::none, \"None\"));\n    m.def(\n        \"test_no_assign_boost\",\n        [](const boost_opt_no_assign &x) { return x ? x->value : 42; },\n        py::arg_v(\"x\", boost::none, \"None\"));\n\n    using opt_boost_holder = OptionalHolder<boost::optional, MoveOutDetector>;\n    py::class_<opt_boost_holder>(m, \"OptionalBoostHolder\", \"Class with optional member\")\n        .def(py::init<>())\n        .def_readonly(\"member\", &opt_boost_holder::member)\n        .def(\"member_initialized\", &opt_boost_holder::member_initialized);\n\n    using opt_boost_props = OptionalProperties<boost::optional>;\n    pybind11::class_<opt_boost_props>(m, \"OptionalBoostProperties\")\n        .def(pybind11::init<>())\n        .def_property_readonly(\"access_by_ref\", &opt_boost_props::access_by_ref)\n        .def_property_readonly(\"access_by_copy\", &opt_boost_props::access_by_copy);\n#endif\n\n    // test_refsensitive_optional\n    using refsensitive_opt_int = ReferenceSensitiveOptional<int>;\n    using refsensitive_opt_no_assign = ReferenceSensitiveOptional<NoAssign>;\n    m.def(\"double_or_zero_refsensitive\",\n          [](const refsensitive_opt_int &x) -> int { return (x ? x.value() : 0) * 2; });\n    m.def(\"half_or_none_refsensitive\", [](int x) -> refsensitive_opt_int {\n        return x != 0 ? refsensitive_opt_int(x / 2) : refsensitive_opt_int();\n    });\n    m.def(\n        \"test_nullopt_refsensitive\",\n        // NOLINTNEXTLINE(performance-unnecessary-value-param)\n        [](refsensitive_opt_int x) { return x ? x.value() : 42; },\n        py::arg_v(\"x\", refsensitive_opt_int(), \"None\"));\n    m.def(\n        \"test_no_assign_refsensitive\",\n        [](const refsensitive_opt_no_assign &x) { return x ? x->value : 42; },\n        py::arg_v(\"x\", refsensitive_opt_no_assign(), \"None\"));\n\n    using opt_refsensitive_holder = OptionalHolder<ReferenceSensitiveOptional, MoveOutDetector>;\n    py::class_<opt_refsensitive_holder>(\n        m, \"OptionalRefSensitiveHolder\", \"Class with optional member\")\n        .def(py::init<>())\n        .def_readonly(\"member\", &opt_refsensitive_holder::member)\n        .def(\"member_initialized\", &opt_refsensitive_holder::member_initialized);\n\n    using opt_refsensitive_props = OptionalProperties<ReferenceSensitiveOptional>;\n    pybind11::class_<opt_refsensitive_props>(m, \"OptionalRefSensitiveProperties\")\n        .def(pybind11::init<>())\n        .def_property_readonly(\"access_by_ref\", &opt_refsensitive_props::access_by_ref)\n        .def_property_readonly(\"access_by_copy\", &opt_refsensitive_props::access_by_copy);\n\n#ifdef PYBIND11_HAS_FILESYSTEM\n    // test_fs_path\n    m.attr(\"has_filesystem\") = true;\n    m.def(\"parent_path\", [](const std::filesystem::path &path) { return path.parent_path(); });\n    m.def(\"parent_paths\", [](const std::vector<std::filesystem::path> &paths) {\n        std::vector<std::filesystem::path> result;\n        result.reserve(paths.size());\n        for (const auto &path : paths) {\n            result.push_back(path.parent_path());\n        }\n        return result;\n    });\n    m.def(\"parent_paths_list\", [](const py::typing::List<std::filesystem::path> &paths) {\n        py::typing::List<std::filesystem::path> result;\n        for (auto path : paths) {\n            result.append(path.cast<std::filesystem::path>().parent_path());\n        }\n        return result;\n    });\n    m.def(\"parent_paths_nested_list\",\n          [](const py::typing::List<py::typing::List<std::filesystem::path>> &paths_lists) {\n              py::typing::List<py::typing::List<std::filesystem::path>> result_lists;\n              for (auto paths : paths_lists) {\n                  py::typing::List<std::filesystem::path> result;\n                  for (auto path : paths) {\n                      result.append(path.cast<std::filesystem::path>().parent_path());\n                  }\n                  result_lists.append(result);\n              }\n              return result_lists;\n          });\n    m.def(\"parent_paths_tuple\",\n          [](const py::typing::Tuple<std::filesystem::path, std::filesystem::path> &paths) {\n              py::typing::Tuple<std::filesystem::path, std::filesystem::path> result\n                  = py::make_tuple(paths[0].cast<std::filesystem::path>().parent_path(),\n                                   paths[1].cast<std::filesystem::path>().parent_path());\n              return result;\n          });\n    m.def(\"parent_paths_tuple_ellipsis\",\n          [](const py::typing::Tuple<std::filesystem::path, py::ellipsis> &paths) {\n              py::typing::Tuple<std::filesystem::path, py::ellipsis> result(paths.size());\n              for (size_t i = 0; i < paths.size(); ++i) {\n                  result[i] = paths[i].cast<std::filesystem::path>().parent_path();\n              }\n              return result;\n          });\n    m.def(\"parent_paths_dict\",\n          [](const py::typing::Dict<std::string, std::filesystem::path> &paths) {\n              py::typing::Dict<std::string, std::filesystem::path> result;\n              for (auto it : paths) {\n                  result[it.first] = it.second.cast<std::filesystem::path>().parent_path();\n              }\n              return result;\n          });\n#endif\n\n#ifdef PYBIND11_TEST_VARIANT\n    static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,\n                  \"visitor::result_type is required by boost::variant in C++11 mode\");\n\n    struct visitor {\n        using result_type = const char *;\n\n        result_type operator()(int) { return \"int\"; }\n        result_type operator()(const std::string &) { return \"std::string\"; }\n        result_type operator()(double) { return \"double\"; }\n        result_type operator()(std::nullptr_t) { return \"std::nullptr_t\"; }\n#    if defined(PYBIND11_HAS_VARIANT)\n        result_type operator()(std::monostate) { return \"std::monostate\"; }\n#    endif\n    };\n\n    // test_variant\n    m.def(\"load_variant\", [](const variant<int, std::string, double, std::nullptr_t> &v) {\n        return py::detail::visit_helper<variant>::call(visitor(), v);\n    });\n    m.def(\"load_variant_2pass\", [](variant<int, double> v) {\n        return py::detail::visit_helper<variant>::call(visitor(), v);\n    });\n    m.def(\"cast_variant\", []() {\n        using V = variant<int, std::string>;\n        return py::make_tuple(V(5), V(\"Hello\"));\n    });\n\n#    if defined(PYBIND11_HAS_VARIANT)\n    // std::monostate tests.\n    m.def(\"load_monostate_variant\",\n          [](const variant<std::monostate, int, std::string> &v) -> const char * {\n              return py::detail::visit_helper<variant>::call(visitor(), v);\n          });\n    m.def(\"cast_monostate_variant\", []() {\n        using V = variant<std::monostate, int, std::string>;\n        return py::make_tuple(V{}, V(5), V(\"Hello\"));\n    });\n#    endif\n#endif\n\n    // #528: templated constructor\n    // (no python tests: the test here is that this compiles)\n    m.def(\"tpl_ctor_vector\", [](std::vector<TplCtorClass> &) {});\n    m.def(\"tpl_ctor_map\", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});\n    m.def(\"tpl_ctor_set\", [](std::unordered_set<TplCtorClass> &) {});\n#if defined(PYBIND11_HAS_OPTIONAL)\n    m.def(\"tpl_constr_optional\", [](std::optional<TplCtorClass> &) {});\n#endif\n#if defined(PYBIND11_HAS_EXP_OPTIONAL)\n    m.def(\"tpl_constr_optional_exp\", [](std::experimental::optional<TplCtorClass> &) {});\n#endif\n#if defined(PYBIND11_TEST_BOOST)\n    m.def(\"tpl_constr_optional_boost\", [](boost::optional<TplCtorClass> &) {});\n#endif\n\n    // test_vec_of_reference_wrapper\n    // #171: Can't return STL structures containing reference wrapper\n    m.def(\"return_vec_of_reference_wrapper\", [](std::reference_wrapper<UserType> p4) {\n        static UserType p1{1}, p2{2}, p3{3};\n        return std::vector<std::reference_wrapper<UserType>>{\n            std::ref(p1), std::ref(p2), std::ref(p3), p4};\n    });\n\n    // test_stl_pass_by_pointer\n    m.def(\"stl_pass_by_pointer\", [](std::vector<int> *v) { return *v; }, \"v\"_a = nullptr);\n\n    // #1258: pybind11/stl.h converts string to vector<string>\n    m.def(\"func_with_string_or_vector_string_arg_overload\",\n          [](const std::vector<std::string> &) { return 1; });\n    m.def(\"func_with_string_or_vector_string_arg_overload\",\n          [](const std::list<std::string> &) { return 2; });\n    m.def(\"func_with_string_or_vector_string_arg_overload\", [](const std::string &) { return 3; });\n\n    class Placeholder {\n    public:\n        Placeholder() { print_created(this); }\n        Placeholder(const Placeholder &) = delete;\n        ~Placeholder() { print_destroyed(this); }\n    };\n    py::class_<Placeholder>(m, \"Placeholder\");\n\n    /// test_stl_vector_ownership\n    m.def(\n        \"test_stl_ownership\",\n        []() {\n            std::vector<Placeholder *> result;\n            result.push_back(new Placeholder());\n            return result;\n        },\n        py::return_value_policy::take_ownership);\n\n    m.def(\"array_cast_sequence\", [](std::array<int, 3> x) { return x; });\n\n    /// test_issue_1561\n    struct Issue1561Inner {\n        std::string data;\n    };\n    struct Issue1561Outer {\n        std::vector<Issue1561Inner> list;\n    };\n\n    py::class_<Issue1561Inner>(m, \"Issue1561Inner\")\n        .def(py::init<std::string>())\n        .def_readwrite(\"data\", &Issue1561Inner::data);\n\n    py::class_<Issue1561Outer>(m, \"Issue1561Outer\")\n        .def(py::init<>())\n        .def_readwrite(\"list\", &Issue1561Outer::list);\n\n    m.def(\n        \"return_vector_bool_raw_ptr\",\n        []() { return new std::vector<bool>(4513); },\n        // Without explicitly specifying `take_ownership`, this function leaks.\n        py::return_value_policy::take_ownership);\n\n    m.def(\"pass_std_vector_int\", pass_std_vector_int);\n    m.def(\"pass_std_vector_pair_int\", [](const std::vector<std::pair<int, int>> &v) {\n        int zum = 0;\n        for (const auto &ij : v) {\n            zum += ij.first * 100 + ij.second;\n        }\n        return zum;\n    });\n    m.def(\"pass_std_array_int_2\", [](const std::array<int, 2> &a) {\n        return pass_std_vector_int(std::vector<int>(a.begin(), a.end())) + 1;\n    });\n    m.def(\"pass_std_set_int\", [](const std::set<int> &s) {\n        int zum = 200;\n        for (const int i : s) {\n            zum += 3 * i;\n        }\n        return zum;\n    });\n    m.def(\"pass_std_map_int\", [](const std::map<int, int> &m) {\n        int zum = 500;\n        for (const auto &p : m) {\n            zum += p.first * 1000 + p.second;\n        }\n        return zum;\n    });\n    m.def(\"roundtrip_std_vector_int\", [](const std::vector<int> &v) { return v; });\n    m.def(\"roundtrip_std_map_str_int\", [](const std::map<std::string, int> &m) { return m; });\n    m.def(\"roundtrip_std_set_int\", [](const std::set<int> &s) { return s; });\n    m.def(\n        \"roundtrip_std_vector_int_noconvert\",\n        [](const std::vector<int> &v) { return v; },\n        py::arg(\"v\").noconvert());\n    m.def(\n        \"roundtrip_std_map_str_int_noconvert\",\n        [](const std::map<std::string, int> &m) { return m; },\n        py::arg(\"m\").noconvert());\n    m.def(\n        \"roundtrip_std_set_int_noconvert\",\n        [](const std::set<int> &s) { return s; },\n        py::arg(\"s\").noconvert());\n}\n"
  },
  {
    "path": "tests/test_stl.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nimport env  # noqa: F401\nfrom pybind11_tests import ConstructorStats, UserType\nfrom pybind11_tests import stl as m\n\n\ndef test_vector(doc):\n    \"\"\"std::vector <-> list\"\"\"\n    lst = m.cast_vector()\n    assert lst == [1]\n    lst.append(2)\n    assert m.load_vector(lst)\n    assert m.load_vector(tuple(lst))\n\n    assert m.cast_bool_vector() == [True, False]\n    assert m.load_bool_vector([True, False])\n    assert m.load_bool_vector((True, False))\n\n    assert doc(m.cast_vector) == \"cast_vector() -> list[int]\"\n    assert (\n        doc(m.load_vector)\n        == \"load_vector(arg0: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> bool\"\n    )\n\n    # Test regression caused by 936: pointers to stl containers weren't castable\n    assert m.cast_ptr_vector() == [\"lvalue\", \"lvalue\"]\n\n\ndef test_deque():\n    \"\"\"std::deque <-> list\"\"\"\n    lst = m.cast_deque()\n    assert lst == [1]\n    lst.append(2)\n    assert m.load_deque(lst)\n    assert m.load_deque(tuple(lst))\n\n\ndef test_array(doc):\n    \"\"\"std::array <-> list\"\"\"\n    lst = m.cast_array()\n    assert lst == [1, 2]\n    assert m.load_array(lst)\n    assert m.load_array(tuple(lst))\n\n    assert (\n        doc(m.cast_array)\n        == 'cast_array() -> typing.Annotated[list[int], \"FixedSize(2)\"]'\n    )\n    assert (\n        doc(m.load_array)\n        == 'load_array(arg0: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], \"FixedSize(2)\"]) -> bool'\n    )\n\n\ndef test_array_no_default_ctor():\n    lst = m.NoDefaultCtorArray(3)\n    assert [e.val for e in lst.arr] == [13, 23]\n    lst.arr = m.NoDefaultCtorArray(4).arr\n    assert [e.val for e in lst.arr] == [14, 24]\n\n\ndef test_valarray(doc):\n    \"\"\"std::valarray <-> list\"\"\"\n    lst = m.cast_valarray()\n    assert lst == [1, 4, 9]\n    assert m.load_valarray(lst)\n    assert m.load_valarray(tuple(lst))\n\n    assert doc(m.cast_valarray) == \"cast_valarray() -> list[int]\"\n    assert (\n        doc(m.load_valarray)\n        == \"load_valarray(arg0: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> bool\"\n    )\n\n\ndef test_map(doc):\n    \"\"\"std::map <-> dict\"\"\"\n    d = m.cast_map()\n    assert d == {\"key\": \"value\"}\n    assert \"key\" in d\n    d[\"key2\"] = \"value2\"\n    assert \"key2\" in d\n    assert m.load_map(d)\n\n    assert doc(m.cast_map) == \"cast_map() -> dict[str, str]\"\n    assert (\n        doc(m.load_map) == \"load_map(arg0: collections.abc.Mapping[str, str]) -> bool\"\n    )\n\n\ndef test_set(doc):\n    \"\"\"std::set <-> set\"\"\"\n    s = m.cast_set()\n    assert s == {\"key1\", \"key2\"}\n    s.add(\"key3\")\n    assert m.load_set(s)\n    assert m.load_set(frozenset(s))\n\n    assert doc(m.cast_set) == \"cast_set() -> set[str]\"\n    assert doc(m.load_set) == \"load_set(arg0: collections.abc.Set[str]) -> bool\"\n\n\ndef test_recursive_casting():\n    \"\"\"Tests that stl casters preserve lvalue/rvalue context for container values\"\"\"\n    assert m.cast_rv_vector() == [\"rvalue\", \"rvalue\"]\n    assert m.cast_lv_vector() == [\"lvalue\", \"lvalue\"]\n    assert m.cast_rv_array() == [\"rvalue\", \"rvalue\", \"rvalue\"]\n    assert m.cast_lv_array() == [\"lvalue\", \"lvalue\"]\n    assert m.cast_rv_map() == {\"a\": \"rvalue\"}\n    assert m.cast_lv_map() == {\"a\": \"lvalue\", \"b\": \"lvalue\"}\n    assert m.cast_rv_nested() == [[[{\"b\": \"rvalue\", \"c\": \"rvalue\"}], [{\"a\": \"rvalue\"}]]]\n    assert m.cast_lv_nested() == {\n        \"a\": [[[\"lvalue\", \"lvalue\"]], [[\"lvalue\", \"lvalue\"]]],\n        \"b\": [[[\"lvalue\", \"lvalue\"], [\"lvalue\", \"lvalue\"]]],\n    }\n\n    # Issue #853 test case:\n    z = m.cast_unique_ptr_vector()\n    assert z[0].value == 7\n    assert z[1].value == 42\n\n\ndef test_move_out_container():\n    \"\"\"Properties use the `reference_internal` policy by default. If the underlying function\n    returns an rvalue, the policy is automatically changed to `move` to avoid referencing\n    a temporary. In case the return value is a container of user-defined types, the policy\n    also needs to be applied to the elements, not just the container.\"\"\"\n    c = m.MoveOutContainer()\n    moved_out_list = c.move_list\n    assert [x.value for x in moved_out_list] == [0, 1, 2]\n\n\n@pytest.mark.skipif(not hasattr(m, \"has_optional\"), reason=\"no <optional>\")\ndef test_optional():\n    assert m.double_or_zero(None) == 0\n    assert m.double_or_zero(42) == 84\n    pytest.raises(TypeError, m.double_or_zero, \"foo\")\n\n    assert m.half_or_none(0) is None\n    assert m.half_or_none(42) == 21\n    pytest.raises(TypeError, m.half_or_none, \"foo\")\n\n    assert m.test_nullopt() == 42\n    assert m.test_nullopt(None) == 42\n    assert m.test_nullopt(42) == 42\n    assert m.test_nullopt(43) == 43\n\n    assert m.test_no_assign() == 42\n    assert m.test_no_assign(None) == 42\n    assert m.test_no_assign(m.NoAssign(43)) == 43\n    pytest.raises(TypeError, m.test_no_assign, 43)\n\n    assert m.nodefer_none_optional(None)\n\n    holder = m.OptionalHolder()\n    mvalue = holder.member\n    assert mvalue.initialized\n    assert holder.member_initialized()\n\n    props = m.OptionalProperties()\n    assert int(props.access_by_ref) == 42\n    assert int(props.access_by_copy) == 42\n\n\n@pytest.mark.skipif(\n    not hasattr(m, \"has_exp_optional\"), reason=\"no <experimental/optional>\"\n)\ndef test_exp_optional():\n    assert m.double_or_zero_exp(None) == 0\n    assert m.double_or_zero_exp(42) == 84\n    pytest.raises(TypeError, m.double_or_zero_exp, \"foo\")\n\n    assert m.half_or_none_exp(0) is None\n    assert m.half_or_none_exp(42) == 21\n    pytest.raises(TypeError, m.half_or_none_exp, \"foo\")\n\n    assert m.test_nullopt_exp() == 42\n    assert m.test_nullopt_exp(None) == 42\n    assert m.test_nullopt_exp(42) == 42\n    assert m.test_nullopt_exp(43) == 43\n\n    assert m.test_no_assign_exp() == 42\n    assert m.test_no_assign_exp(None) == 42\n    assert m.test_no_assign_exp(m.NoAssign(43)) == 43\n    pytest.raises(TypeError, m.test_no_assign_exp, 43)\n\n    holder = m.OptionalExpHolder()\n    mvalue = holder.member\n    assert mvalue.initialized\n    assert holder.member_initialized()\n\n    props = m.OptionalExpProperties()\n    assert int(props.access_by_ref) == 42\n    assert int(props.access_by_copy) == 42\n\n\n@pytest.mark.skipif(not hasattr(m, \"has_boost_optional\"), reason=\"no <boost/optional>\")\ndef test_boost_optional():\n    assert m.double_or_zero_boost(None) == 0\n    assert m.double_or_zero_boost(42) == 84\n    pytest.raises(TypeError, m.double_or_zero_boost, \"foo\")\n\n    assert m.half_or_none_boost(0) is None\n    assert m.half_or_none_boost(42) == 21\n    pytest.raises(TypeError, m.half_or_none_boost, \"foo\")\n\n    assert m.test_nullopt_boost() == 42\n    assert m.test_nullopt_boost(None) == 42\n    assert m.test_nullopt_boost(42) == 42\n    assert m.test_nullopt_boost(43) == 43\n\n    assert m.test_no_assign_boost() == 42\n    assert m.test_no_assign_boost(None) == 42\n    assert m.test_no_assign_boost(m.NoAssign(43)) == 43\n    pytest.raises(TypeError, m.test_no_assign_boost, 43)\n\n    holder = m.OptionalBoostHolder()\n    mvalue = holder.member\n    assert mvalue.initialized\n    assert holder.member_initialized()\n\n    props = m.OptionalBoostProperties()\n    assert int(props.access_by_ref) == 42\n    assert int(props.access_by_copy) == 42\n\n\ndef test_reference_sensitive_optional(doc):\n    assert m.double_or_zero_refsensitive(None) == 0\n    assert m.double_or_zero_refsensitive(42) == 84\n    pytest.raises(TypeError, m.double_or_zero_refsensitive, \"foo\")\n\n    assert (\n        doc(m.double_or_zero_refsensitive)\n        == \"double_or_zero_refsensitive(arg0: typing.SupportsInt | typing.SupportsIndex | None) -> int\"\n    )\n\n    assert m.half_or_none_refsensitive(0) is None\n    assert m.half_or_none_refsensitive(42) == 21\n    pytest.raises(TypeError, m.half_or_none_refsensitive, \"foo\")\n\n    assert m.test_nullopt_refsensitive() == 42\n    assert m.test_nullopt_refsensitive(None) == 42\n    assert m.test_nullopt_refsensitive(42) == 42\n    assert m.test_nullopt_refsensitive(43) == 43\n\n    assert m.test_no_assign_refsensitive() == 42\n    assert m.test_no_assign_refsensitive(None) == 42\n    assert m.test_no_assign_refsensitive(m.NoAssign(43)) == 43\n    pytest.raises(TypeError, m.test_no_assign_refsensitive, 43)\n\n    holder = m.OptionalRefSensitiveHolder()\n    mvalue = holder.member\n    assert mvalue.initialized\n    assert holder.member_initialized()\n\n    props = m.OptionalRefSensitiveProperties()\n    assert int(props.access_by_ref) == 42\n    assert int(props.access_by_copy) == 42\n\n\n@pytest.mark.skipif(not hasattr(m, \"has_filesystem\"), reason=\"no <filesystem>\")\ndef test_fs_path():\n    from pathlib import Path\n\n    class PseudoStrPath:\n        def __fspath__(self):\n            return \"foo/bar\"\n\n    class PseudoBytesPath:\n        def __fspath__(self):\n            return b\"foo/bar\"\n\n    # Single argument\n    assert m.parent_path(Path(\"foo/bar\")) == Path(\"foo\")\n    assert m.parent_path(\"foo/bar\") == Path(\"foo\")\n    assert m.parent_path(b\"foo/bar\") == Path(\"foo\")\n    assert m.parent_path(PseudoStrPath()) == Path(\"foo\")\n    assert m.parent_path(PseudoBytesPath()) == Path(\"foo\")\n    # std::vector\n    assert m.parent_paths([\"foo/bar\", \"foo/baz\"]) == [Path(\"foo\"), Path(\"foo\")]\n    # py::typing::List\n    assert m.parent_paths_list([\"foo/bar\", \"foo/baz\"]) == [Path(\"foo\"), Path(\"foo\")]\n    # Nested py::typing::List\n    assert m.parent_paths_nested_list([[\"foo/bar\"], [\"foo/baz\", \"foo/buzz\"]]) == [\n        [Path(\"foo\")],\n        [Path(\"foo\"), Path(\"foo\")],\n    ]\n    # py::typing::Tuple\n    assert m.parent_paths_tuple((\"foo/bar\", \"foo/baz\")) == (Path(\"foo\"), Path(\"foo\"))\n    # py::typing::Dict\n    assert m.parent_paths_dict(\n        {\n            \"key1\": Path(\"foo/bar\"),\n            \"key2\": \"foo/baz\",\n            \"key3\": b\"foo/buzz\",\n        }\n    ) == {\n        \"key1\": Path(\"foo\"),\n        \"key2\": Path(\"foo\"),\n        \"key3\": Path(\"foo\"),\n    }\n\n\n@pytest.mark.skipif(not hasattr(m, \"has_filesystem\"), reason=\"no <filesystem>\")\ndef test_path_typing(doc):\n    # Single argument\n    assert (\n        doc(m.parent_path)\n        == \"parent_path(arg0: os.PathLike | str | bytes) -> pathlib.Path\"\n    )\n    # std::vector\n    assert (\n        doc(m.parent_paths)\n        == \"parent_paths(arg0: collections.abc.Sequence[os.PathLike | str | bytes]) -> list[pathlib.Path]\"\n    )\n    # py::typing::List\n    assert (\n        doc(m.parent_paths_list)\n        == \"parent_paths_list(arg0: list[os.PathLike | str | bytes]) -> list[pathlib.Path]\"\n    )\n    # Nested py::typing::List\n    assert (\n        doc(m.parent_paths_nested_list)\n        == \"parent_paths_nested_list(arg0: list[list[os.PathLike | str | bytes]]) -> list[list[pathlib.Path]]\"\n    )\n    # py::typing::Tuple\n    assert (\n        doc(m.parent_paths_tuple)\n        == \"parent_paths_tuple(arg0: tuple[os.PathLike | str | bytes, os.PathLike | str | bytes]) -> tuple[pathlib.Path, pathlib.Path]\"\n    )\n    # py::typing::Dict\n    assert (\n        doc(m.parent_paths_dict)\n        == \"parent_paths_dict(arg0: dict[str, os.PathLike | str | bytes]) -> dict[str, pathlib.Path]\"\n    )\n\n\n@pytest.mark.skipif(not hasattr(m, \"load_variant\"), reason=\"no <variant>\")\ndef test_variant(doc):\n    assert m.load_variant(1) == \"int\"\n    assert m.load_variant(\"1\") == \"std::string\"\n    assert m.load_variant(1.0) == \"double\"\n    assert m.load_variant(None) == \"std::nullptr_t\"\n\n    assert m.load_variant_2pass(1) == \"int\"\n    assert m.load_variant_2pass(1.0) == \"double\"\n\n    assert m.cast_variant() == (5, \"Hello\")\n\n    assert (\n        doc(m.load_variant)\n        == \"load_variant(arg0: typing.SupportsInt | typing.SupportsIndex | str | typing.SupportsFloat | typing.SupportsIndex | None) -> str\"\n    )\n\n\n@pytest.mark.skipif(\n    not hasattr(m, \"load_monostate_variant\"), reason=\"no std::monostate\"\n)\ndef test_variant_monostate(doc):\n    assert m.load_monostate_variant(None) == \"std::monostate\"\n    assert m.load_monostate_variant(1) == \"int\"\n    assert m.load_monostate_variant(\"1\") == \"std::string\"\n\n    assert m.cast_monostate_variant() == (None, 5, \"Hello\")\n\n    assert (\n        doc(m.load_monostate_variant)\n        == \"load_monostate_variant(arg0: None | typing.SupportsInt | typing.SupportsIndex | str) -> str\"\n    )\n\n\ndef test_vec_of_reference_wrapper():\n    \"\"\"#171: Can't return reference wrappers (or STL structures containing them)\"\"\"\n    assert (\n        str(m.return_vec_of_reference_wrapper(UserType(4)))\n        == \"[UserType(1), UserType(2), UserType(3), UserType(4)]\"\n    )\n\n\ndef test_stl_pass_by_pointer(msg):\n    \"\"\"Passing nullptr or None to an STL container pointer is not expected to work\"\"\"\n    with pytest.raises(TypeError) as excinfo:\n        m.stl_pass_by_pointer()  # default value is `nullptr`\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:\n            1. (v: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = None) -> list[int]\n\n        Invoked with:\n    \"\"\"\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        m.stl_pass_by_pointer(None)\n    assert (\n        msg(excinfo.value)\n        == \"\"\"\n        stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported:\n            1. (v: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex] = None) -> list[int]\n\n        Invoked with: None\n    \"\"\"\n    )\n\n    assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]\n\n\ndef test_missing_header_message():\n    \"\"\"Trying convert `list` to a `std::vector`, or vice versa, without including\n    <pybind11/stl.h> should result in a helpful suggestion in the error message\"\"\"\n    import pybind11_cross_module_tests as cm\n\n    expected_message = (\n        \"Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\\n\"\n        \"<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\\n\"\n        \"conversions are optional and require extra headers to be included\\n\"\n        \"when compiling your pybind11 module.\"\n    )\n\n    with pytest.raises(TypeError) as excinfo:\n        cm.missing_header_arg([1.0, 2.0, 3.0])\n    assert expected_message in str(excinfo.value)\n\n    with pytest.raises(TypeError) as excinfo:\n        cm.missing_header_return()\n    assert expected_message in str(excinfo.value)\n\n\ndef test_function_with_string_and_vector_string_arg():\n    \"\"\"Check if a string is NOT implicitly converted to a list, which was the\n    behavior before fix of issue #1258\"\"\"\n    assert m.func_with_string_or_vector_string_arg_overload((\"A\", \"B\")) == 2\n    assert m.func_with_string_or_vector_string_arg_overload([\"A\", \"B\"]) == 2\n    assert m.func_with_string_or_vector_string_arg_overload(\"A\") == 3\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_stl_ownership():\n    cstats = ConstructorStats.get(m.Placeholder)\n    assert cstats.alive() == 0\n    r = m.test_stl_ownership()\n    assert len(r) == 1\n    del r\n    assert cstats.alive() == 0\n\n\ndef test_array_cast_sequence():\n    assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3]\n\n\ndef test_issue_1561():\n    \"\"\"check fix for issue #1561\"\"\"\n    bar = m.Issue1561Outer()\n    bar.list = [m.Issue1561Inner(\"bar\")]\n    assert bar.list\n    assert bar.list[0].data == \"bar\"\n\n\ndef test_return_vector_bool_raw_ptr():\n    # Add `while True:` for manual leak checking.\n    v = m.return_vector_bool_raw_ptr()\n    assert isinstance(v, list)\n    assert len(v) == 4513\n\n\n@pytest.mark.parametrize(\n    (\"fn\", \"offset\"), [(m.pass_std_vector_int, 0), (m.pass_std_array_int_2, 1)]\n)\ndef test_pass_std_vector_int(fn, offset):\n    assert fn([7, 13]) == 140 + offset\n    assert fn({6, 2}) == 116 + offset\n    assert fn({\"x\": 8, \"y\": 11}.values()) == 138 + offset\n    assert fn({3: None, 9: None}.keys()) == 124 + offset\n    assert fn(i for i in [4, 17]) == 142 + offset\n    assert fn(map(lambda i: i * 3, [8, 7])) == 190 + offset  # noqa: C417\n    with pytest.raises(TypeError):\n        fn({\"x\": 0, \"y\": 1})\n    with pytest.raises(TypeError):\n        fn({})\n\n\ndef test_pass_std_vector_pair_int():\n    fn = m.pass_std_vector_pair_int\n    assert fn({1: 2, 3: 4}.items()) == 406\n    assert fn(zip([5, 17], [13, 9])) == 2222\n\n\ndef test_list_caster_fully_consumes_generator_object():\n    def gen_invalid():\n        yield from [1, 2.0, 3]\n\n    gen_obj = gen_invalid()\n    with pytest.raises(TypeError):\n        m.pass_std_vector_int(gen_obj)\n    assert not tuple(gen_obj)\n\n\ndef test_pass_std_set_int():\n    fn = m.pass_std_set_int\n    assert fn({3, 15}) == 254\n    assert fn({5: None, 12: None}.keys()) == 251\n    with pytest.raises(TypeError):\n        fn([])\n    with pytest.raises(TypeError):\n        fn({})\n    with pytest.raises(TypeError):\n        fn({}.values())\n    with pytest.raises(TypeError):\n        fn(i for i in [])\n\n\ndef test_set_caster_dict_keys_failure():\n    dict_keys = {1: None, 2.0: None, 3: None}.keys()\n    # The asserts does not really exercise anything in pybind11, but if one of\n    # them fails in some future version of Python, the set_caster load\n    # implementation may need to be revisited.\n    assert tuple(dict_keys) == (1, 2.0, 3)\n    assert tuple(dict_keys) == (1, 2.0, 3)\n    with pytest.raises(TypeError):\n        m.pass_std_set_int(dict_keys)\n    assert tuple(dict_keys) == (1, 2.0, 3)\n\n\nclass FakePyMappingMissingItems:\n    def __getitem__(self, _):\n        raise RuntimeError(\"Not expected to be called.\")\n\n\nclass FakePyMappingWithItems(FakePyMappingMissingItems):\n    def items(self):\n        return ((1, 3), (2, 4))\n\n\nclass FakePyMappingBadItems(FakePyMappingMissingItems):\n    def items(self):\n        return ((1, 2), (3, \"x\"))\n\n\nclass FakePyMappingItemsNotCallable(FakePyMappingMissingItems):\n    @property\n    def items(self):\n        return ((1, 2), (3, 4))\n\n\nclass FakePyMappingItemsWithArg(FakePyMappingMissingItems):\n    def items(self, _):\n        return ((1, 2), (3, 4))\n\n\nclass FakePyMappingGenObj(FakePyMappingMissingItems):\n    def __init__(self, gen_obj):\n        super().__init__()\n        self.gen_obj = gen_obj\n\n    def items(self):\n        yield from self.gen_obj\n\n\ndef test_pass_std_map_int():\n    fn = m.pass_std_map_int\n    assert fn({1: 2, 3: 4}) == 4506\n    with pytest.raises(TypeError):\n        fn([])\n    assert fn(FakePyMappingWithItems()) == 3507\n    with pytest.raises(TypeError):\n        fn(FakePyMappingMissingItems())\n    with pytest.raises(TypeError):\n        fn(FakePyMappingBadItems())\n    with pytest.raises(TypeError):\n        fn(FakePyMappingItemsNotCallable())\n    with pytest.raises(TypeError):\n        fn(FakePyMappingItemsWithArg())\n\n\n@pytest.mark.parametrize(\n    (\"items\", \"expected_exception\"),\n    [\n        (((1, 2), (3, \"x\"), (4, 5)), TypeError),\n        (((1, 2), (3, 4, 5), (6, 7)), ValueError),\n    ],\n)\ndef test_map_caster_fully_consumes_generator_object(items, expected_exception):\n    def gen_invalid():\n        yield from items\n\n    gen_obj = gen_invalid()\n    with pytest.raises(expected_exception):\n        m.pass_std_map_int(FakePyMappingGenObj(gen_obj))\n    assert not tuple(gen_obj)\n\n\ndef test_sequence_caster_protocol(doc):\n    from collections.abc import Sequence\n\n    # Implements the Sequence protocol without explicitly inheriting from collections.abc.Sequence.\n    class BareSequenceLike:\n        def __init__(self, *args):\n            self.data = tuple(args)\n\n        def __len__(self):\n            return len(self.data)\n\n        def __getitem__(self, index):\n            return self.data[index]\n\n    # Implements the Sequence protocol by reusing BareSequenceLike's implementation.\n    # Additionally, inherits from collections.abc.Sequence.\n    class FormalSequenceLike(BareSequenceLike, Sequence):\n        pass\n\n    # convert mode\n    assert (\n        doc(m.roundtrip_std_vector_int)\n        == \"roundtrip_std_vector_int(arg0: collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex]) -> list[int]\"\n    )\n    assert m.roundtrip_std_vector_int([1, 2, 3]) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int((1, 2, 3)) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int(FormalSequenceLike(1, 2, 3)) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int(BareSequenceLike(1, 2, 3)) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int([]) == []\n    assert m.roundtrip_std_vector_int(()) == []\n    assert m.roundtrip_std_vector_int(BareSequenceLike()) == []\n    # noconvert mode\n    assert (\n        doc(m.roundtrip_std_vector_int_noconvert)\n        == \"roundtrip_std_vector_int_noconvert(v: list[int]) -> list[int]\"\n    )\n    assert m.roundtrip_std_vector_int_noconvert([1, 2, 3]) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int_noconvert((1, 2, 3)) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int_noconvert(FormalSequenceLike(1, 2, 3)) == [\n        1,\n        2,\n        3,\n    ]\n    assert m.roundtrip_std_vector_int_noconvert(BareSequenceLike(1, 2, 3)) == [1, 2, 3]\n    assert m.roundtrip_std_vector_int_noconvert([]) == []\n    assert m.roundtrip_std_vector_int_noconvert(()) == []\n    assert m.roundtrip_std_vector_int_noconvert(BareSequenceLike()) == []\n\n\ndef test_mapping_caster_protocol(doc):\n    from collections.abc import Mapping\n\n    # Implements the Mapping protocol without explicitly inheriting from collections.abc.Mapping.\n    class BareMappingLike:\n        def __init__(self, **kwargs):\n            self.data = dict(kwargs)\n\n        def __len__(self):\n            return len(self.data)\n\n        def __getitem__(self, key):\n            return self.data[key]\n\n        def __iter__(self):\n            yield from self.data\n\n    # Implements the Mapping protocol by reusing BareMappingLike's implementation.\n    # Additionally, inherits from collections.abc.Mapping.\n    class FormalMappingLike(BareMappingLike, Mapping):\n        pass\n\n    a1b2c3 = {\"a\": 1, \"b\": 2, \"c\": 3}\n    # convert mode\n    assert (\n        doc(m.roundtrip_std_map_str_int)\n        == \"roundtrip_std_map_str_int(arg0: collections.abc.Mapping[str, typing.SupportsInt | typing.SupportsIndex]) -> dict[str, int]\"\n    )\n    assert m.roundtrip_std_map_str_int(a1b2c3) == a1b2c3\n    assert m.roundtrip_std_map_str_int(FormalMappingLike(**a1b2c3)) == a1b2c3\n    assert m.roundtrip_std_map_str_int({}) == {}\n    assert m.roundtrip_std_map_str_int(FormalMappingLike()) == {}\n    with pytest.raises(TypeError):\n        m.roundtrip_std_map_str_int(BareMappingLike(**a1b2c3))\n    # noconvert mode\n    assert (\n        doc(m.roundtrip_std_map_str_int_noconvert)\n        == \"roundtrip_std_map_str_int_noconvert(m: dict[str, int]) -> dict[str, int]\"\n    )\n    assert m.roundtrip_std_map_str_int_noconvert(a1b2c3) == a1b2c3\n    assert m.roundtrip_std_map_str_int_noconvert({}) == {}\n    with pytest.raises(TypeError):\n        m.roundtrip_std_map_str_int_noconvert(FormalMappingLike(**a1b2c3))\n    with pytest.raises(TypeError):\n        m.roundtrip_std_map_str_int_noconvert(BareMappingLike(**a1b2c3))\n\n\ndef test_set_caster_protocol(doc):\n    from collections.abc import Set\n\n    # Implements the Set protocol without explicitly inheriting from collections.abc.Set.\n    class BareSetLike:\n        def __init__(self, *args):\n            self.data = set(args)\n\n        def __len__(self):\n            return len(self.data)\n\n        def __contains__(self, item):\n            return item in self.data\n\n        def __iter__(self):\n            yield from self.data\n\n    # Implements the Set protocol by reusing BareSetLike's implementation.\n    # Additionally, inherits from collections.abc.Set.\n    class FormalSetLike(BareSetLike, Set):\n        pass\n\n    # convert mode\n    assert (\n        doc(m.roundtrip_std_set_int)\n        == \"roundtrip_std_set_int(arg0: collections.abc.Set[typing.SupportsInt | typing.SupportsIndex]) -> set[int]\"\n    )\n    assert m.roundtrip_std_set_int({1, 2, 3}) == {1, 2, 3}\n    assert m.roundtrip_std_set_int(FormalSetLike(1, 2, 3)) == {1, 2, 3}\n    assert m.roundtrip_std_set_int(set()) == set()\n    assert m.roundtrip_std_set_int(FormalSetLike()) == set()\n    with pytest.raises(TypeError):\n        m.roundtrip_std_set_int(BareSetLike(1, 2, 3))\n    # noconvert mode\n    assert (\n        doc(m.roundtrip_std_set_int_noconvert)\n        == \"roundtrip_std_set_int_noconvert(s: set[int]) -> set[int]\"\n    )\n    assert m.roundtrip_std_set_int_noconvert({1, 2, 3}) == {1, 2, 3}\n    assert m.roundtrip_std_set_int_noconvert(set()) == set()\n    with pytest.raises(TypeError):\n        m.roundtrip_std_set_int_noconvert(FormalSetLike(1, 2, 3))\n    with pytest.raises(TypeError):\n        m.roundtrip_std_set_int_noconvert(BareSetLike(1, 2, 3))\n"
  },
  {
    "path": "tests/test_stl_binders.cpp",
    "content": "/*\n    tests/test_stl_binders.cpp -- Usage of stl_binders functions\n\n    Copyright (c) 2016 Sergey Lyskov\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/numpy.h>\n#include <pybind11/stl_bind.h>\n\n#include \"pybind11_tests.h\"\n\n#include <deque>\n#include <map>\n#include <unordered_map>\n#include <vector>\n\nclass El {\npublic:\n    El() = delete;\n    explicit El(int v) : a(v) {}\n\n    int a;\n};\n\nstd::ostream &operator<<(std::ostream &s, El const &v) {\n    s << \"El{\" << v.a << '}';\n    return s;\n}\n\n/// Issue #487: binding std::vector<E> with E non-copyable\nclass E_nc {\npublic:\n    explicit E_nc(int i) : value{i} {}\n    E_nc(const E_nc &) = delete;\n    E_nc &operator=(const E_nc &) = delete;\n    E_nc(E_nc &&) = default;\n    E_nc &operator=(E_nc &&) = default;\n\n    int value;\n};\n\ntemplate <class Container>\nContainer *one_to_n(int n) {\n    auto *v = new Container();\n    for (int i = 1; i <= n; i++) {\n        v->emplace_back(i);\n    }\n    return v;\n}\n\ntemplate <class Map>\nMap *times_ten(int n) {\n    auto *m = new Map();\n    for (int i = 1; i <= n; i++) {\n        m->emplace(i, E_nc(10 * i));\n    }\n    return m;\n}\n\ntemplate <class NestMap>\nNestMap *times_hundred(int n) {\n    auto *m = new NestMap();\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= n; j++) {\n            (*m)[i].emplace(j * 10, E_nc(100 * j));\n        }\n    }\n    return m;\n}\n\n/*\n * Recursive data structures as test for issue #4623\n */\nstruct RecursiveVector : std::vector<RecursiveVector> {\n    using Parent = std::vector<RecursiveVector>;\n    using Parent::Parent;\n};\n\nstruct RecursiveMap : std::map<int, RecursiveMap> {\n    using Parent = std::map<int, RecursiveMap>;\n    using Parent::Parent;\n};\n\nclass UserVectorLike : private std::vector<int> {\npublic:\n    // This is only a subset of the member functions, as needed at the time.\n    using Base = std::vector<int>;\n    using typename Base::const_iterator;\n    using typename Base::difference_type;\n    using typename Base::iterator;\n    using typename Base::size_type;\n    using typename Base::value_type;\n\n    using Base::at;\n    using Base::back;\n    using Base::Base;\n    using Base::begin;\n    using Base::cbegin;\n    using Base::cend;\n    using Base::clear;\n    using Base::empty;\n    using Base::end;\n    using Base::erase;\n    using Base::front;\n    using Base::insert;\n    using Base::pop_back;\n    using Base::push_back;\n    using Base::reserve;\n    using Base::shrink_to_fit;\n    using Base::swap;\n    using Base::operator[];\n    using Base::capacity;\n    using Base::size;\n};\n\nbool operator==(UserVectorLike const &, UserVectorLike const &) { return true; }\nbool operator!=(UserVectorLike const &, UserVectorLike const &) { return false; }\n\nclass UserMapLike : private std::map<int, int> {\npublic:\n    // This is only a subset of the member functions, as needed at the time.\n    using Base = std::map<int, int>;\n    using typename Base::const_iterator;\n    using typename Base::iterator;\n    using typename Base::key_type;\n    using typename Base::mapped_type;\n    using typename Base::size_type;\n    using typename Base::value_type;\n\n    using Base::at;\n    using Base::Base;\n    using Base::begin;\n    using Base::cbegin;\n    using Base::cend;\n    using Base::clear;\n    using Base::emplace;\n    using Base::emplace_hint;\n    using Base::empty;\n    using Base::end;\n    using Base::erase;\n    using Base::find;\n    using Base::insert;\n    using Base::max_size;\n    using Base::swap;\n    using Base::operator[];\n    using Base::size;\n};\n\n/*\n * Pybind11 does not catch more complicated recursion schemes, such as mutual\n * recursion.\n * In that case custom recursive_container_traits specializations need to be added,\n * thus manually telling pybind11 about the recursion.\n */\nstruct MutuallyRecursiveContainerPairMV;\nstruct MutuallyRecursiveContainerPairVM;\n\nstruct MutuallyRecursiveContainerPairMV : std::map<int, MutuallyRecursiveContainerPairVM> {};\nstruct MutuallyRecursiveContainerPairVM : std::vector<MutuallyRecursiveContainerPairMV> {};\n\nnamespace pybind11 {\nnamespace detail {\ntemplate <typename SFINAE>\nstruct recursive_container_traits<MutuallyRecursiveContainerPairMV, SFINAE> {\n    using type_to_check_recursively = recursive_bottom;\n};\ntemplate <typename SFINAE>\nstruct recursive_container_traits<MutuallyRecursiveContainerPairVM, SFINAE> {\n    using type_to_check_recursively = recursive_bottom;\n};\n} // namespace detail\n} // namespace pybind11\n\nTEST_SUBMODULE(stl_binders, m) {\n    // test_vector_int\n    py::bind_vector<std::vector<unsigned int>>(m, \"VectorInt\", py::buffer_protocol());\n\n    // test_vector_custom\n    py::class_<El>(m, \"El\").def(py::init<int>());\n    py::bind_vector<std::vector<El>>(m, \"VectorEl\");\n    py::bind_vector<std::vector<std::vector<El>>>(m, \"VectorVectorEl\");\n\n    // test_map_string_double\n    py::bind_map<std::map<std::string, double>>(m, \"MapStringDouble\");\n    py::bind_map<std::unordered_map<std::string, double>>(m, \"UnorderedMapStringDouble\");\n\n    // test_map_string_double_const\n    py::bind_map<std::map<std::string, double const>>(m, \"MapStringDoubleConst\");\n    py::bind_map<std::unordered_map<std::string, double const>>(m,\n                                                                \"UnorderedMapStringDoubleConst\");\n\n    // test_map_view_types\n    py::bind_map<std::map<std::string, float>>(m, \"MapStringFloat\");\n    py::bind_map<std::unordered_map<std::string, float>>(m, \"UnorderedMapStringFloat\");\n\n    py::bind_map<std::map<std::pair<double, int>, int32_t>>(m, \"MapPairDoubleIntInt32\");\n    py::bind_map<std::map<std::pair<double, int>, int64_t>>(m, \"MapPairDoubleIntInt64\");\n\n    py::bind_map<std::map<int, py::object>>(m, \"MapIntObject\");\n    py::bind_map<std::map<std::string, py::object>>(m, \"MapStringObject\");\n\n    py::class_<E_nc>(m, \"ENC\").def(py::init<int>()).def_readwrite(\"value\", &E_nc::value);\n\n    // test_noncopyable_containers\n    py::bind_vector<std::vector<E_nc>>(m, \"VectorENC\");\n    m.def(\"get_vnc\", &one_to_n<std::vector<E_nc>>);\n    py::bind_vector<std::deque<E_nc>>(m, \"DequeENC\");\n    m.def(\"get_dnc\", &one_to_n<std::deque<E_nc>>);\n    py::bind_map<std::map<int, E_nc>>(m, \"MapENC\");\n    m.def(\"get_mnc\", &times_ten<std::map<int, E_nc>>);\n    py::bind_map<std::unordered_map<int, E_nc>>(m, \"UmapENC\");\n    m.def(\"get_umnc\", &times_ten<std::unordered_map<int, E_nc>>);\n    // Issue #1885: binding nested std::map<X, Container<E>> with E non-copyable\n    py::bind_map<std::map<int, std::vector<E_nc>>>(m, \"MapVecENC\");\n    m.def(\"get_nvnc\", [](int n) {\n        auto *m = new std::map<int, std::vector<E_nc>>();\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= n; j++) {\n                (*m)[i].emplace_back(j);\n            }\n        }\n        return m;\n    });\n    py::bind_map<std::map<int, std::map<int, E_nc>>>(m, \"MapMapENC\");\n    m.def(\"get_nmnc\", &times_hundred<std::map<int, std::map<int, E_nc>>>);\n    py::bind_map<std::unordered_map<int, std::unordered_map<int, E_nc>>>(m, \"UmapUmapENC\");\n    m.def(\"get_numnc\", &times_hundred<std::unordered_map<int, std::unordered_map<int, E_nc>>>);\n\n    // test_vector_buffer\n    py::bind_vector<std::vector<unsigned char>>(m, \"VectorUChar\", py::buffer_protocol());\n    // no dtype declared for this version:\n    struct VUndeclStruct {\n        bool w;\n        uint32_t x;\n        double y;\n        bool z;\n    };\n    m.def(\"create_undeclstruct\", [m]() mutable {\n        py::bind_vector<std::vector<VUndeclStruct>>(\n            m, \"VectorUndeclStruct\", py::buffer_protocol());\n    });\n\n    // Bind recursive container types\n    py::bind_vector<RecursiveVector>(m, \"RecursiveVector\");\n    py::bind_map<RecursiveMap>(m, \"RecursiveMap\");\n    py::bind_map<MutuallyRecursiveContainerPairMV>(m, \"MutuallyRecursiveContainerPairMV\");\n    py::bind_vector<MutuallyRecursiveContainerPairVM>(m, \"MutuallyRecursiveContainerPairVM\");\n\n    // Bind with private inheritance + `using` directives.\n    py::bind_vector<UserVectorLike>(m, \"UserVectorLike\");\n    py::bind_map<UserMapLike>(m, \"UserMapLike\");\n\n    // The rest depends on numpy:\n    try {\n        py::module_::import(\"numpy\");\n    } catch (...) {\n        return;\n    }\n\n    // test_vector_buffer_numpy\n    struct VStruct {\n        bool w;\n        uint32_t x;\n        double y;\n        bool z;\n    };\n    PYBIND11_NUMPY_DTYPE(VStruct, w, x, y, z);\n    py::class_<VStruct>(m, \"VStruct\").def_readwrite(\"x\", &VStruct::x);\n    py::bind_vector<std::vector<VStruct>>(m, \"VectorStruct\", py::buffer_protocol());\n    m.def(\"get_vectorstruct\",\n          [] { return std::vector<VStruct>{{false, 5, 3.0, true}, {true, 30, -1e4, false}}; });\n}\n"
  },
  {
    "path": "tests/test_stl_binders.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import stl_binders as m\n\n\ndef test_vector_int():\n    v_int = m.VectorInt([0, 0])\n    assert len(v_int) == 2\n    assert bool(v_int) is True\n\n    # test construction from a generator\n    v_int1 = m.VectorInt(x for x in range(5))\n    assert v_int1 == m.VectorInt([0, 1, 2, 3, 4])\n\n    v_int2 = m.VectorInt([0, 0])\n    assert v_int == v_int2\n    v_int2[1] = 1\n    assert v_int != v_int2\n\n    v_int2.append(2)\n    v_int2.insert(0, 1)\n    v_int2.insert(0, 2)\n    v_int2.insert(0, 3)\n    v_int2.insert(6, 3)\n    assert str(v_int2) == \"VectorInt[3, 2, 1, 0, 1, 2, 3]\"\n    with pytest.raises(IndexError):\n        v_int2.insert(8, 4)\n\n    v_int.append(99)\n    v_int2[2:-2] = v_int\n    assert v_int2 == m.VectorInt([3, 2, 0, 0, 99, 2, 3])\n    del v_int2[1:3]\n    assert v_int2 == m.VectorInt([3, 0, 99, 2, 3])\n    del v_int2[0]\n    assert v_int2 == m.VectorInt([0, 99, 2, 3])\n\n    v_int2.extend(m.VectorInt([4, 5]))\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5])\n\n    v_int2.extend([6, 7])\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7])\n\n    # test error handling, and that the vector is unchanged\n    with pytest.raises(RuntimeError):\n        v_int2.extend([8, \"a\"])\n\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7])\n\n    # test extending from a generator\n    v_int2.extend(x for x in range(5))\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4])\n\n    # test negative indexing\n    assert v_int2[-1] == 4\n\n    # insert with negative index\n    v_int2.insert(-1, 88)\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88, 4])\n\n    # delete negative index\n    del v_int2[-1]\n    assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88])\n\n    v_int2.clear()\n    assert len(v_int2) == 0\n\n\n# Older PyPy's failed here, related to the PyPy's buffer protocol.\ndef test_vector_buffer():\n    b = bytearray([1, 2, 3, 4])\n    v = m.VectorUChar(b)\n    assert v[1] == 2\n    v[2] = 5\n    mv = memoryview(v)  # We expose the buffer interface\n    assert mv[2] == 5\n    mv[2] = 6\n    assert v[2] == 6\n\n    mv = memoryview(b)\n    v = m.VectorUChar(mv[::2])\n    assert v[1] == 3\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.create_undeclstruct()  # Undeclared struct contents, no buffer interface\n    assert \"NumPy type info missing for \" in str(excinfo.value)\n\n\ndef test_vector_buffer_numpy():\n    np = pytest.importorskip(\"numpy\")\n    a = np.array([1, 2, 3, 4], dtype=np.int32)\n    with pytest.raises(TypeError):\n        m.VectorInt(a)\n\n    a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.uintc)\n    v = m.VectorInt(a[0, :])\n    assert len(v) == 4\n    assert v[2] == 3\n    ma = np.asarray(v)\n    ma[2] = 5\n    assert v[2] == 5\n\n    v = m.VectorInt(a[:, 1])\n    assert len(v) == 3\n    assert v[2] == 10\n\n    v = m.get_vectorstruct()\n    assert v[0].x == 5\n    ma = np.asarray(v)\n    ma[1][\"x\"] = 99\n    assert v[1].x == 99\n\n    v = m.VectorStruct(\n        np.zeros(\n            3,\n            dtype=np.dtype(\n                [(\"w\", \"bool\"), (\"x\", \"I\"), (\"y\", \"float64\"), (\"z\", \"bool\")], align=True\n            ),\n        )\n    )\n    assert len(v) == 3\n\n    b = np.array([1, 2, 3, 4], dtype=np.uint8)\n    v = m.VectorUChar(b[::2])\n    assert v[1] == 3\n\n\ndef test_vector_bool():\n    import pybind11_cross_module_tests as cm\n\n    vv_c = cm.VectorBool()\n    for i in range(10):\n        vv_c.append(i % 2 == 0)\n    for i in range(10):\n        assert vv_c[i] == (i % 2 == 0)\n    assert str(vv_c) == \"VectorBool[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\"\n\n\ndef test_vector_custom():\n    v_a = m.VectorEl()\n    v_a.append(m.El(1))\n    v_a.append(m.El(2))\n    assert str(v_a) == \"VectorEl[El{1}, El{2}]\"\n\n    vv_a = m.VectorVectorEl()\n    vv_a.append(v_a)\n    vv_b = vv_a[0]\n    assert str(vv_b) == \"VectorEl[El{1}, El{2}]\"\n\n\ndef test_map_string_double():\n    mm = m.MapStringDouble()\n    mm[\"a\"] = 1\n    mm[\"b\"] = 2.5\n\n    assert list(mm) == [\"a\", \"b\"]\n    assert str(mm) == \"MapStringDouble{a: 1, b: 2.5}\"\n    assert \"b\" in mm\n    assert \"c\" not in mm\n    assert 123 not in mm\n\n    # Check that keys, values, items are views, not merely iterable\n    keys = mm.keys()\n    values = mm.values()\n    items = mm.items()\n    assert list(keys) == [\"a\", \"b\"]\n    assert len(keys) == 2\n    assert \"a\" in keys\n    assert \"c\" not in keys\n    assert 123 not in keys\n    assert list(items) == [(\"a\", 1), (\"b\", 2.5)]\n    assert len(items) == 2\n    assert (\"b\", 2.5) in items\n    assert \"hello\" not in items\n    assert (\"b\", 2.5, None) not in items\n    assert list(values) == [1, 2.5]\n    assert len(values) == 2\n    assert 1 in values\n    assert 2 not in values\n    # Check that views update when the map is updated\n    mm[\"c\"] = -1\n    assert list(keys) == [\"a\", \"b\", \"c\"]\n    assert list(values) == [1, 2.5, -1]\n    assert list(items) == [(\"a\", 1), (\"b\", 2.5), (\"c\", -1)]\n\n    um = m.UnorderedMapStringDouble()\n    um[\"ua\"] = 1.1\n    um[\"ub\"] = 2.6\n\n    assert sorted(um) == [\"ua\", \"ub\"]\n    assert list(um.keys()) == list(um)\n    assert sorted(um.items()) == [(\"ua\", 1.1), (\"ub\", 2.6)]\n    assert list(zip(um.keys(), um.values())) == list(um.items())\n    assert \"UnorderedMapStringDouble\" in str(um)\n\n\ndef test_map_string_double_const():\n    mc = m.MapStringDoubleConst()\n    mc[\"a\"] = 10\n    mc[\"b\"] = 20.5\n    assert str(mc) == \"MapStringDoubleConst{a: 10, b: 20.5}\"\n\n    umc = m.UnorderedMapStringDoubleConst()\n    umc[\"a\"] = 11\n    umc[\"b\"] = 21.5\n\n    str(umc)\n\n\ndef test_noncopyable_containers():\n    # std::vector\n    vnc = m.get_vnc(5)\n    for i in range(5):\n        assert vnc[i].value == i + 1\n\n    for i, j in enumerate(vnc, start=1):\n        assert j.value == i\n\n    # std::deque\n    dnc = m.get_dnc(5)\n    for i in range(5):\n        assert dnc[i].value == i + 1\n\n    i = 1\n    for j in dnc:\n        assert j.value == i\n        i += 1\n\n    # std::map\n    mnc = m.get_mnc(5)\n    for i in range(1, 6):\n        assert mnc[i].value == 10 * i\n\n    vsum = 0\n    for k, v in mnc.items():\n        assert v.value == 10 * k\n        vsum += v.value\n\n    assert vsum == 150\n\n    # std::unordered_map\n    mnc = m.get_umnc(5)\n    for i in range(1, 6):\n        assert mnc[i].value == 10 * i\n\n    vsum = 0\n    for k, v in mnc.items():\n        assert v.value == 10 * k\n        vsum += v.value\n\n    assert vsum == 150\n\n    # nested std::map<std::vector>\n    nvnc = m.get_nvnc(5)\n    for i in range(1, 6):\n        for j in range(5):\n            assert nvnc[i][j].value == j + 1\n\n    # Note: maps do not have .values()\n    for v in nvnc.values():\n        for i, j in enumerate(v, start=1):\n            assert j.value == i\n\n    # nested std::map<std::map>\n    nmnc = m.get_nmnc(5)\n    for i in range(1, 6):\n        for j in range(10, 60, 10):\n            assert nmnc[i][j].value == 10 * j\n\n    vsum = 0\n    for v_o in nmnc.values():\n        for k_i, v_i in v_o.items():\n            assert v_i.value == 10 * k_i\n            vsum += v_i.value\n\n    assert vsum == 7500\n\n    # nested std::unordered_map<std::unordered_map>\n    numnc = m.get_numnc(5)\n    for i in range(1, 6):\n        for j in range(10, 60, 10):\n            assert numnc[i][j].value == 10 * j\n\n    vsum = 0\n    for v_o in numnc.values():\n        for k_i, v_i in v_o.items():\n            assert v_i.value == 10 * k_i\n            vsum += v_i.value\n\n    assert vsum == 7500\n\n\ndef test_map_delitem():\n    mm = m.MapStringDouble()\n    mm[\"a\"] = 1\n    mm[\"b\"] = 2.5\n\n    assert list(mm) == [\"a\", \"b\"]\n    assert list(mm.items()) == [(\"a\", 1), (\"b\", 2.5)]\n    del mm[\"a\"]\n    assert list(mm) == [\"b\"]\n    assert list(mm.items()) == [(\"b\", 2.5)]\n\n    with pytest.raises(KeyError) as excinfo:\n        mm[\"a_long_key\"]\n    assert \"a_long_key\" in str(excinfo.value)\n\n    with pytest.raises(KeyError) as excinfo:\n        del mm[\"a_long_key\"]\n    assert \"a_long_key\" in str(excinfo.value)\n\n    cut_length = 100\n    k_very_long = \"ab\" * cut_length + \"xyz\"\n    with pytest.raises(KeyError) as excinfo:\n        mm[k_very_long]\n    assert k_very_long in str(excinfo.value)\n    k_very_long += \"@\"\n    with pytest.raises(KeyError) as excinfo:\n        mm[k_very_long]\n    k_repr = k_very_long[:cut_length] + \"✄✄✄\" + k_very_long[-cut_length:]\n    assert k_repr in str(excinfo.value)\n\n    um = m.UnorderedMapStringDouble()\n    um[\"ua\"] = 1.1\n    um[\"ub\"] = 2.6\n\n    assert sorted(um) == [\"ua\", \"ub\"]\n    assert sorted(um.items()) == [(\"ua\", 1.1), (\"ub\", 2.6)]\n    del um[\"ua\"]\n    assert sorted(um) == [\"ub\"]\n    assert sorted(um.items()) == [(\"ub\", 2.6)]\n\n\ndef test_map_view_types():\n    map_string_double = m.MapStringDouble()\n    unordered_map_string_double = m.UnorderedMapStringDouble()\n    map_string_double_const = m.MapStringDoubleConst()\n    unordered_map_string_double_const = m.UnorderedMapStringDoubleConst()\n\n    assert map_string_double.keys().__class__.__name__ == \"KeysView\"\n    assert map_string_double.values().__class__.__name__ == \"ValuesView\"\n    assert map_string_double.items().__class__.__name__ == \"ItemsView\"\n\n    keys_type = type(map_string_double.keys())\n    assert type(unordered_map_string_double.keys()) is keys_type\n    assert type(map_string_double_const.keys()) is keys_type\n    assert type(unordered_map_string_double_const.keys()) is keys_type\n\n    values_type = type(map_string_double.values())\n    assert type(unordered_map_string_double.values()) is values_type\n    assert type(map_string_double_const.values()) is values_type\n    assert type(unordered_map_string_double_const.values()) is values_type\n\n    items_type = type(map_string_double.items())\n    assert type(unordered_map_string_double.items()) is items_type\n    assert type(map_string_double_const.items()) is items_type\n    assert type(unordered_map_string_double_const.items()) is items_type\n\n    map_string_float = m.MapStringFloat()\n    unordered_map_string_float = m.UnorderedMapStringFloat()\n\n    assert type(map_string_float.keys()) is keys_type\n    assert type(unordered_map_string_float.keys()) is keys_type\n    assert type(map_string_float.values()) is values_type\n    assert type(unordered_map_string_float.values()) is values_type\n    assert type(map_string_float.items()) is items_type\n    assert type(unordered_map_string_float.items()) is items_type\n\n    map_pair_double_int_int32 = m.MapPairDoubleIntInt32()\n    map_pair_double_int_int64 = m.MapPairDoubleIntInt64()\n\n    assert type(map_pair_double_int_int32.values()) is values_type\n    assert type(map_pair_double_int_int64.values()) is values_type\n\n    map_int_object = m.MapIntObject()\n    map_string_object = m.MapStringObject()\n\n    assert type(map_int_object.keys()) is keys_type\n    assert type(map_string_object.keys()) is keys_type\n    assert type(map_int_object.items()) is items_type\n    assert type(map_string_object.items()) is items_type\n\n\ndef test_recursive_vector():\n    recursive_vector = m.RecursiveVector()\n    recursive_vector.append(m.RecursiveVector())\n    recursive_vector[0].append(m.RecursiveVector())\n    recursive_vector[0].append(m.RecursiveVector())\n    # Can't use len() since test_stl_binders.cpp does not include stl.h,\n    # so the necessary conversion is missing\n    assert recursive_vector[0].count(m.RecursiveVector()) == 2\n\n\ndef test_recursive_map():\n    recursive_map = m.RecursiveMap()\n    recursive_map[100] = m.RecursiveMap()\n    recursive_map[100][101] = m.RecursiveMap()\n    recursive_map[100][102] = m.RecursiveMap()\n    assert list(recursive_map[100].keys()) == [101, 102]\n\n\ndef test_user_vector_like():\n    vec = m.UserVectorLike()\n    vec.append(2)\n    assert vec[0] == 2\n    assert len(vec) == 1\n\n\ndef test_user_like_map():\n    map = m.UserMapLike()\n    map[33] = 44\n    assert map[33] == 44\n    assert len(map) == 1\n"
  },
  {
    "path": "tests/test_tagbased_polymorphic.cpp",
    "content": "/*\n    tests/test_tagbased_polymorphic.cpp -- test of polymorphic_type_hook\n\n    Copyright (c) 2018 Hudson River Trading LLC <opensource@hudson-trading.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/stl.h>\n\n#include \"pybind11_tests.h\"\n\nstruct Animal {\n    // Make this type also a \"standard\" polymorphic type, to confirm that\n    // specializing polymorphic_type_hook using enable_if_t still works\n    // (https://github.com/pybind/pybind11/pull/2016/).\n    virtual ~Animal() = default;\n\n    Animal(const Animal &) = delete;\n\n    // Enum for tag-based polymorphism.\n    enum class Kind {\n        Unknown = 0,\n        Dog = 100,\n        Labrador,\n        Chihuahua,\n        LastDog = 199,\n        Cat = 200,\n        Panther,\n        LastCat = 299\n    };\n    static const std::type_info *type_of_kind(Kind kind);\n    static std::string name_of_kind(Kind kind);\n\n    const Kind kind;\n    const std::string name;\n\nprotected:\n    Animal(const std::string &_name, Kind _kind) : kind(_kind), name(_name) {}\n};\n\nstruct Dog : Animal {\n    explicit Dog(const std::string &_name, Kind _kind = Kind::Dog) : Animal(_name, _kind) {}\n    std::string bark() const { return name_of_kind(kind) + \" \" + name + \" goes \" + sound; }\n    std::string sound = \"WOOF!\";\n};\n\nstruct Labrador : Dog {\n    explicit Labrador(const std::string &_name, int _excitement = 9001)\n        : Dog(_name, Kind::Labrador), excitement(_excitement) {}\n    int excitement;\n};\n\nstruct Chihuahua : Dog {\n    explicit Chihuahua(const std::string &_name) : Dog(_name, Kind::Chihuahua) {\n        sound = \"iyiyiyiyiyi\";\n    }\n    std::string bark() const { return Dog::bark() + \" and runs in circles\"; }\n};\n\nstruct Cat : Animal {\n    explicit Cat(const std::string &_name, Kind _kind = Kind::Cat) : Animal(_name, _kind) {}\n    std::string purr() const { return \"mrowr\"; }\n};\n\nstruct Panther : Cat {\n    explicit Panther(const std::string &_name) : Cat(_name, Kind::Panther) {}\n    std::string purr() const { return \"mrrrRRRRRR\"; }\n};\n\nstd::vector<std::unique_ptr<Animal>> create_zoo() {\n    std::vector<std::unique_ptr<Animal>> ret;\n    ret.emplace_back(new Labrador(\"Fido\", 15000));\n\n    // simulate some new type of Dog that the Python bindings\n    // haven't been updated for; it should still be considered\n    // a Dog, not just an Animal.\n    // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)\n    ret.emplace_back(new Dog(\"Ginger\", Dog::Kind(150)));\n\n    ret.emplace_back(new Chihuahua(\"Hertzl\"));\n    ret.emplace_back(new Cat(\"Tiger\", Cat::Kind::Cat));\n    ret.emplace_back(new Panther(\"Leo\"));\n    return ret;\n}\n\nconst std::type_info *Animal::type_of_kind(Kind kind) {\n    switch (kind) {\n        case Kind::Unknown:\n        case Kind::Dog:\n            break;\n\n        case Kind::Labrador:\n            return &typeid(Labrador);\n        case Kind::Chihuahua:\n            return &typeid(Chihuahua);\n\n        case Kind::LastDog:\n        case Kind::Cat:\n            break;\n        case Kind::Panther:\n            return &typeid(Panther);\n        case Kind::LastCat:\n            break;\n    }\n\n    if (kind >= Kind::Dog && kind <= Kind::LastDog) {\n        return &typeid(Dog);\n    }\n    if (kind >= Kind::Cat && kind <= Kind::LastCat) {\n        return &typeid(Cat);\n    }\n    return nullptr;\n}\n\nstd::string Animal::name_of_kind(Kind kind) {\n    std::string raw_name = type_of_kind(kind)->name();\n    py::detail::clean_type_id(raw_name);\n    return raw_name;\n}\n\nnamespace PYBIND11_NAMESPACE {\ntemplate <typename itype>\nstruct polymorphic_type_hook<itype, detail::enable_if_t<std::is_base_of<Animal, itype>::value>> {\n    static const void *get(const itype *src, const std::type_info *&type) {\n        type = src ? Animal::type_of_kind(src->kind) : nullptr;\n        return src;\n    }\n};\n} // namespace PYBIND11_NAMESPACE\n\nTEST_SUBMODULE(tagbased_polymorphic, m) {\n    py::class_<Animal>(m, \"Animal\").def_readonly(\"name\", &Animal::name);\n    py::class_<Dog, Animal>(m, \"Dog\")\n        .def(py::init<std::string>())\n        .def_readwrite(\"sound\", &Dog::sound)\n        .def(\"bark\", &Dog::bark);\n    py::class_<Labrador, Dog>(m, \"Labrador\")\n        .def(py::init<std::string, int>(), \"name\"_a, \"excitement\"_a = 9001)\n        .def_readwrite(\"excitement\", &Labrador::excitement);\n    py::class_<Chihuahua, Dog>(m, \"Chihuahua\")\n        .def(py::init<std::string>())\n        .def(\"bark\", &Chihuahua::bark);\n    py::class_<Cat, Animal>(m, \"Cat\").def(py::init<std::string>()).def(\"purr\", &Cat::purr);\n    py::class_<Panther, Cat>(m, \"Panther\")\n        .def(py::init<std::string>())\n        .def(\"purr\", &Panther::purr);\n    m.def(\"create_zoo\", &create_zoo);\n}\n"
  },
  {
    "path": "tests/test_tagbased_polymorphic.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import tagbased_polymorphic as m\n\n\ndef test_downcast():\n    zoo = m.create_zoo()\n    assert [type(animal) for animal in zoo] == [\n        m.Labrador,\n        m.Dog,\n        m.Chihuahua,\n        m.Cat,\n        m.Panther,\n    ]\n    assert [animal.name for animal in zoo] == [\n        \"Fido\",\n        \"Ginger\",\n        \"Hertzl\",\n        \"Tiger\",\n        \"Leo\",\n    ]\n    zoo[1].sound = \"woooooo\"\n    assert [dog.bark() for dog in zoo[:3]] == [\n        \"Labrador Fido goes WOOF!\",\n        \"Dog Ginger goes woooooo\",\n        \"Chihuahua Hertzl goes iyiyiyiyiyi and runs in circles\",\n    ]\n    assert [cat.purr() for cat in zoo[3:]] == [\"mrowr\", \"mrrrRRRRRR\"]\n    zoo[0].excitement -= 1000\n    assert zoo[0].excitement == 14000\n"
  },
  {
    "path": "tests/test_thread.cpp",
    "content": "/*\n    tests/test_thread.cpp -- call pybind11 bound methods in threads\n\n    Copyright (c) 2021 Laramie Leavitt (Google LLC) <lar@google.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/cast.h>\n#include <pybind11/pybind11.h>\n\n#include \"pybind11_tests.h\"\n\n#include <chrono>\n#include <thread>\n\n#if defined(PYBIND11_HAS_STD_BARRIER)\n#    include <barrier>\n#endif\n\nnamespace py = pybind11;\n\nnamespace {\n\nstruct IntStruct {\n    explicit IntStruct(int v) : value(v) {};\n    ~IntStruct() { value = -value; }\n    IntStruct(const IntStruct &) = default;\n    IntStruct &operator=(const IntStruct &) = default;\n\n    int value;\n};\n\nstruct EmptyStruct {};\nEmptyStruct SharedInstance;\n\n} // namespace\n\nTEST_SUBMODULE(thread, m) {\n    py::class_<IntStruct>(m, \"IntStruct\").def(py::init([](const int i) { return IntStruct(i); }));\n\n    // implicitly_convertible uses loader_life_support when an implicit\n    // conversion is required in order to lifetime extend the reference.\n    //\n    // This test should be run with ASAN for better effectiveness.\n    py::implicitly_convertible<int, IntStruct>();\n\n    m.def(\"test\", [](int expected, const IntStruct &in) {\n        {\n            py::gil_scoped_release release;\n            std::this_thread::sleep_for(std::chrono::milliseconds(5));\n        }\n\n        if (in.value != expected) {\n            throw std::runtime_error(\"Value changed!!\");\n        }\n    });\n\n    m.def(\n        \"test_no_gil\",\n        [](int expected, const IntStruct &in) {\n            std::this_thread::sleep_for(std::chrono::milliseconds(5));\n            if (in.value != expected) {\n                throw std::runtime_error(\"Value changed!!\");\n            }\n        },\n        py::call_guard<py::gil_scoped_release>());\n\n    py::class_<EmptyStruct>(m, \"EmptyStruct\")\n        .def_readonly_static(\"SharedInstance\", &SharedInstance);\n\n#if defined(PYBIND11_HAS_STD_BARRIER)\n    // In the free-threaded build, during PyThreadState_Clear, removing the thread from the biased\n    // reference counting table may call destructors. Make sure that it doesn't crash.\n    m.def(\"test_pythread_state_clear_destructor\", [](py::type cls) {\n        py::handle obj;\n\n        std::barrier barrier{2};\n        std::thread thread1{[&]() {\n            py::gil_scoped_acquire gil;\n            obj = cls().release();\n            barrier.arrive_and_wait();\n        }};\n        std::thread thread2{[&]() {\n            py::gil_scoped_acquire gil;\n            barrier.arrive_and_wait();\n            // ob_ref_shared becomes negative; transition to the queued state\n            obj.dec_ref();\n        }};\n\n        // jthread is not supported by Apple Clang\n        thread1.join();\n        thread2.join();\n    });\n#endif\n\n    m.attr(\"defined_PYBIND11_HAS_STD_BARRIER\") =\n#ifdef PYBIND11_HAS_STD_BARRIER\n        true;\n#else\n        false;\n#endif\n    m.def(\"acquire_gil\", []() { py::gil_scoped_acquire gil_acquired; });\n\n    // NOTE: std::string_view also uses loader_life_support to ensure that\n    // the string contents remain alive, but that's a C++ 17 feature.\n}\n"
  },
  {
    "path": "tests/test_thread.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport threading\n\nimport pytest\n\nimport env\nfrom pybind11_tests import thread as m\n\n\nclass Thread(threading.Thread):\n    def __init__(self, fn):\n        super().__init__()\n        self.fn = fn\n        self.e = None\n\n    def run(self):\n        try:\n            for i in range(10):\n                self.fn(i, i)\n        except Exception as e:\n            self.e = e\n\n    def join(self):\n        super().join()\n        if self.e:\n            raise self.e\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_implicit_conversion():\n    a = Thread(m.test)\n    b = Thread(m.test)\n    c = Thread(m.test)\n    for x in [a, b, c]:\n        x.start()\n    for x in [c, b, a]:\n        x.join()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_implicit_conversion_no_gil():\n    a = Thread(m.test_no_gil)\n    b = Thread(m.test_no_gil)\n    c = Thread(m.test_no_gil)\n    for x in [a, b, c]:\n        x.start()\n    for x in [c, b, a]:\n        x.join()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_bind_shared_instance():\n    nb_threads = 4\n    b = threading.Barrier(nb_threads)\n\n    def access_shared_instance():\n        b.wait()\n        for _ in range(1000):\n            m.EmptyStruct.SharedInstance  # noqa: B018\n\n    threads = [\n        threading.Thread(target=access_shared_instance) for _ in range(nb_threads)\n    ]\n    for thread in threads:\n        thread.start()\n    for thread in threads:\n        thread.join()\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\n@pytest.mark.skipif(not m.defined_PYBIND11_HAS_STD_BARRIER, reason=\"no <barrier>\")\n@pytest.mark.skipif(env.sys_is_gil_enabled(), reason=\"Deadlock with the GIL\")\ndef test_pythread_state_clear_destructor():\n    class Foo:\n        def __del__(self):\n            m.acquire_gil()\n\n    m.test_pythread_state_clear_destructor(Foo)\n"
  },
  {
    "path": "tests/test_type_caster_pyobject_ptr.cpp",
    "content": "#include <pybind11/functional.h>\n#include <pybind11/stl.h>\n#include <pybind11/type_caster_pyobject_ptr.h>\n\n#include \"pybind11_tests.h\"\n\n#include <cstddef>\n#include <string>\n#include <vector>\n\nnamespace test_type_caster_pyobject_ptr {\n\nstd::vector<PyObject *> make_vector_pyobject_ptr(const py::object &ValueHolder) {\n    std::vector<PyObject *> vec_obj;\n    for (int i = 1; i < 3; i++) {\n        vec_obj.push_back(ValueHolder(i * 93).release().ptr());\n    }\n    // This vector now owns the refcounts.\n    return vec_obj;\n}\n\nstruct WithPyObjectPtrReturn {\n#if defined(__clang_major__) && __clang_major__ < 4\n    WithPyObjectPtrReturn() = default;\n    WithPyObjectPtrReturn(const WithPyObjectPtrReturn &) = default;\n#endif\n    virtual ~WithPyObjectPtrReturn() = default;\n    virtual PyObject *return_pyobject_ptr() const = 0;\n};\n\nstruct WithPyObjectPtrReturnTrampoline : WithPyObjectPtrReturn {\n    PyObject *return_pyobject_ptr() const override {\n        PYBIND11_OVERRIDE_PURE(PyObject *, WithPyObjectPtrReturn, return_pyobject_ptr,\n                               /* no arguments */);\n    }\n};\n\nstd::string call_return_pyobject_ptr(const WithPyObjectPtrReturn *base_class_ptr) {\n    PyObject *returned_obj = base_class_ptr->return_pyobject_ptr();\n// It is not worth the trouble doing something special for PyPy/GraalPy\n#if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)\n    if (Py_REFCNT(returned_obj) != 1) {\n        py::pybind11_fail(__FILE__ \":\" PYBIND11_TOSTRING(__LINE__));\n    }\n#endif\n    auto ret_val = py::repr(returned_obj).cast<std::string>();\n    Py_DECREF(returned_obj);\n    return ret_val;\n}\n\n} // namespace test_type_caster_pyobject_ptr\n\nTEST_SUBMODULE(type_caster_pyobject_ptr, m) {\n    using namespace test_type_caster_pyobject_ptr;\n\n    m.def(\"cast_from_pyobject_ptr\", []() {\n        PyObject *ptr = PyLong_FromLongLong(6758L);\n        return py::cast(ptr, py::return_value_policy::take_ownership);\n    });\n    m.def(\"cast_handle_to_pyobject_ptr\", [](py::handle obj) {\n        auto rc1 = obj.ref_count();\n        auto *ptr = py::cast<PyObject *>(obj);\n        auto rc2 = obj.ref_count();\n        if (rc2 != rc1 + 1) {\n            return -1;\n        }\n        return 100 - py::reinterpret_steal<py::object>(ptr).attr(\"value\").cast<int>();\n    });\n    m.def(\"cast_object_to_pyobject_ptr\", [](py::object obj) {\n        py::handle hdl = obj;\n        auto rc1 = hdl.ref_count();\n        auto *ptr = py::cast<PyObject *>(std::move(obj));\n        auto rc2 = hdl.ref_count();\n        if (rc2 != rc1) {\n            return -1;\n        }\n        return 300 - py::reinterpret_steal<py::object>(ptr).attr(\"value\").cast<int>();\n    });\n    m.def(\"cast_list_to_pyobject_ptr\", [](py::list lst) {\n        // This is to cover types implicitly convertible to object.\n        py::handle hdl = lst;\n        auto rc1 = hdl.ref_count();\n        auto *ptr = py::cast<PyObject *>(std::move(lst));\n        auto rc2 = hdl.ref_count();\n        if (rc2 != rc1) {\n            return -1;\n        }\n        return 400 - static_cast<int>(py::len(py::reinterpret_steal<py::list>(ptr)));\n    });\n\n    m.def(\n        \"return_pyobject_ptr\",\n        []() { return PyLong_FromLongLong(2314L); },\n        py::return_value_policy::take_ownership);\n    m.def(\"pass_pyobject_ptr\", [](PyObject *ptr) {\n        return 200 - py::reinterpret_borrow<py::object>(ptr).attr(\"value\").cast<int>();\n    });\n\n    m.def(\"call_callback_with_object_return\",\n          [](const std::function<py::object(int)> &cb, int value) { return cb(value); });\n    m.def(\n        \"call_callback_with_pyobject_ptr_return\",\n        [](const std::function<PyObject *(int)> &cb, int value) { return cb(value); },\n        py::return_value_policy::take_ownership);\n    m.def(\n        \"call_callback_with_pyobject_ptr_arg\",\n        [](const std::function<int(PyObject *)> &cb, py::handle obj) { return cb(obj.ptr()); },\n        py::arg(\"cb\"), // This triggers return_value_policy::automatic_reference\n        py::arg(\"obj\"));\n\n    m.def(\"cast_to_pyobject_ptr_nullptr\", [](bool set_error) {\n        if (set_error) {\n            py::set_error(PyExc_RuntimeError, \"Reflective of healthy error handling.\");\n        }\n        PyObject *ptr = nullptr;\n        py::cast(ptr);\n    });\n\n    m.def(\"cast_to_pyobject_ptr_non_nullptr_with_error_set\", []() {\n        py::set_error(PyExc_RuntimeError, \"Reflective of unhealthy error handling.\");\n        py::cast(Py_None);\n    });\n\n    m.def(\"pass_list_pyobject_ptr\", [](const std::vector<PyObject *> &vec_obj) {\n        int acc = 0;\n        for (const auto &ptr : vec_obj) {\n            acc = acc * 1000 + py::reinterpret_borrow<py::object>(ptr).attr(\"value\").cast<int>();\n        }\n        return acc;\n    });\n\n    m.def(\"return_list_pyobject_ptr_take_ownership\",\n          make_vector_pyobject_ptr,\n          // Ownership is transferred one-by-one when the vector is converted to a Python list.\n          py::return_value_policy::take_ownership);\n\n    m.def(\"return_list_pyobject_ptr_reference\",\n          make_vector_pyobject_ptr,\n          // Ownership is not transferred.\n          py::return_value_policy::reference);\n\n    m.def(\"dec_ref_each_pyobject_ptr\", [](const std::vector<PyObject *> &vec_obj) {\n        std::size_t i = 0;\n        for (; i < vec_obj.size(); i++) {\n            py::handle h(vec_obj[i]);\n            if (static_cast<std::size_t>(h.ref_count()) < 2) {\n                break; // Something is badly wrong.\n            }\n            h.dec_ref();\n        }\n        return i;\n    });\n\n    m.def(\"pass_pyobject_ptr_and_int\", [](PyObject *, int) {});\n\n#ifdef PYBIND11_NO_COMPILE_SECTION // Change to ifndef for manual testing.\n    {\n        PyObject *ptr = nullptr;\n        (void) py::cast(*ptr);\n    }\n#endif\n\n    py::class_<WithPyObjectPtrReturn, WithPyObjectPtrReturnTrampoline>(m, \"WithPyObjectPtrReturn\")\n        .def(py::init<>())\n        .def(\"return_pyobject_ptr\", &WithPyObjectPtrReturn::return_pyobject_ptr);\n\n    m.def(\"call_return_pyobject_ptr\", call_return_pyobject_ptr);\n}\n"
  },
  {
    "path": "tests/test_type_caster_pyobject_ptr.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import type_caster_pyobject_ptr as m\n\n\n# For use as a temporary user-defined object, to maximize sensitivity of the tests below.\nclass ValueHolder:\n    def __init__(self, value):\n        self.value = value\n\n\ndef test_cast_from_pyobject_ptr():\n    assert m.cast_from_pyobject_ptr() == 6758\n\n\ndef test_cast_handle_to_pyobject_ptr():\n    assert m.cast_handle_to_pyobject_ptr(ValueHolder(24)) == 76\n\n\ndef test_cast_object_to_pyobject_ptr():\n    assert m.cast_object_to_pyobject_ptr(ValueHolder(43)) == 257\n\n\ndef test_cast_list_to_pyobject_ptr():\n    assert m.cast_list_to_pyobject_ptr([1, 2, 3, 4, 5]) == 395\n\n\ndef test_return_pyobject_ptr():\n    assert m.return_pyobject_ptr() == 2314\n\n\ndef test_pass_pyobject_ptr():\n    assert m.pass_pyobject_ptr(ValueHolder(82)) == 118\n\n\n@pytest.mark.parametrize(\n    \"call_callback\",\n    [\n        m.call_callback_with_object_return,\n        m.call_callback_with_pyobject_ptr_return,\n    ],\n)\ndef test_call_callback_with_object_return(call_callback):\n    def cb(value):\n        if value < 0:\n            raise ValueError(\"Raised from cb\")\n        return ValueHolder(1000 - value)\n\n    assert call_callback(cb, 287).value == 713\n\n    with pytest.raises(ValueError, match=\"^Raised from cb$\"):\n        call_callback(cb, -1)\n\n\ndef test_call_callback_with_pyobject_ptr_arg():\n    def cb(obj):\n        return 300 - obj.value\n\n    assert m.call_callback_with_pyobject_ptr_arg(cb, ValueHolder(39)) == 261\n\n\n@pytest.mark.parametrize(\"set_error\", [True, False])\ndef test_cast_to_python_nullptr(set_error):\n    expected = {\n        True: r\"^Reflective of healthy error handling\\.$\",\n        False: (\n            r\"^Internal error: pybind11::error_already_set called \"\n            r\"while Python error indicator not set\\.$\"\n        ),\n    }[set_error]\n    with pytest.raises(RuntimeError, match=expected):\n        m.cast_to_pyobject_ptr_nullptr(set_error)\n\n\ndef test_cast_to_python_non_nullptr_with_error_set():\n    with pytest.raises(SystemError) as excinfo:\n        m.cast_to_pyobject_ptr_non_nullptr_with_error_set()\n    assert str(excinfo.value) == \"src != nullptr but PyErr_Occurred()\"\n    assert str(excinfo.value.__cause__) == \"Reflective of unhealthy error handling.\"\n\n\ndef test_pass_list_pyobject_ptr():\n    acc = m.pass_list_pyobject_ptr([ValueHolder(842), ValueHolder(452)])\n    assert acc == 842452\n\n\ndef test_return_list_pyobject_ptr_take_ownership():\n    vec_obj = m.return_list_pyobject_ptr_take_ownership(ValueHolder)\n    assert [e.value for e in vec_obj] == [93, 186]\n\n\ndef test_return_list_pyobject_ptr_reference():\n    vec_obj = m.return_list_pyobject_ptr_reference(ValueHolder)\n    assert [e.value for e in vec_obj] == [93, 186]\n    # Commenting out the next `assert` will leak the Python references.\n    # An easy way to see evidence of the leaks:\n    # Insert `while True:` as the first line of this function and monitor the\n    # process RES (Resident Memory Size) with the Unix top command.\n    assert m.dec_ref_each_pyobject_ptr(vec_obj) == 2\n\n\ndef test_type_caster_name_via_incompatible_function_arguments_type_error():\n    with pytest.raises(\n        TypeError,\n        match=r\"1\\. \\(arg0: object, arg1: typing.SupportsInt \\| typing.SupportsIndex\\) -> None\",\n    ):\n        m.pass_pyobject_ptr_and_int(ValueHolder(101), ValueHolder(202))\n\n\ndef test_trampoline_with_pyobject_ptr_return():\n    class Drvd(m.WithPyObjectPtrReturn):\n        def return_pyobject_ptr(self):\n            return [\"11\", \"22\", \"33\"]\n\n    # Basic health check: First make sure this works as expected.\n    d = Drvd()\n    assert d.return_pyobject_ptr() == [\"11\", \"22\", \"33\"]\n\n    while True:\n        # This failed before PR #5156: AddressSanitizer: heap-use-after-free ... in Py_DECREF\n        d_repr = m.call_return_pyobject_ptr(d)\n        assert d_repr == repr([\"11\", \"22\", \"33\"])\n        break  # Comment out for manual leak checking.\n"
  },
  {
    "path": "tests/test_type_caster_std_function_specializations.cpp",
    "content": "#include <pybind11/functional.h>\n#include <pybind11/pybind11.h>\n\n#include \"pybind11_tests.h\"\n\nnamespace py = pybind11;\n\nnamespace {\n\nstruct SpecialReturn {\n    int value = 99;\n};\n\n} // namespace\n\nnamespace pybind11 {\nnamespace detail {\nnamespace type_caster_std_function_specializations {\n\ntemplate <typename... Args>\nstruct func_wrapper<SpecialReturn, Args...> : func_wrapper_base {\n    using func_wrapper_base::func_wrapper_base;\n    SpecialReturn operator()(Args... args) const {\n        gil_scoped_acquire acq;\n        SpecialReturn result;\n        try {\n            result = hfunc.f(std::forward<Args>(args)...).template cast<SpecialReturn>();\n        } catch (error_already_set &) {\n            result.value += 1;\n        }\n        result.value += 100;\n        return result;\n    }\n};\n\n} // namespace type_caster_std_function_specializations\n} // namespace detail\n} // namespace pybind11\n\nTEST_SUBMODULE(type_caster_std_function_specializations, m) {\n    py::class_<SpecialReturn>(m, \"SpecialReturn\")\n        .def(py::init<>())\n        .def_readwrite(\"value\", &SpecialReturn::value);\n    m.def(\"call_callback_with_special_return\",\n          [](const std::function<SpecialReturn()> &func) { return func(); });\n}\n"
  },
  {
    "path": "tests/test_type_caster_std_function_specializations.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import type_caster_std_function_specializations as m\n\n\ndef test_callback_with_special_return():\n    def return_special():\n        return m.SpecialReturn()\n\n    def raise_exception():\n        raise ValueError(\"called raise_exception.\")\n\n    assert return_special().value == 99\n    assert m.call_callback_with_special_return(return_special).value == 199\n    assert m.call_callback_with_special_return(raise_exception).value == 200\n"
  },
  {
    "path": "tests/test_union.cpp",
    "content": "/*\n    tests/test_class.cpp -- test py::class_ definitions and basic functionality\n\n    Copyright (c) 2019 Roland Dreier <roland.dreier@gmail.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include \"pybind11_tests.h\"\n\nTEST_SUBMODULE(union_, m) {\n    union TestUnion {\n        int value_int;\n        unsigned value_uint;\n    };\n\n    py::class_<TestUnion>(m, \"TestUnion\")\n        .def(py::init<>())\n        .def_readonly(\"as_int\", &TestUnion::value_int)\n        .def_readwrite(\"as_uint\", &TestUnion::value_uint);\n}\n"
  },
  {
    "path": "tests/test_union.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import union_ as m\n\n\ndef test_union():\n    instance = m.TestUnion()\n\n    instance.as_uint = 10\n    assert instance.as_int == 10\n"
  },
  {
    "path": "tests/test_unnamed_namespace_a.cpp",
    "content": "#include \"pybind11_tests.h\"\n\nnamespace {\nstruct any_struct {};\n} // namespace\n\nTEST_SUBMODULE(unnamed_namespace_a, m) {\n    if (py::detail::get_type_info(typeid(any_struct)) == nullptr) {\n        py::class_<any_struct>(m, \"unnamed_namespace_a_any_struct\");\n    } else {\n        m.attr(\"unnamed_namespace_a_any_struct\") = py::none();\n    }\n    m.attr(\"defined_WIN32_or__WIN32\") =\n#if defined(WIN32) || defined(_WIN32)\n        true;\n#else\n        false;\n#endif\n    m.attr(\"defined___clang__\") =\n#if defined(__clang__)\n        true;\n#else\n        false;\n#endif\n    m.attr(\"defined__LIBCPP_VERSION\") =\n#if defined(_LIBCPP_VERSION)\n        true;\n#else\n        false;\n#endif\n    m.attr(\"defined___GLIBCXX__\") =\n#if defined(__GLIBCXX__)\n        true;\n#else\n        false;\n#endif\n}\n"
  },
  {
    "path": "tests/test_unnamed_namespace_a.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import unnamed_namespace_a as m\nfrom pybind11_tests import unnamed_namespace_b as mb\n\nXFAIL_CONDITION = (\n    \"m.defined__LIBCPP_VERSION or \"\n    \"(not m.defined_WIN32_or__WIN32 and m.defined___clang__)\"\n)\nXFAIL_REASON = \"Known issues: https://github.com/pybind/pybind11/pull/4319\"\n\n\n@pytest.mark.xfail(XFAIL_CONDITION, reason=XFAIL_REASON, strict=False)\n@pytest.mark.parametrize(\n    \"any_struct\", [m.unnamed_namespace_a_any_struct, mb.unnamed_namespace_b_any_struct]\n)\ndef test_have_class_any_struct(any_struct):\n    assert any_struct is not None\n\n\ndef test_have_at_least_one_class_any_struct():\n    assert (\n        m.unnamed_namespace_a_any_struct is not None\n        or mb.unnamed_namespace_b_any_struct is not None\n    )\n\n\n@pytest.mark.xfail(XFAIL_CONDITION, reason=XFAIL_REASON, strict=True)\ndef test_have_both_class_any_struct():\n    assert m.unnamed_namespace_a_any_struct is not None\n    assert mb.unnamed_namespace_b_any_struct is not None\n"
  },
  {
    "path": "tests/test_unnamed_namespace_b.cpp",
    "content": "#include \"pybind11_tests.h\"\n\nnamespace {\nstruct any_struct {};\n} // namespace\n\nTEST_SUBMODULE(unnamed_namespace_b, m) {\n    if (py::detail::get_type_info(typeid(any_struct)) == nullptr) {\n        py::class_<any_struct>(m, \"unnamed_namespace_b_any_struct\");\n    } else {\n        m.attr(\"unnamed_namespace_b_any_struct\") = py::none();\n    }\n}\n"
  },
  {
    "path": "tests/test_unnamed_namespace_b.py",
    "content": "from __future__ import annotations\n\nfrom pybind11_tests import unnamed_namespace_b as m\n\n\ndef test_have_attr_any_struct():\n    assert hasattr(m, \"unnamed_namespace_b_any_struct\")\n"
  },
  {
    "path": "tests/test_vector_unique_ptr_member.cpp",
    "content": "#include \"pybind11_tests.h\"\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\nnamespace pybind11_tests {\nnamespace vector_unique_ptr_member {\n\nstruct DataType {};\n\n// Reduced from a use case in the wild.\nstruct VectorOwner {\n    static std::unique_ptr<VectorOwner> Create(std::size_t num_elems) {\n        return std::unique_ptr<VectorOwner>(\n            new VectorOwner(std::vector<std::unique_ptr<DataType>>(num_elems)));\n    }\n\n    std::size_t data_size() const { return data_.size(); }\n\nprivate:\n    explicit VectorOwner(std::vector<std::unique_ptr<DataType>> data) : data_(std::move(data)) {}\n\n    const std::vector<std::unique_ptr<DataType>> data_;\n};\n\n} // namespace vector_unique_ptr_member\n} // namespace pybind11_tests\n\nnamespace pybind11 {\nnamespace detail {\n\ntemplate <>\nstruct is_copy_constructible<pybind11_tests::vector_unique_ptr_member::VectorOwner>\n    : std::false_type {};\n\ntemplate <>\nstruct is_move_constructible<pybind11_tests::vector_unique_ptr_member::VectorOwner>\n    : std::false_type {};\n\n} // namespace detail\n} // namespace pybind11\n\nusing namespace pybind11_tests::vector_unique_ptr_member;\n\npy::object py_cast_VectorOwner_ptr(VectorOwner *ptr) { return py::cast(ptr); }\n\nTEST_SUBMODULE(vector_unique_ptr_member, m) {\n    py::class_<VectorOwner>(m, \"VectorOwner\")\n        .def_static(\"Create\", &VectorOwner::Create)\n        .def(\"data_size\", &VectorOwner::data_size);\n\n    m.def(\"py_cast_VectorOwner_ptr\", py_cast_VectorOwner_ptr);\n}\n"
  },
  {
    "path": "tests/test_vector_unique_ptr_member.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\nfrom pybind11_tests import vector_unique_ptr_member as m\n\n\n@pytest.mark.parametrize(\"num_elems\", range(3))\ndef test_create(num_elems):\n    vo = m.VectorOwner.Create(num_elems)\n    assert vo.data_size() == num_elems\n\n\ndef test_cast():\n    vo = m.VectorOwner.Create(0)\n    assert m.py_cast_VectorOwner_ptr(vo) is vo\n"
  },
  {
    "path": "tests/test_virtual_functions.cpp",
    "content": "/*\n    tests/test_virtual_functions.cpp -- overriding virtual functions from Python\n\n    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/functional.h>\n\n#include \"constructor_stats.h\"\n#include \"pybind11_tests.h\"\n\n#include <thread>\n\n/* This is an example class that we'll want to be able to extend from Python */\nclass ExampleVirt {\npublic:\n    explicit ExampleVirt(int state) : state(state) { print_created(this, state); }\n    ExampleVirt(const ExampleVirt &e) : state(e.state) { print_copy_created(this); }\n    ExampleVirt(ExampleVirt &&e) noexcept : state(e.state) {\n        print_move_created(this);\n        e.state = 0;\n    }\n    virtual ~ExampleVirt() { print_destroyed(this); }\n\n    virtual int run(int value) {\n        py::print(\"Original implementation of \"\n                  \"ExampleVirt::run(state={}, value={}, str1={}, str2={})\"_s.format(\n                      state, value, get_string1(), *get_string2()));\n        return state + value;\n    }\n\n    virtual bool run_bool() = 0;\n    virtual void pure_virtual() = 0;\n\n    // Returning a reference/pointer to a type converted from python (numbers, strings, etc.) is a\n    // bit trickier, because the actual int& or std::string& or whatever only exists temporarily,\n    // so we have to handle it specially in the trampoline class (see below).\n    virtual const std::string &get_string1() { return str1; }\n    virtual const std::string *get_string2() { return &str2; }\n\nprivate:\n    int state;\n    const std::string str1{\"default1\"}, str2{\"default2\"};\n};\n\n/* This is a wrapper class that must be generated */\nclass PyExampleVirt : public ExampleVirt {\npublic:\n    using ExampleVirt::ExampleVirt; /* Inherit constructors */\n\n    int run(int value) override {\n        /* Generate wrapping code that enables native function overloading */\n        PYBIND11_OVERRIDE(int,         /* Return type */\n                          ExampleVirt, /* Parent class */\n                          run,         /* Name of function */\n                          value        /* Argument(s) */\n        );\n    }\n\n    bool run_bool() override {\n        PYBIND11_OVERRIDE_PURE(bool,        /* Return type */\n                               ExampleVirt, /* Parent class */\n                               run_bool,    /* Name of function */\n                                            /* This function has no arguments. The trailing comma\n                                               in the previous line is needed for some compilers */\n        );\n    }\n\n    void pure_virtual() override {\n        PYBIND11_OVERRIDE_PURE(void,         /* Return type */\n                               ExampleVirt,  /* Parent class */\n                               pure_virtual, /* Name of function */\n                                             /* This function has no arguments. The trailing comma\n                                                in the previous line is needed for some compilers */\n        );\n    }\n\n    // We can return reference types for compatibility with C++ virtual interfaces that do so, but\n    // note they have some significant limitations (see the documentation).\n    const std::string &get_string1() override {\n        PYBIND11_OVERRIDE(const std::string &, /* Return type */\n                          ExampleVirt,         /* Parent class */\n                          get_string1,         /* Name of function */\n                                               /* (no arguments) */\n        );\n    }\n\n    const std::string *get_string2() override {\n        PYBIND11_OVERRIDE(const std::string *, /* Return type */\n                          ExampleVirt,         /* Parent class */\n                          get_string2,         /* Name of function */\n                                               /* (no arguments) */\n        );\n    }\n};\n\nclass NonCopyable {\npublic:\n    NonCopyable(int a, int b) : value{new int(a * b)} { print_created(this, a, b); }\n    NonCopyable(NonCopyable &&o) noexcept : value{std::move(o.value)} { print_move_created(this); }\n    NonCopyable(const NonCopyable &) = delete;\n    NonCopyable() = delete;\n    void operator=(const NonCopyable &) = delete;\n    void operator=(NonCopyable &&) = delete;\n    std::string get_value() const {\n        if (value) {\n            return std::to_string(*value);\n        }\n        return \"(null)\";\n    }\n    ~NonCopyable() { print_destroyed(this); }\n\nprivate:\n    std::unique_ptr<int> value;\n};\n\n// This is like the above, but is both copy and movable.  In effect this means it should get moved\n// when it is not referenced elsewhere, but copied if it is still referenced.\nclass Movable {\npublic:\n    Movable(int a, int b) : value{a + b} { print_created(this, a, b); }\n    Movable(const Movable &m) : value{m.value} { print_copy_created(this); }\n    Movable(Movable &&m) noexcept : value{m.value} { print_move_created(this); }\n    std::string get_value() const { return std::to_string(value); }\n    ~Movable() { print_destroyed(this); }\n\nprivate:\n    int value;\n};\n\nclass NCVirt {\npublic:\n    virtual ~NCVirt() = default;\n    NCVirt() = default;\n    NCVirt(const NCVirt &) = delete;\n    virtual NonCopyable get_noncopyable(int a, int b) { return NonCopyable(a, b); }\n    virtual Movable get_movable(int a, int b) = 0;\n\n    std::string print_nc(int a, int b) { return get_noncopyable(a, b).get_value(); }\n    std::string print_movable(int a, int b) { return get_movable(a, b).get_value(); }\n};\nclass NCVirtTrampoline : public NCVirt {\n#if !defined(__INTEL_COMPILER) && !defined(__CUDACC__) && !defined(__PGIC__)\n    NonCopyable get_noncopyable(int a, int b) override {\n        PYBIND11_OVERRIDE(NonCopyable, NCVirt, get_noncopyable, a, b);\n    }\n#endif\n    Movable get_movable(int a, int b) override {\n        PYBIND11_OVERRIDE_PURE(Movable, NCVirt, get_movable, a, b);\n    }\n};\n\nstruct Base {\n    virtual std::string dispatch() const = 0;\n    virtual ~Base() = default;\n    Base() = default;\n    Base(const Base &) = delete;\n};\n\nstruct DispatchIssue : Base {\n    std::string dispatch() const override {\n        PYBIND11_OVERRIDE_PURE(std::string, Base, dispatch, /* no arguments */);\n    }\n};\n\n// An abstract adder class that uses visitor pattern to add two data\n// objects and send the result to the visitor functor\nstruct AdderBase {\n    struct Data {};\n    using DataVisitor = std::function<void(const Data &)>;\n\n    virtual void\n    operator()(const Data &first, const Data &second, const DataVisitor &visitor) const\n        = 0;\n    virtual ~AdderBase() = default;\n    AdderBase() = default;\n    AdderBase(const AdderBase &) = delete;\n};\n\nstruct Adder : AdderBase {\n    void\n    operator()(const Data &first, const Data &second, const DataVisitor &visitor) const override {\n        PYBIND11_OVERRIDE_PURE_NAME(\n            void, AdderBase, \"__call__\", operator(), first, second, visitor);\n    }\n};\n\nstatic void test_gil() {\n    {\n        py::gil_scoped_acquire lock;\n        py::print(\"1st lock acquired\");\n    }\n\n    {\n        py::gil_scoped_acquire lock;\n        py::print(\"2nd lock acquired\");\n    }\n}\n\nstatic void test_gil_from_thread() {\n    py::gil_scoped_release release;\n\n    std::thread t(test_gil);\n    t.join();\n}\n\nclass test_override_cache_helper {\n\npublic:\n    virtual int func() { return 0; }\n\n    test_override_cache_helper() = default;\n    virtual ~test_override_cache_helper() = default;\n    // Non-copyable\n    test_override_cache_helper &operator=(test_override_cache_helper const &Right) = delete;\n    test_override_cache_helper(test_override_cache_helper const &Copy) = delete;\n};\n\nclass test_override_cache_helper_trampoline : public test_override_cache_helper {\n    int func() override { PYBIND11_OVERRIDE(int, test_override_cache_helper, func); }\n};\n\ninline int test_override_cache(std::shared_ptr<test_override_cache_helper> const &instance) {\n    return instance->func();\n}\n\n// Forward declaration (so that we can put the main tests here; the inherited virtual approaches\n// are rather long).\nvoid initialize_inherited_virtuals(py::module_ &m);\n\nTEST_SUBMODULE(virtual_functions, m) {\n    // test_override\n    py::class_<ExampleVirt, PyExampleVirt>(m, \"ExampleVirt\")\n        .def(py::init<int>())\n        /* Reference original class in function definitions */\n        .def(\"run\", &ExampleVirt::run)\n        .def(\"run_bool\", &ExampleVirt::run_bool)\n        .def(\"pure_virtual\", &ExampleVirt::pure_virtual);\n\n    py::class_<NonCopyable>(m, \"NonCopyable\").def(py::init<int, int>());\n\n    py::class_<Movable>(m, \"Movable\").def(py::init<int, int>());\n\n    // test_move_support\n#if !defined(__INTEL_COMPILER) && !defined(__CUDACC__) && !defined(__PGIC__)\n    py::class_<NCVirt, NCVirtTrampoline>(m, \"NCVirt\")\n        .def(py::init<>())\n        .def(\"get_noncopyable\", &NCVirt::get_noncopyable)\n        .def(\"get_movable\", &NCVirt::get_movable)\n        .def(\"print_nc\", &NCVirt::print_nc)\n        .def(\"print_movable\", &NCVirt::print_movable);\n#endif\n\n    m.def(\"runExampleVirt\", [](ExampleVirt *ex, int value) { return ex->run(value); });\n    m.def(\"runExampleVirtBool\", [](ExampleVirt *ex) { return ex->run_bool(); });\n    m.def(\"runExampleVirtVirtual\", [](ExampleVirt *ex) { ex->pure_virtual(); });\n\n    m.def(\"cstats_debug\", &ConstructorStats::get<ExampleVirt>);\n    initialize_inherited_virtuals(m);\n\n    // test_alias_delay_initialization1\n    // don't invoke Python dispatch classes by default when instantiating C++ classes\n    // that were not extended on the Python side\n    struct A {\n        A() = default;\n        A(const A &) = delete;\n        virtual ~A() = default;\n        virtual void f() { py::print(\"A.f()\"); }\n    };\n\n    struct PyA : A {\n        PyA() { py::print(\"PyA.PyA()\"); }\n        PyA(const PyA &) = delete;\n        ~PyA() override { py::print(\"PyA.~PyA()\"); }\n\n        void f() override {\n            py::print(\"PyA.f()\");\n            // This convolution just gives a `void`, but tests that PYBIND11_TYPE() works to\n            // protect a type containing a ,\n            PYBIND11_OVERRIDE(PYBIND11_TYPE(typename std::enable_if<true, void>::type), A, f);\n        }\n    };\n\n    py::class_<A, PyA>(m, \"A\").def(py::init<>()).def(\"f\", &A::f);\n\n    m.def(\"call_f\", [](A *a) { a->f(); });\n\n    // test_alias_delay_initialization2\n    // ... unless we explicitly request it, as in this example:\n    struct A2 {\n        A2() = default;\n        A2(const A2 &) = delete;\n        virtual ~A2() = default;\n        virtual void f() { py::print(\"A2.f()\"); }\n    };\n\n    struct PyA2 : A2 {\n        PyA2() { py::print(\"PyA2.PyA2()\"); }\n        PyA2(const PyA2 &) = delete;\n        ~PyA2() override { py::print(\"PyA2.~PyA2()\"); }\n        void f() override {\n            py::print(\"PyA2.f()\");\n            PYBIND11_OVERRIDE(void, A2, f);\n        }\n    };\n\n    py::class_<A2, PyA2>(m, \"A2\")\n        .def(py::init_alias<>())\n        .def(py::init([](int) { return new PyA2(); }))\n        .def(\"f\", &A2::f);\n\n    m.def(\"call_f\", [](A2 *a2) { a2->f(); });\n\n    // test_dispatch_issue\n    // #159: virtual function dispatch has problems with similar-named functions\n    py::class_<Base, DispatchIssue>(m, \"DispatchIssue\")\n        .def(py::init<>())\n        .def(\"dispatch\", &Base::dispatch);\n\n    m.def(\"dispatch_issue_go\", [](const Base *b) { return b->dispatch(); });\n\n    // test_recursive_dispatch_issue\n    // #3357: Recursive dispatch fails to find python function override\n    pybind11::class_<AdderBase, Adder>(m, \"Adder\")\n        .def(pybind11::init<>())\n        .def(\"__call__\", &AdderBase::operator());\n\n    pybind11::class_<AdderBase::Data>(m, \"Data\").def(pybind11::init<>());\n\n    m.def(\"add2\",\n          [](const AdderBase::Data &first,\n             const AdderBase::Data &second,\n             const AdderBase &adder,\n             const AdderBase::DataVisitor &visitor) { adder(first, second, visitor); });\n\n    m.def(\"add3\",\n          [](const AdderBase::Data &first,\n             const AdderBase::Data &second,\n             const AdderBase::Data &third,\n             const AdderBase &adder,\n             const AdderBase::DataVisitor &visitor) {\n              adder(first, second, [&](const AdderBase::Data &first_plus_second) {\n                  // NOLINTNEXTLINE(readability-suspicious-call-argument)\n                  adder(first_plus_second, third, visitor);\n              });\n          });\n\n    // test_override_ref\n    // #392/397: overriding reference-returning functions\n    class OverrideTest {\n    public:\n        struct A {\n            std::string value = \"hi\";\n        };\n        std::string v;\n        A a;\n        explicit OverrideTest(const std::string &v) : v{v} {}\n        OverrideTest() = default;\n        OverrideTest(const OverrideTest &) = delete;\n        virtual std::string str_value() { return v; }\n        virtual std::string &str_ref() { return v; }\n        virtual A A_value() { return a; }\n        virtual A &A_ref() { return a; }\n        virtual ~OverrideTest() = default;\n    };\n\n    class PyOverrideTest : public OverrideTest {\n    public:\n        using OverrideTest::OverrideTest;\n        std::string str_value() override {\n            PYBIND11_OVERRIDE(std::string, OverrideTest, str_value);\n        }\n        // Not allowed (enabling the below should hit a static_assert failure): we can't get a\n        // reference to a python numeric value, since we only copy values in the numeric type\n        // caster:\n#ifdef PYBIND11_NEVER_DEFINED_EVER\n        std::string &str_ref() override {\n            PYBIND11_OVERRIDE(std::string &, OverrideTest, str_ref);\n        }\n#endif\n        // But we can work around it like this:\n    private:\n        std::string _tmp;\n        std::string str_ref_helper() { PYBIND11_OVERRIDE(std::string, OverrideTest, str_ref); }\n\n    public:\n        std::string &str_ref() override { return _tmp = str_ref_helper(); }\n\n        A A_value() override { PYBIND11_OVERRIDE(A, OverrideTest, A_value); }\n        A &A_ref() override { PYBIND11_OVERRIDE(A &, OverrideTest, A_ref); }\n    };\n\n    py::class_<OverrideTest::A>(m, \"OverrideTest_A\")\n        .def_readwrite(\"value\", &OverrideTest::A::value);\n    py::class_<OverrideTest, PyOverrideTest>(m, \"OverrideTest\")\n        .def(py::init<const std::string &>())\n        .def(\"str_value\", &OverrideTest::str_value)\n#ifdef PYBIND11_NEVER_DEFINED_EVER\n        .def(\"str_ref\", &OverrideTest::str_ref)\n#endif\n        .def(\"A_value\", &OverrideTest::A_value)\n        .def(\"A_ref\", &OverrideTest::A_ref);\n\n    py::class_<test_override_cache_helper,\n               test_override_cache_helper_trampoline,\n               std::shared_ptr<test_override_cache_helper>>(m, \"test_override_cache_helper\")\n        .def(py::init_alias<>())\n        .def(\"func\", &test_override_cache_helper::func);\n\n    m.def(\"test_override_cache\", test_override_cache);\n}\n\n// Inheriting virtual methods.  We do two versions here: the repeat-everything version and the\n// templated trampoline versions mentioned in docs/advanced.rst.\n//\n// These base classes are exactly the same, but we technically need distinct\n// classes for this example code because we need to be able to bind them\n// properly (pybind11, sensibly, doesn't allow us to bind the same C++ class to\n// multiple python classes).\nclass A_Repeat {\n#define A_METHODS                                                                                 \\\npublic:                                                                                           \\\n    virtual int unlucky_number() = 0;                                                             \\\n    virtual std::string say_something(unsigned times) {                                           \\\n        std::string s = \"\";                                                                       \\\n        for (unsigned i = 0; i < times; ++i)                                                      \\\n            s += \"hi\";                                                                            \\\n        return s;                                                                                 \\\n    }                                                                                             \\\n    std::string say_everything() {                                                                \\\n        return say_something(1) + \" \" + std::to_string(unlucky_number());                         \\\n    }\n    A_METHODS\n    A_Repeat() = default;\n    A_Repeat(const A_Repeat &) = delete;\n    virtual ~A_Repeat() = default;\n};\nclass B_Repeat : public A_Repeat {\n#define B_METHODS                                                                                 \\\npublic:                                                                                           \\\n    int unlucky_number() override { return 13; }                                                  \\\n    std::string say_something(unsigned times) override {                                          \\\n        return \"B says hi \" + std::to_string(times) + \" times\";                                   \\\n    }                                                                                             \\\n    virtual double lucky_number() { return 7.0; }\n    B_METHODS\n};\nclass C_Repeat : public B_Repeat {\n#define C_METHODS                                                                                 \\\npublic:                                                                                           \\\n    int unlucky_number() override { return 4444; }                                                \\\n    double lucky_number() override { return 888; }\n    C_METHODS\n};\nclass D_Repeat : public C_Repeat {\n#define D_METHODS // Nothing overridden.\n    D_METHODS\n};\n\n// Base classes for templated inheritance trampolines.  Identical to the repeat-everything version:\nclass A_Tpl {\n    A_METHODS;\n    A_Tpl() = default;\n    A_Tpl(const A_Tpl &) = delete;\n    virtual ~A_Tpl() = default;\n};\nclass B_Tpl : public A_Tpl {\n    B_METHODS\n};\nclass C_Tpl : public B_Tpl {\n    C_METHODS\n};\nclass D_Tpl : public C_Tpl {\n    D_METHODS\n};\n\n// Inheritance approach 1: each trampoline gets every virtual method (11 in total)\nclass PyA_Repeat : public A_Repeat {\npublic:\n    using A_Repeat::A_Repeat;\n    int unlucky_number() override { PYBIND11_OVERRIDE_PURE(int, A_Repeat, unlucky_number, ); }\n    std::string say_something(unsigned times) override {\n        PYBIND11_OVERRIDE(std::string, A_Repeat, say_something, times);\n    }\n};\nclass PyB_Repeat : public B_Repeat {\npublic:\n    using B_Repeat::B_Repeat;\n    int unlucky_number() override { PYBIND11_OVERRIDE(int, B_Repeat, unlucky_number, ); }\n    std::string say_something(unsigned times) override {\n        PYBIND11_OVERRIDE(std::string, B_Repeat, say_something, times);\n    }\n    double lucky_number() override { PYBIND11_OVERRIDE(double, B_Repeat, lucky_number, ); }\n};\nclass PyC_Repeat : public C_Repeat {\npublic:\n    using C_Repeat::C_Repeat;\n    int unlucky_number() override { PYBIND11_OVERRIDE(int, C_Repeat, unlucky_number, ); }\n    std::string say_something(unsigned times) override {\n        PYBIND11_OVERRIDE(std::string, C_Repeat, say_something, times);\n    }\n    double lucky_number() override { PYBIND11_OVERRIDE(double, C_Repeat, lucky_number, ); }\n};\nclass PyD_Repeat : public D_Repeat {\npublic:\n    using D_Repeat::D_Repeat;\n    int unlucky_number() override { PYBIND11_OVERRIDE(int, D_Repeat, unlucky_number, ); }\n    std::string say_something(unsigned times) override {\n        PYBIND11_OVERRIDE(std::string, D_Repeat, say_something, times);\n    }\n    double lucky_number() override { PYBIND11_OVERRIDE(double, D_Repeat, lucky_number, ); }\n};\n\n// Inheritance approach 2: templated trampoline classes.\n//\n// Advantages:\n// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one\n//   for any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes\n//   and 11 methods (repeat).\n// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and\n//   can properly inherit constructors.\n//\n// Disadvantage:\n// - the compiler must still generate and compile 14 different methods (more, even, than the 11\n//   required for the repeat approach) instead of the 6 required for MI.  (If there was no pure\n//   method (or no pure method override), the number would drop down to the same 11 as the repeat\n//   approach).\ntemplate <class Base = A_Tpl>\nclass PyA_Tpl : public Base {\npublic:\n    using Base::Base; // Inherit constructors\n    int unlucky_number() override { PYBIND11_OVERRIDE_PURE(int, Base, unlucky_number, ); }\n    std::string say_something(unsigned times) override {\n        PYBIND11_OVERRIDE(std::string, Base, say_something, times);\n    }\n};\ntemplate <class Base = B_Tpl>\nclass PyB_Tpl : public PyA_Tpl<Base> {\npublic:\n    using PyA_Tpl<Base>::PyA_Tpl; // Inherit constructors (via PyA_Tpl's inherited constructors)\n    // NOLINTNEXTLINE(bugprone-parent-virtual-call)\n    int unlucky_number() override { PYBIND11_OVERRIDE(int, Base, unlucky_number, ); }\n    double lucky_number() override { PYBIND11_OVERRIDE(double, Base, lucky_number, ); }\n};\n// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these\n// (we can use PyB_Tpl<C_Tpl> and PyB_Tpl<D_Tpl> for the trampoline classes instead):\n/*\ntemplate <class Base = C_Tpl> class PyC_Tpl : public PyB_Tpl<Base> {\npublic:\n    using PyB_Tpl<Base>::PyB_Tpl;\n};\ntemplate <class Base = D_Tpl> class PyD_Tpl : public PyC_Tpl<Base> {\npublic:\n    using PyC_Tpl<Base>::PyC_Tpl;\n};\n*/\n\nvoid initialize_inherited_virtuals(py::module_ &m) {\n    // test_inherited_virtuals\n\n    // Method 1: repeat\n    py::class_<A_Repeat, PyA_Repeat>(m, \"A_Repeat\")\n        .def(py::init<>())\n        .def(\"unlucky_number\", &A_Repeat::unlucky_number)\n        .def(\"say_something\", &A_Repeat::say_something)\n        .def(\"say_everything\", &A_Repeat::say_everything);\n    py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, \"B_Repeat\")\n        .def(py::init<>())\n        .def(\"lucky_number\", &B_Repeat::lucky_number);\n    py::class_<C_Repeat, B_Repeat, PyC_Repeat>(m, \"C_Repeat\").def(py::init<>());\n    py::class_<D_Repeat, C_Repeat, PyD_Repeat>(m, \"D_Repeat\").def(py::init<>());\n\n    // test_\n    // Method 2: Templated trampolines\n    py::class_<A_Tpl, PyA_Tpl<>>(m, \"A_Tpl\")\n        .def(py::init<>())\n        .def(\"unlucky_number\", &A_Tpl::unlucky_number)\n        .def(\"say_something\", &A_Tpl::say_something)\n        .def(\"say_everything\", &A_Tpl::say_everything);\n    py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, \"B_Tpl\")\n        .def(py::init<>())\n        .def(\"lucky_number\", &B_Tpl::lucky_number);\n    py::class_<C_Tpl, B_Tpl, PyB_Tpl<C_Tpl>>(m, \"C_Tpl\").def(py::init<>());\n    py::class_<D_Tpl, C_Tpl, PyB_Tpl<D_Tpl>>(m, \"D_Tpl\").def(py::init<>());\n\n    // Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)\n    m.def(\"test_gil\", &test_gil);\n    m.def(\"test_gil_from_thread\", &test_gil_from_thread);\n}\n"
  },
  {
    "path": "tests/test_virtual_functions.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nimport pytest\n\nimport env\n\nm = pytest.importorskip(\"pybind11_tests.virtual_functions\")\nfrom pybind11_tests import ConstructorStats  # noqa: E402\n\n\ndef test_override(capture, msg):\n    class ExtendedExampleVirt(m.ExampleVirt):\n        def __init__(self, state):\n            super().__init__(state + 1)\n            self.data = \"Hello world\"\n\n        def run(self, value):\n            print(f\"ExtendedExampleVirt::run({value}), calling parent..\")\n            return super().run(value + 1)\n\n        def run_bool(self):\n            print(\"ExtendedExampleVirt::run_bool()\")\n            return False\n\n        def get_string1(self):\n            return \"override1\"\n\n        def pure_virtual(self):\n            print(f\"ExtendedExampleVirt::pure_virtual(): {self.data}\")\n\n    class ExtendedExampleVirt2(ExtendedExampleVirt):\n        def __init__(self, state):\n            super().__init__(state + 1)\n\n        def get_string2(self):\n            return \"override2\"\n\n    ex12 = m.ExampleVirt(10)\n    with capture:\n        assert m.runExampleVirt(ex12, 20) == 30\n    assert (\n        capture\n        == \"\"\"\n        Original implementation of ExampleVirt::run(state=10, value=20, str1=default1, str2=default2)\n    \"\"\"\n    )\n\n    with pytest.raises(RuntimeError) as excinfo:\n        m.runExampleVirtVirtual(ex12)\n    assert (\n        msg(excinfo.value)\n        == 'Tried to call pure virtual function \"ExampleVirt::pure_virtual\"'\n    )\n\n    ex12p = ExtendedExampleVirt(10)\n    with capture:\n        assert m.runExampleVirt(ex12p, 20) == 32\n    assert (\n        capture\n        == \"\"\"\n        ExtendedExampleVirt::run(20), calling parent..\n        Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)\n    \"\"\"\n    )\n    with capture:\n        assert m.runExampleVirtBool(ex12p) is False\n    assert capture == \"ExtendedExampleVirt::run_bool()\"\n    with capture:\n        m.runExampleVirtVirtual(ex12p)\n    assert capture == \"ExtendedExampleVirt::pure_virtual(): Hello world\"\n\n    ex12p2 = ExtendedExampleVirt2(15)\n    with capture:\n        assert m.runExampleVirt(ex12p2, 50) == 68\n    assert (\n        capture\n        == \"\"\"\n        ExtendedExampleVirt::run(50), calling parent..\n        Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)\n    \"\"\"\n    )\n\n    if env.GRAALPY:\n        pytest.skip(\"ConstructorStats is incompatible with GraalPy.\")\n\n    cstats = ConstructorStats.get(m.ExampleVirt)\n    assert cstats.alive() == 3\n    del ex12, ex12p, ex12p2\n    assert cstats.alive() == 0\n    assert cstats.values() == [\"10\", \"11\", \"17\"]\n    assert cstats.copy_constructions == 0\n    assert cstats.move_constructions >= 0\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_alias_delay_initialization1(capture):\n    \"\"\"`A` only initializes its trampoline class when we inherit from it\n\n    If we just create and use an A instance directly, the trampoline initialization is\n    bypassed and we only initialize an A() instead (for performance reasons).\n    \"\"\"\n\n    class B(m.A):\n        def __init__(self):\n            super().__init__()\n\n        def f(self):\n            print(\"In python f()\")\n\n    # C++ version\n    with capture:\n        a = m.A()\n        m.call_f(a)\n        del a\n        pytest.gc_collect()\n    assert capture == \"A.f()\"\n\n    # Python version\n    with capture:\n        b = B()\n        m.call_f(b)\n        del b\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        PyA.PyA()\n        PyA.f()\n        In python f()\n        PyA.~PyA()\n    \"\"\"\n    )\n\n\n@pytest.mark.skipif(\"env.GRAALPY\", reason=\"Cannot reliably trigger GC\")\ndef test_alias_delay_initialization2(capture):\n    \"\"\"`A2`, unlike the above, is configured to always initialize the alias\n\n    While the extra initialization and extra class layer has small virtual dispatch\n    performance penalty, it also allows us to do more things with the trampoline\n    class such as defining local variables and performing construction/destruction.\n    \"\"\"\n\n    class B2(m.A2):\n        def __init__(self):\n            super().__init__()\n\n        def f(self):\n            print(\"In python B2.f()\")\n\n    # No python subclass version\n    with capture:\n        a2 = m.A2()\n        m.call_f(a2)\n        del a2\n        pytest.gc_collect()\n        a3 = m.A2(1)\n        m.call_f(a3)\n        del a3\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        PyA2.PyA2()\n        PyA2.f()\n        A2.f()\n        PyA2.~PyA2()\n        PyA2.PyA2()\n        PyA2.f()\n        A2.f()\n        PyA2.~PyA2()\n    \"\"\"\n    )\n\n    # Python subclass version\n    with capture:\n        b2 = B2()\n        m.call_f(b2)\n        del b2\n        pytest.gc_collect()\n    assert (\n        capture\n        == \"\"\"\n        PyA2.PyA2()\n        PyA2.f()\n        In python B2.f()\n        PyA2.~PyA2()\n    \"\"\"\n    )\n\n\n# PyPy: Reference count > 1 causes call with noncopyable instance\n# to fail in ncv1.print_nc()\n@pytest.mark.xfail(\"env.PYPY or env.GRAALPY\")\n@pytest.mark.skipif(\n    not hasattr(m, \"NCVirt\"), reason=\"NCVirt does not work on Intel/PGI/NVCC compilers\"\n)\ndef test_move_support():\n    class NCVirtExt(m.NCVirt):\n        def get_noncopyable(self, a, b):\n            # Constructs and returns a new instance:\n            return m.NonCopyable(a * a, b * b)\n\n        def get_movable(self, a, b):\n            # Return a referenced copy\n            self.movable = m.Movable(a, b)\n            return self.movable\n\n    class NCVirtExt2(m.NCVirt):\n        def get_noncopyable(self, a, b):\n            # Keep a reference: this is going to throw an exception\n            self.nc = m.NonCopyable(a, b)\n            return self.nc\n\n        def get_movable(self, a, b):\n            # Return a new instance without storing it\n            return m.Movable(a, b)\n\n    ncv1 = NCVirtExt()\n    assert ncv1.print_nc(2, 3) == \"36\"\n    assert ncv1.print_movable(4, 5) == \"9\"\n    ncv2 = NCVirtExt2()\n    assert ncv2.print_movable(7, 7) == \"14\"\n    # Don't check the exception message here because it differs under debug/non-debug mode\n    with pytest.raises(RuntimeError):\n        ncv2.print_nc(9, 9)\n\n    nc_stats = ConstructorStats.get(m.NonCopyable)\n    mv_stats = ConstructorStats.get(m.Movable)\n    assert nc_stats.alive() == 1\n    assert mv_stats.alive() == 1\n    del ncv1, ncv2\n    assert nc_stats.alive() == 0\n    assert mv_stats.alive() == 0\n    assert nc_stats.values() == [\"4\", \"9\", \"9\", \"9\"]\n    assert mv_stats.values() == [\"4\", \"5\", \"7\", \"7\"]\n    assert nc_stats.copy_constructions == 0\n    assert mv_stats.copy_constructions == 1\n    assert nc_stats.move_constructions >= 0\n    assert mv_stats.move_constructions >= 0\n\n\ndef test_dispatch_issue(msg):\n    \"\"\"#159: virtual function dispatch has problems with similar-named functions\"\"\"\n\n    class PyClass1(m.DispatchIssue):\n        def dispatch(self):\n            return \"Yay..\"\n\n    class PyClass2(m.DispatchIssue):\n        def dispatch(self):\n            with pytest.raises(RuntimeError) as excinfo:\n                super().dispatch()\n            assert (\n                msg(excinfo.value)\n                == 'Tried to call pure virtual function \"Base::dispatch\"'\n            )\n\n            return m.dispatch_issue_go(PyClass1())\n\n    b = PyClass2()\n    assert m.dispatch_issue_go(b) == \"Yay..\"\n\n\ndef test_recursive_dispatch_issue():\n    \"\"\"#3357: Recursive dispatch fails to find python function override\"\"\"\n\n    class Data(m.Data):\n        def __init__(self, value):\n            super().__init__()\n            self.value = value\n\n    class Adder(m.Adder):\n        def __call__(self, first, second, visitor):\n            # lambda is a workaround, which adds extra frame to the\n            # current CPython thread. Removing lambda reveals the bug\n            # [https://github.com/pybind/pybind11/issues/3357]\n            (lambda: visitor(Data(first.value + second.value)))()  # noqa: PLC3002\n\n    class StoreResultVisitor:\n        def __init__(self):\n            self.result = None\n\n        def __call__(self, data):\n            self.result = data.value\n\n    store = StoreResultVisitor()\n\n    m.add2(Data(1), Data(2), Adder(), store)\n    assert store.result == 3\n\n    # without lambda in Adder class, this function fails with\n    # RuntimeError: Tried to call pure virtual function \"AdderBase::__call__\"\n    m.add3(Data(1), Data(2), Data(3), Adder(), store)\n    assert store.result == 6\n\n\ndef test_override_ref():\n    \"\"\"#392/397: overriding reference-returning functions\"\"\"\n    o = m.OverrideTest(\"asdf\")\n\n    # Not allowed (see associated .cpp comment)\n    # i = o.str_ref()\n    # assert o.str_ref() == \"asdf\"\n    assert o.str_value() == \"asdf\"\n\n    assert o.A_value().value == \"hi\"\n    a = o.A_ref()\n    assert a.value == \"hi\"\n    a.value = \"bye\"\n    assert a.value == \"bye\"\n\n\ndef test_inherited_virtuals():\n    class AR(m.A_Repeat):\n        def unlucky_number(self):\n            return 99\n\n    class AT(m.A_Tpl):\n        def unlucky_number(self):\n            return 999\n\n    obj = AR()\n    assert obj.say_something(3) == \"hihihi\"\n    assert obj.unlucky_number() == 99\n    assert obj.say_everything() == \"hi 99\"\n\n    obj = AT()\n    assert obj.say_something(3) == \"hihihi\"\n    assert obj.unlucky_number() == 999\n    assert obj.say_everything() == \"hi 999\"\n\n    for obj in [m.B_Repeat(), m.B_Tpl()]:\n        assert obj.say_something(3) == \"B says hi 3 times\"\n        assert obj.unlucky_number() == 13\n        assert obj.lucky_number() == 7.0\n        assert obj.say_everything() == \"B says hi 1 times 13\"\n\n    for obj in [m.C_Repeat(), m.C_Tpl()]:\n        assert obj.say_something(3) == \"B says hi 3 times\"\n        assert obj.unlucky_number() == 4444\n        assert obj.lucky_number() == 888.0\n        assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    class CR(m.C_Repeat):\n        def lucky_number(self):\n            return m.C_Repeat.lucky_number(self) + 1.25\n\n    obj = CR()\n    assert obj.say_something(3) == \"B says hi 3 times\"\n    assert obj.unlucky_number() == 4444\n    assert obj.lucky_number() == 889.25\n    assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    class CT(m.C_Tpl):\n        pass\n\n    obj = CT()\n    assert obj.say_something(3) == \"B says hi 3 times\"\n    assert obj.unlucky_number() == 4444\n    assert obj.lucky_number() == 888.0\n    assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    class CCR(CR):\n        def lucky_number(self):\n            return CR.lucky_number(self) * 10\n\n    obj = CCR()\n    assert obj.say_something(3) == \"B says hi 3 times\"\n    assert obj.unlucky_number() == 4444\n    assert obj.lucky_number() == 8892.5\n    assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    class CCT(CT):\n        def lucky_number(self):\n            return CT.lucky_number(self) * 1000\n\n    obj = CCT()\n    assert obj.say_something(3) == \"B says hi 3 times\"\n    assert obj.unlucky_number() == 4444\n    assert obj.lucky_number() == 888000.0\n    assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    class DR(m.D_Repeat):\n        def unlucky_number(self):\n            return 123\n\n        def lucky_number(self):\n            return 42.0\n\n    for obj in [m.D_Repeat(), m.D_Tpl()]:\n        assert obj.say_something(3) == \"B says hi 3 times\"\n        assert obj.unlucky_number() == 4444\n        assert obj.lucky_number() == 888.0\n        assert obj.say_everything() == \"B says hi 1 times 4444\"\n\n    obj = DR()\n    assert obj.say_something(3) == \"B says hi 3 times\"\n    assert obj.unlucky_number() == 123\n    assert obj.lucky_number() == 42.0\n    assert obj.say_everything() == \"B says hi 1 times 123\"\n\n    class DT(m.D_Tpl):\n        def say_something(self, times):\n            return \"DT says:\" + (\" quack\" * times)\n\n        def unlucky_number(self):\n            return 1234\n\n        def lucky_number(self):\n            return -4.25\n\n    obj = DT()\n    assert obj.say_something(3) == \"DT says: quack quack quack\"\n    assert obj.unlucky_number() == 1234\n    assert obj.lucky_number() == -4.25\n    assert obj.say_everything() == \"DT says: quack 1234\"\n\n    class DT2(DT):\n        def say_something(self, times):\n            return \"DT2: \" + (\"QUACK\" * times)\n\n        def unlucky_number(self):\n            return -3\n\n    class BT(m.B_Tpl):\n        def say_something(self, times):\n            return \"BT\" * times\n\n        def unlucky_number(self):\n            return -7\n\n        def lucky_number(self):\n            return -1.375\n\n    obj = BT()\n    assert obj.say_something(3) == \"BTBTBT\"\n    assert obj.unlucky_number() == -7\n    assert obj.lucky_number() == -1.375\n    assert obj.say_everything() == \"BT -7\"\n\n\n@pytest.mark.skipif(sys.platform.startswith(\"emscripten\"), reason=\"Requires threads\")\ndef test_issue_1454():\n    # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)\n    m.test_gil()\n    m.test_gil_from_thread()\n\n\ndef test_python_override():\n    def func():\n        class Test(m.test_override_cache_helper):\n            def func(self):\n                return 42\n\n        return Test()\n\n    def func2():\n        class Test(m.test_override_cache_helper):\n            pass\n\n        return Test()\n\n    for _ in range(1500):\n        assert m.test_override_cache(func()) == 42\n        assert m.test_override_cache(func2()) == 0\n"
  },
  {
    "path": "tests/test_warnings.cpp",
    "content": "/*\n    tests/test_warnings.cpp -- usage of warnings::warn() and warnings categories.\n\n    Copyright (c) 2024 Jan Iwaszkiewicz <jiwaszkiewicz6@gmail.com>\n\n    All rights reserved. Use of this source code is governed by a\n    BSD-style license that can be found in the LICENSE file.\n*/\n\n#include <pybind11/warnings.h>\n\n#include \"pybind11_tests.h\"\n\n#include <utility>\n\nTEST_SUBMODULE(warnings_, m) {\n\n    // Test warning mechanism base\n    m.def(\"warn_and_return_value\", []() {\n        std::string message = \"This is simple warning\";\n        py::warnings::warn(message.c_str(), PyExc_Warning);\n        return 21;\n    });\n\n    m.def(\"warn_with_default_category\", []() { py::warnings::warn(\"This is RuntimeWarning\"); });\n\n    m.def(\"warn_with_different_category\",\n          []() { py::warnings::warn(\"This is FutureWarning\", PyExc_FutureWarning); });\n\n    m.def(\"warn_with_invalid_category\",\n          []() { py::warnings::warn(\"Invalid category\", PyExc_Exception); });\n\n    // Test custom warnings\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> ex_storage;\n    ex_storage.call_once_and_store_result([&]() {\n        return py::warnings::new_warning_type(m, \"CustomWarning\", PyExc_DeprecationWarning);\n    });\n\n    m.def(\"warn_with_custom_type\", []() {\n        py::warnings::warn(\"This is CustomWarning\", ex_storage.get_stored());\n        return 37;\n    });\n\n    m.def(\"register_duplicate_warning\",\n          [m]() { py::warnings::new_warning_type(m, \"CustomWarning\", PyExc_RuntimeWarning); });\n}\n"
  },
  {
    "path": "tests/test_warnings.py",
    "content": "from __future__ import annotations\n\nimport warnings\n\nimport pytest\n\nimport pybind11_tests  # noqa: F401\nfrom pybind11_tests import warnings_ as m\n\n\n@pytest.mark.parametrize(\n    (\"expected_category\", \"expected_message\", \"expected_value\", \"module_function\"),\n    [\n        (Warning, \"This is simple warning\", 21, m.warn_and_return_value),\n        (RuntimeWarning, \"This is RuntimeWarning\", None, m.warn_with_default_category),\n        (FutureWarning, \"This is FutureWarning\", None, m.warn_with_different_category),\n    ],\n)\ndef test_warning_simple(\n    expected_category, expected_message, expected_value, module_function\n):\n    with pytest.warns(Warning, match=\"This is\") as excinfo:\n        value = module_function()\n\n    assert issubclass(excinfo[0].category, expected_category)\n    assert str(excinfo[0].message) == expected_message\n    assert value == expected_value\n\n\ndef test_warning_wrong_subclass_fail():\n    with pytest.raises(Exception) as excinfo:\n        m.warn_with_invalid_category()\n\n    assert issubclass(excinfo.type, RuntimeError)\n    assert (\n        str(excinfo.value)\n        == \"pybind11::warnings::warn(): cannot raise warning, category must be a subclass of PyExc_Warning!\"\n    )\n\n\ndef test_warning_double_register_fail():\n    with pytest.raises(Exception) as excinfo:\n        m.register_duplicate_warning()\n\n    assert issubclass(excinfo.type, RuntimeError)\n    assert (\n        str(excinfo.value)\n        == 'pybind11::warnings::new_warning_type(): an attribute with name \"CustomWarning\" exists already.'\n    )\n\n\ndef test_warning_register():\n    assert m.CustomWarning is not None\n\n    with pytest.warns(m.CustomWarning) as excinfo:\n        warnings.warn(\"This is warning from Python!\", m.CustomWarning, stacklevel=1)\n\n    assert issubclass(excinfo[0].category, DeprecationWarning)\n    assert str(excinfo[0].message) == \"This is warning from Python!\"\n\n\ndef test_warning_custom():\n    with pytest.warns(m.CustomWarning) as excinfo:\n        value = m.warn_with_custom_type()\n\n    assert issubclass(excinfo[0].category, DeprecationWarning)\n    assert str(excinfo[0].message) == \"This is CustomWarning\"\n    assert value == 37\n"
  },
  {
    "path": "tests/test_with_catch/CMakeLists.txt",
    "content": "possibly_uninitialized(PYTHON_MODULE_EXTENSION Python_INTERPRETER_ID)\n\nif(\"${PYTHON_MODULE_EXTENSION}\" MATCHES \"pypy\"\n   OR \"${Python_INTERPRETER_ID}\" STREQUAL \"PyPy\"\n   OR \"${PYTHON_MODULE_EXTENSION}\" MATCHES \"graalpy\")\n  message(STATUS \"Skipping embed test on PyPy or GraalPy\")\n  add_custom_target(cpptest) # Dummy target on PyPy or GraalPy. Embedding is not supported.\n  set(_suppress_unused_variable_warning \"${DOWNLOAD_CATCH}\")\n  return()\nendif()\n\nif(TARGET Python::Module AND NOT TARGET Python::Python)\n  message(STATUS \"Skipping embed test since no embed libs found\")\n  add_custom_target(cpptest) # Dummy target since embedding is not supported.\n  set(_suppress_unused_variable_warning \"${DOWNLOAD_CATCH}\")\n  return()\nendif()\n\nfind_package(Catch 2.13.10)\n\nif(CATCH_FOUND)\n  message(STATUS \"Building interpreter tests using Catch v${CATCH_VERSION}\")\nelse()\n  message(STATUS \"Catch not detected. Interpreter tests will be skipped. Install Catch headers\"\n                 \" manually or use `cmake -DDOWNLOAD_CATCH=ON` to fetch them automatically.\")\n  return()\nendif()\n\nfind_package(Threads REQUIRED)\n\nif(PYBIND11_TEST_SMART_HOLDER)\n  add_compile_definitions(\n    -DPYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE)\nendif()\n\nadd_executable(test_with_catch catch.cpp test_args_convert_vector.cpp test_argument_vector.cpp\n                               test_interpreter.cpp test_subinterpreter.cpp)\npybind11_enable_warnings(test_with_catch)\n\ntarget_link_libraries(test_with_catch PRIVATE pybind11::embed Catch2::Catch2 Threads::Threads)\n\nif(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)\n  file(COPY test_interpreter.py test_trampoline.py DESTINATION \"${CMAKE_CURRENT_BINARY_DIR}\")\nendif()\n\nadd_custom_target(\n  cpptest\n  COMMAND \"$<TARGET_FILE:test_with_catch>\"\n  DEPENDS test_with_catch\n  WORKING_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}\"\n  USES_TERMINAL # Ensures output is shown immediately (not buffered and possibly lost on crash)\n)\n\npybind11_add_module(external_module THIN_LTO external_module.cpp)\nset_target_properties(external_module PROPERTIES LIBRARY_OUTPUT_DIRECTORY\n                                                 \"${CMAKE_CURRENT_BINARY_DIR}\")\nforeach(config ${CMAKE_CONFIGURATION_TYPES})\n  string(TOUPPER ${config} config)\n  set_target_properties(external_module PROPERTIES LIBRARY_OUTPUT_DIRECTORY_${config}\n                                                   \"${CMAKE_CURRENT_BINARY_DIR}\")\nendforeach()\nadd_dependencies(cpptest external_module)\n\nadd_dependencies(check cpptest)\n"
  },
  {
    "path": "tests/test_with_catch/catch.cpp",
    "content": "// The Catch implementation is compiled here. This is a standalone\n// translation unit to avoid recompiling it for every test change.\n\n#include <pybind11/embed.h>\n\n#include <chrono>\n#include <csignal>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <sstream>\n\n#ifndef _WIN32\n#    include <unistd.h>\n#endif\n\n// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to\n// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).\nPYBIND11_WARNING_DISABLE_MSVC(4996)\n\n// Catch uses _ internally, which breaks gettext style defines\n#ifdef _\n#    undef _\n#endif\n\n#define CATCH_CONFIG_RUNNER\n#define CATCH_CONFIG_DEFAULT_REPORTER \"progress\"\n#include \"catch_skip.h\"\n\n#include <catch.hpp>\n\nnamespace py = pybind11;\n\n// Simple progress reporter that prints a line per test case.\nnamespace {\n\nclass ProgressReporter : public Catch::StreamingReporterBase<ProgressReporter> {\npublic:\n    using StreamingReporterBase<ProgressReporter>::StreamingReporterBase;\n\n    static std::string getDescription() { return \"Simple progress reporter (one line per test)\"; }\n\n    void testCaseStarting(Catch::TestCaseInfo const &testInfo) override {\n        print_python_version_once();\n        auto &os = Catch::cout();\n        os << \"[ RUN      ] \" << testInfo.name << '\\n';\n        os.flush();\n    }\n\n    void testCaseEnded(Catch::TestCaseStats const &stats) override {\n        bool failed = stats.totals.assertions.failed > 0;\n        auto &os = Catch::cout();\n        os << (failed ? \"[  FAILED  ] \" : \"[       OK ] \") << stats.testInfo.name << '\\n';\n        os.flush();\n    }\n\n    void noMatchingTestCases(std::string const &spec) override {\n        auto &os = Catch::cout();\n        os << \"[  NO TEST ] no matching test cases for spec: \" << spec << '\\n';\n        os.flush();\n    }\n\n    void reportInvalidArguments(std::string const &arg) override {\n        auto &os = Catch::cout();\n        os << \"[   ERROR  ] invalid Catch2 arguments: \" << arg << '\\n';\n        os.flush();\n    }\n\n    void assertionStarting(Catch::AssertionInfo const &) override {}\n\n    bool assertionEnded(Catch::AssertionStats const &) override { return false; }\n\n    void testRunEnded(Catch::TestRunStats const &stats) override {\n        auto &os = Catch::cout();\n        auto passed = stats.totals.testCases.passed;\n        auto failed = stats.totals.testCases.failed;\n        auto total = passed + failed;\n        auto assertions = stats.totals.assertions.passed + stats.totals.assertions.failed;\n        if (failed == 0) {\n            os << \"[  PASSED  ] \" << total << \" test cases, \" << assertions << \" assertions.\\n\";\n        } else {\n            os << \"[  FAILED  ] \" << failed << \" of \" << total << \" test cases, \" << assertions\n               << \" assertions.\\n\";\n        }\n        os.flush();\n    }\n\nprivate:\n    void print_python_version_once() {\n        if (printed_) {\n            return;\n        }\n        printed_ = true;\n        auto &os = Catch::cout();\n        os << \"[ PYTHON   ] \" << Py_GetVersion() << '\\n';\n        os.flush();\n    }\n\n    bool printed_ = false;\n};\n\n} // namespace\n\nCATCH_REGISTER_REPORTER(\"progress\", ProgressReporter)\n\nnamespace {\n\nstd::string get_utc_timestamp() {\n    auto now = std::chrono::system_clock::now();\n    auto time_t_now = std::chrono::system_clock::to_time_t(now);\n    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;\n\n    std::tm utc_tm{};\n#if defined(_WIN32)\n    gmtime_s(&utc_tm, &time_t_now);\n#else\n    gmtime_r(&time_t_now, &utc_tm);\n#endif\n\n    std::ostringstream oss;\n    oss << std::put_time(&utc_tm, \"%Y-%m-%d %H:%M:%S\") << '.' << std::setfill('0') << std::setw(3)\n        << ms.count() << 'Z';\n    return oss.str();\n}\n\n#ifndef _WIN32\n// Signal handler to print a message when the process is terminated.\n// Uses only async-signal-safe functions.\nvoid termination_signal_handler(int sig) {\n    const char *msg = \"[  SIGNAL  ] Process received SIGTERM\\n\";\n    // write() is async-signal-safe, unlike std::cout\n    ssize_t written = write(STDOUT_FILENO, msg, strlen(msg));\n    (void) written; // suppress \"unused variable\" warnings\n    // Re-raise with default handler to get proper exit status\n    std::signal(sig, SIG_DFL);\n    std::raise(sig);\n}\n#endif\n\n} // namespace\n\nint main(int argc, char *argv[]) {\n#ifndef _WIN32\n    std::signal(SIGTERM, termination_signal_handler);\n#endif\n\n    // Setup for TEST_CASE in test_interpreter.cpp, tagging on a large random number:\n    std::string updated_pythonpath(\"pybind11_test_with_catch_PYTHONPATH_2099743835476552\");\n    const char *preexisting_pythonpath = getenv(\"PYTHONPATH\");\n    if (preexisting_pythonpath != nullptr) {\n#if defined(_WIN32)\n        updated_pythonpath += ';';\n#else\n        updated_pythonpath += ':';\n#endif\n        updated_pythonpath += preexisting_pythonpath;\n    }\n#if defined(_WIN32)\n    _putenv_s(\"PYTHONPATH\", updated_pythonpath.c_str());\n#else\n    setenv(\"PYTHONPATH\", updated_pythonpath.c_str(), /*replace=*/1);\n#endif\n\n    std::cout << \"[ STARTING ] \" << get_utc_timestamp() << '\\n';\n    std::cout.flush();\n\n    py::scoped_interpreter guard{};\n\n    auto result = Catch::Session().run(argc, argv);\n\n    std::cout << \"[ DONE     ] \" << get_utc_timestamp() << \" (result \" << result << \")\\n\";\n    std::cout.flush();\n\n    return result < 0xff ? result : 0xff;\n}\n"
  },
  {
    "path": "tests/test_with_catch/catch_skip.h",
    "content": "// Macro to skip a test at runtime with a visible message.\n// Catch2 v2 doesn't have native skip support (v3 does with SKIP()).\n// The test will count as \"passed\" in totals, but the output clearly shows it was skipped.\n\n#pragma once\n\n#include <catch.hpp>\n\n#define PYBIND11_CATCH2_SKIP_IF(condition, reason)                                                \\\n    do {                                                                                          \\\n        if (condition) {                                                                          \\\n            Catch::cout() << \"[ SKIPPED  ] \" << (reason) << '\\n';                                 \\\n            Catch::cout().flush();                                                                \\\n            return;                                                                               \\\n        }                                                                                         \\\n    } while (0)\n"
  },
  {
    "path": "tests/test_with_catch/external_module.cpp",
    "content": "#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\n/* Simple test module/test class to check that the referenced internals data of external pybind11\n * modules aren't preserved over a finalize/initialize.\n */\n\nnamespace {\n// Compare unsafe_reset_internals_for_single_interpreter in\n// test_subinterpreter.cpp.\nvoid unsafe_reset_local_internals() {\n    // NOTE: This code is NOT SAFE unless the caller guarantees no other threads are alive\n    // NOTE: This code is tied to the precise implementation of the internals holder\n\n    py::detail::get_local_internals_pp_manager().unref();\n    py::detail::get_local_internals();\n}\n} // namespace\n\nPYBIND11_MODULE(external_module,\n                m,\n                py::mod_gil_not_used(),\n                py::multiple_interpreters::per_interpreter_gil()) {\n    // At least one test (\"Single Subinterpreter\") wants to reset\n    // internals. We have separate local internals because we are a\n    // separate DSO, so ours need to be reset too!\n    unsafe_reset_local_internals();\n    class A {\n    public:\n        explicit A(int value) : v{value} {};\n        int v;\n    };\n\n    py::class_<A>(m, \"A\").def(py::init<int>()).def_readwrite(\"value\", &A::v);\n\n    m.def(\"internals_at\",\n          []() { return reinterpret_cast<uintptr_t>(&py::detail::get_internals()); });\n}\n"
  },
  {
    "path": "tests/test_with_catch/test_args_convert_vector.cpp",
    "content": "#include \"pybind11/pybind11.h\"\n#include \"catch.hpp\"\n\nnamespace py = pybind11;\n\nusing args_convert_vector = py::detail::args_convert_vector<py::detail::arg_vector_small_size>;\n\nnamespace {\ntemplate <typename Container>\nstd::vector<Container> get_sample_vectors() {\n    std::vector<Container> result;\n    result.emplace_back();\n    for (const auto sz : {0, 4, 5, 6, 31, 32, 33, 63, 64, 65}) {\n        for (const bool b : {false, true}) {\n            result.emplace_back(static_cast<std::size_t>(sz), b);\n        }\n    }\n    return result;\n}\n\nvoid require_vector_matches_sample(const args_convert_vector &actual,\n                                   const std::vector<bool> &expected) {\n    REQUIRE(actual.size() == expected.size());\n    for (size_t ii = 0; ii < actual.size(); ++ii) {\n        REQUIRE(actual[ii] == expected[ii]);\n    }\n}\n\ntemplate <typename ActualMutationFunc, typename ExpectedMutationFunc>\nvoid mutation_test_with_samples(ActualMutationFunc actual_mutation_func,\n                                ExpectedMutationFunc expected_mutation_func) {\n    auto sample_contents = get_sample_vectors<std::vector<bool>>();\n    auto samples = get_sample_vectors<args_convert_vector>();\n    for (size_t ii = 0; ii < samples.size(); ++ii) {\n        auto &actual = samples[ii];\n        auto &expected = sample_contents[ii];\n\n        actual_mutation_func(actual);\n        expected_mutation_func(expected);\n        require_vector_matches_sample(actual, expected);\n    }\n}\n} // namespace\n\n// I would like to write [capture](auto& vec) block inline, but we\n// have to work with C++11, which doesn't have generic lambdas.\n// NOLINTBEGIN(bugprone-macro-parentheses)\n#define MUTATION_LAMBDA(capture, block)                                                           \\\n    [capture](args_convert_vector & vec) block, [capture](std::vector<bool> & vec) block\n// NOLINTEND(bugprone-macro-parentheses)\n\n// For readability, rather than having ugly empty arguments.\n#define NO_CAPTURE\n\nTEST_CASE(\"check sample args_convert_vector contents\") {\n    mutation_test_with_samples(MUTATION_LAMBDA(NO_CAPTURE, { (void) vec; }));\n}\n\nTEST_CASE(\"args_convert_vector push_back\") {\n    for (const bool b : {false, true}) {\n        mutation_test_with_samples(MUTATION_LAMBDA(b, { vec.push_back(b); }));\n    }\n}\n\nTEST_CASE(\"args_convert_vector reserve\") {\n    for (std::size_t ii = 0; ii < 4; ++ii) {\n        mutation_test_with_samples(MUTATION_LAMBDA(ii, { vec.reserve(ii); }));\n    }\n}\n\nTEST_CASE(\"args_convert_vector reserve then push_back\") {\n    for (std::size_t ii = 0; ii < 4; ++ii) {\n        for (const bool b : {false, true}) {\n            mutation_test_with_samples(MUTATION_LAMBDA(=, {\n                vec.reserve(ii);\n                vec.push_back(b);\n            }));\n        }\n    }\n}\n"
  },
  {
    "path": "tests/test_with_catch/test_argument_vector.cpp",
    "content": "#include \"pybind11/pybind11.h\"\n#include \"catch.hpp\"\n\nnamespace py = pybind11;\n\n// 2 is chosen because it is the smallest number (keeping tests short)\n// where we can create non-empty vectors whose size is the inline size\n// plus or minus 1.\nusing argument_vector = py::detail::argument_vector<2>;\n\nnamespace {\nargument_vector to_argument_vector(const std::vector<py::handle> &v) {\n    argument_vector result;\n    result.reserve(v.size());\n    for (const auto x : v) {\n        result.push_back(x);\n    }\n    return result;\n}\n\nstd::vector<std::vector<py::handle>> get_sample_argument_vector_contents() {\n    return std::vector<std::vector<py::handle>>{\n        {},\n        {py::handle(Py_None)},\n        {py::handle(Py_None), py::handle(Py_False)},\n        {py::handle(Py_None), py::handle(Py_False), py::handle(Py_True)},\n    };\n}\n\nstd::vector<argument_vector> get_sample_argument_vectors() {\n    std::vector<argument_vector> result;\n    for (const auto &vec : get_sample_argument_vector_contents()) {\n        result.push_back(to_argument_vector(vec));\n    }\n    return result;\n}\n\nvoid require_vector_matches_sample(const argument_vector &actual,\n                                   const std::vector<py::handle> &expected) {\n    REQUIRE(actual.size() == expected.size());\n    for (size_t ii = 0; ii < actual.size(); ++ii) {\n        REQUIRE(actual[ii].ptr() == expected[ii].ptr());\n    }\n}\n\ntemplate <typename ActualMutationFunc, typename ExpectedMutationFunc>\nvoid mutation_test_with_samples(ActualMutationFunc actual_mutation_func,\n                                ExpectedMutationFunc expected_mutation_func) {\n    auto sample_contents = get_sample_argument_vector_contents();\n    auto samples = get_sample_argument_vectors();\n    for (size_t ii = 0; ii < samples.size(); ++ii) {\n        auto &actual = samples[ii];\n        auto &expected = sample_contents[ii];\n\n        actual_mutation_func(actual);\n        expected_mutation_func(expected);\n        require_vector_matches_sample(actual, expected);\n    }\n}\n\n} // namespace\n\n// I would like to write [capture](auto& vec) block inline, but we\n// have to work with C++11, which doesn't have generic lambdas.\n// NOLINTBEGIN(bugprone-macro-parentheses)\n#define MUTATION_LAMBDA(capture, block)                                                           \\\n    [capture](argument_vector & vec) block, [capture](std::vector<py::handle> & vec) block\n// NOLINTEND(bugprone-macro-parentheses)\n\n// For readability, rather than having ugly empty arguments.\n#define NO_CAPTURE\n\nTEST_CASE(\"check sample argument_vector contents\") {\n    mutation_test_with_samples(MUTATION_LAMBDA(NO_CAPTURE, { (void) vec; }));\n}\n\nTEST_CASE(\"argument_vector push_back\") {\n    mutation_test_with_samples(MUTATION_LAMBDA(NO_CAPTURE, { vec.emplace_back(Py_None); }));\n}\n\nTEST_CASE(\"argument_vector reserve\") {\n    for (std::size_t ii = 0; ii < 4; ++ii) {\n        mutation_test_with_samples(MUTATION_LAMBDA(ii, { vec.reserve(ii); }));\n    }\n}\n\nTEST_CASE(\"argument_vector reserve then push_back\") {\n    for (std::size_t ii = 0; ii < 4; ++ii) {\n        mutation_test_with_samples(MUTATION_LAMBDA(ii, {\n            vec.reserve(ii);\n            vec.emplace_back(Py_True);\n        }));\n    }\n}\n"
  },
  {
    "path": "tests/test_with_catch/test_interpreter.cpp",
    "content": "#include <pybind11/critical_section.h>\n#include <pybind11/embed.h>\n\n// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to\n// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).\nPYBIND11_WARNING_DISABLE_MSVC(4996)\n\n#include <catch.hpp>\n#include <cstdlib>\n#include <fstream>\n#include <functional>\n#include <thread>\n#include <utility>\n\nnamespace py = pybind11;\nusing namespace py::literals;\n\nsize_t get_sys_path_size() {\n    auto sys_path = py::module::import(\"sys\").attr(\"path\");\n    return py::len(sys_path);\n}\n\nbool has_state_dict_internals_obj() {\n    py::dict state = py::detail::get_python_state_dict();\n    return state.contains(PYBIND11_INTERNALS_ID);\n}\n\nuintptr_t get_details_as_uintptr() {\n    return reinterpret_cast<uintptr_t>(py::detail::get_internals_pp_manager().get_pp()->get());\n}\n\nclass Widget {\npublic:\n    explicit Widget(std::string message) : message(std::move(message)) {}\n    virtual ~Widget() = default;\n\n    std::string the_message() const { return message; }\n    virtual int the_answer() const = 0;\n    virtual std::string argv0() const = 0;\n\nprivate:\n    std::string message;\n};\n\nclass PyWidget final : public Widget {\n    using Widget::Widget;\n\n    int the_answer() const override { PYBIND11_OVERRIDE_PURE(int, Widget, the_answer); }\n    std::string argv0() const override { PYBIND11_OVERRIDE_PURE(std::string, Widget, argv0); }\n};\n\nclass test_override_cache_helper {\n\npublic:\n    virtual int func() { return 0; }\n\n    test_override_cache_helper() = default;\n    virtual ~test_override_cache_helper() = default;\n    // Non-copyable\n    test_override_cache_helper &operator=(test_override_cache_helper const &Right) = delete;\n    test_override_cache_helper(test_override_cache_helper const &Copy) = delete;\n};\n\nclass test_override_cache_helper_trampoline : public test_override_cache_helper {\n    int func() override { PYBIND11_OVERRIDE(int, test_override_cache_helper, func); }\n};\n\nPYBIND11_EMBEDDED_MODULE(widget_module, m, py::multiple_interpreters::per_interpreter_gil()) {\n    py::class_<Widget, PyWidget>(m, \"Widget\")\n        .def(py::init<std::string>())\n        .def_property_readonly(\"the_message\", &Widget::the_message);\n\n    m.def(\"add\", [](int i, int j) { return i + j; });\n\n    auto sub = m.def_submodule(\"sub\");\n    sub.def(\"add\", [](int i, int j) { return i + j; });\n}\n\nPYBIND11_EMBEDDED_MODULE(trampoline_module, m) {\n    py::class_<test_override_cache_helper,\n               test_override_cache_helper_trampoline,\n               std::shared_ptr<test_override_cache_helper>>(m, \"test_override_cache_helper\")\n        .def(py::init_alias<>())\n        .def(\"func\", &test_override_cache_helper::func);\n}\n\nPYBIND11_EMBEDDED_MODULE(throw_exception, ) { throw std::runtime_error(\"C++ Error\"); }\n\nPYBIND11_EMBEDDED_MODULE(throw_error_already_set, ) {\n    auto d = py::dict();\n    d[\"missing\"].cast<py::object>();\n}\n\nTEST_CASE(\"PYTHONPATH is used to update sys.path\") {\n    // The setup for this TEST_CASE is in catch.cpp!\n    auto sys_path = py::str(py::module_::import(\"sys\").attr(\"path\")).cast<std::string>();\n    REQUIRE_THAT(\n        sys_path,\n        Catch::Matchers::Contains(\"pybind11_test_with_catch_PYTHONPATH_2099743835476552\"));\n}\n\nTEST_CASE(\"Pass classes and data between modules defined in C++ and Python\") {\n    auto module_ = py::module_::import(\"test_interpreter\");\n    REQUIRE(py::hasattr(module_, \"DerivedWidget\"));\n\n    auto locals = py::dict(\"hello\"_a = \"Hello, World!\", \"x\"_a = 5, **module_.attr(\"__dict__\"));\n    py::exec(R\"(\n        widget = DerivedWidget(\"{} - {}\".format(hello, x))\n        message = widget.the_message\n    )\",\n             py::globals(),\n             locals);\n    REQUIRE(locals[\"message\"].cast<std::string>() == \"Hello, World! - 5\");\n\n    auto py_widget = module_.attr(\"DerivedWidget\")(\"The question\");\n    auto message = py_widget.attr(\"the_message\");\n    REQUIRE(message.cast<std::string>() == \"The question\");\n\n    const auto &cpp_widget = py_widget.cast<const Widget &>();\n    REQUIRE(cpp_widget.the_answer() == 42);\n}\n\nTEST_CASE(\"Override cache\") {\n    auto module_ = py::module_::import(\"test_trampoline\");\n    REQUIRE(py::hasattr(module_, \"func\"));\n    REQUIRE(py::hasattr(module_, \"func2\"));\n\n    auto locals = py::dict(**module_.attr(\"__dict__\"));\n\n    int i = 0;\n    for (; i < 1500; ++i) {\n        std::shared_ptr<test_override_cache_helper> p_obj;\n        std::shared_ptr<test_override_cache_helper> p_obj2;\n\n        py::object loc_inst = locals[\"func\"]();\n        p_obj = py::cast<std::shared_ptr<test_override_cache_helper>>(loc_inst);\n\n        int ret = p_obj->func();\n\n        REQUIRE(ret == 42);\n\n        loc_inst = locals[\"func2\"]();\n\n        p_obj2 = py::cast<std::shared_ptr<test_override_cache_helper>>(loc_inst);\n\n        p_obj2->func();\n    }\n}\n\nTEST_CASE(\"Import error handling\") {\n    REQUIRE_NOTHROW(py::module_::import(\"widget_module\"));\n    REQUIRE_THROWS_WITH(py::module_::import(\"throw_exception\"), \"ImportError: C++ Error\");\n    REQUIRE_THROWS_WITH(py::module_::import(\"throw_error_already_set\"),\n                        Catch::Contains(\"ImportError: initialization failed\"));\n\n    auto locals = py::dict(\"is_keyerror\"_a = false, \"message\"_a = \"not set\");\n    py::exec(R\"(\n        try:\n            import throw_error_already_set\n        except ImportError as e:\n            is_keyerror = type(e.__cause__) == KeyError\n            message = str(e.__cause__)\n    )\",\n             py::globals(),\n             locals);\n    REQUIRE(locals[\"is_keyerror\"].cast<bool>() == true);\n    REQUIRE(locals[\"message\"].cast<std::string>() == \"'missing'\");\n}\n\nTEST_CASE(\"There can be only one interpreter\") {\n    static_assert(std::is_move_constructible<py::scoped_interpreter>::value, \"\");\n    static_assert(!std::is_move_assignable<py::scoped_interpreter>::value, \"\");\n    static_assert(!std::is_copy_constructible<py::scoped_interpreter>::value, \"\");\n    static_assert(!std::is_copy_assignable<py::scoped_interpreter>::value, \"\");\n\n    REQUIRE_THROWS_WITH(py::initialize_interpreter(), \"The interpreter is already running\");\n    REQUIRE_THROWS_WITH(py::scoped_interpreter(), \"The interpreter is already running\");\n\n    py::finalize_interpreter();\n    REQUIRE_NOTHROW(py::scoped_interpreter());\n    {\n        auto pyi1 = py::scoped_interpreter();\n        auto pyi2 = std::move(pyi1);\n    }\n    py::initialize_interpreter();\n}\n\n#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\nTEST_CASE(\"Custom PyConfig\") {\n    py::finalize_interpreter();\n    PyConfig config;\n    PyConfig_InitPythonConfig(&config);\n    REQUIRE_NOTHROW(py::scoped_interpreter{&config});\n    {\n        py::scoped_interpreter p{&config};\n        REQUIRE(py::module_::import(\"widget_module\").attr(\"add\")(1, 41).cast<int>() == 42);\n    }\n    py::initialize_interpreter();\n}\n\nTEST_CASE(\"scoped_interpreter with PyConfig_InitIsolatedConfig and argv\") {\n    std::vector<std::string> path;\n    for (auto p : py::module::import(\"sys\").attr(\"path\")) {\n        path.emplace_back(py::str(p));\n    }\n\n    py::finalize_interpreter();\n    {\n        PyConfig config;\n        PyConfig_InitIsolatedConfig(&config);\n        char *argv[] = {strdup(\"a.out\")};\n        py::scoped_interpreter argv_scope{&config, 1, argv, true};\n        std::free(argv[0]);\n        // Because this config is isolated, setting the path during init will not work, we have to\n        // set it manually.  If we don't set it, then we can't import \"test_interpreter\"\n        for (auto &&p : path) {\n            py::list(py::module::import(\"sys\").attr(\"path\")).append(p);\n        }\n        try {\n            auto module = py::module::import(\"test_interpreter\");\n            auto py_widget = module.attr(\"DerivedWidget\")(\"The question\");\n            const auto &cpp_widget = py_widget.cast<const Widget &>();\n            REQUIRE(cpp_widget.argv0() == \"a.out\");\n        } catch (py::error_already_set &e) {\n            // catch here so that the exception doesn't escape the interpreter that owns it\n            FAIL(e.what());\n        }\n    }\n    py::initialize_interpreter();\n}\n\nTEST_CASE(\"scoped_interpreter with PyConfig_InitPythonConfig and argv\") {\n    py::finalize_interpreter();\n    {\n        PyConfig config;\n        PyConfig_InitPythonConfig(&config);\n\n        // `initialize_interpreter() overrides the default value for config.parse_argv (`1`) by\n        // changing it to `0`. This test exercises `scoped_interpreter` with the default config.\n        char *argv[] = {strdup(\"a.out\"), strdup(\"arg1\")};\n        py::scoped_interpreter argv_scope(&config, 2, argv);\n        std::free(argv[0]);\n        std::free(argv[1]);\n        auto module = py::module::import(\"test_interpreter\");\n        auto py_widget = module.attr(\"DerivedWidget\")(\"The question\");\n        const auto &cpp_widget = py_widget.cast<const Widget &>();\n        REQUIRE(cpp_widget.argv0() == \"arg1\");\n    }\n    py::initialize_interpreter();\n}\n#endif\n\nTEST_CASE(\"Add program dir to path pre-PyConfig\") {\n    py::finalize_interpreter();\n    size_t path_size_add_program_dir_to_path_false = 0;\n    {\n        py::scoped_interpreter scoped_interp{true, 0, nullptr, false};\n        path_size_add_program_dir_to_path_false = get_sys_path_size();\n    }\n    {\n        py::scoped_interpreter scoped_interp{};\n        REQUIRE(get_sys_path_size() == path_size_add_program_dir_to_path_false + 1);\n    }\n    py::initialize_interpreter();\n}\n\n#if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX\nTEST_CASE(\"Add program dir to path using PyConfig\") {\n    py::finalize_interpreter();\n    size_t path_size_add_program_dir_to_path_false = 0;\n    {\n        PyConfig config;\n        PyConfig_InitPythonConfig(&config);\n        py::scoped_interpreter scoped_interp{&config, 0, nullptr, false};\n        path_size_add_program_dir_to_path_false = get_sys_path_size();\n    }\n    {\n        PyConfig config;\n        PyConfig_InitPythonConfig(&config);\n        py::scoped_interpreter scoped_interp{&config};\n        REQUIRE(get_sys_path_size() == path_size_add_program_dir_to_path_false + 1);\n    }\n    py::initialize_interpreter();\n}\n#endif\n\nTEST_CASE(\"Restart the interpreter\") {\n    // Verify pre-restart state.\n    REQUIRE(py::module_::import(\"widget_module\").attr(\"add\")(1, 2).cast<int>() == 3);\n    REQUIRE(has_state_dict_internals_obj());\n    REQUIRE(py::module_::import(\"external_module\").attr(\"A\")(123).attr(\"value\").cast<int>()\n            == 123);\n\n    // local and foreign module internals should point to the same internals:\n    REQUIRE(get_details_as_uintptr()\n            == py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>());\n\n    // Restart the interpreter.\n    py::finalize_interpreter();\n    REQUIRE(Py_IsInitialized() == 0);\n\n    py::initialize_interpreter();\n    REQUIRE(Py_IsInitialized() == 1);\n\n    // Internals are deleted after a restart.\n    REQUIRE_FALSE(has_state_dict_internals_obj());\n    REQUIRE(get_details_as_uintptr() == 0);\n    pybind11::detail::get_internals();\n    REQUIRE(has_state_dict_internals_obj());\n    REQUIRE(get_details_as_uintptr() != 0);\n    REQUIRE(get_details_as_uintptr()\n            == py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>());\n\n    // Make sure that an interpreter with no get_internals() created until finalize still gets the\n    // internals destroyed\n    py::finalize_interpreter();\n    py::initialize_interpreter();\n    bool ran = false;\n    py::module_::import(\"__main__\").attr(\"internals_destroy_test\")\n        = py::capsule(&ran, [](void *ran) {\n              py::detail::get_internals();\n              REQUIRE(has_state_dict_internals_obj());\n              *static_cast<bool *>(ran) = true;\n          });\n    REQUIRE_FALSE(has_state_dict_internals_obj());\n    REQUIRE_FALSE(ran);\n    py::finalize_interpreter();\n    REQUIRE(ran);\n    py::initialize_interpreter();\n    REQUIRE_FALSE(has_state_dict_internals_obj());\n    REQUIRE(get_details_as_uintptr() == 0);\n\n    // C++ modules can be reloaded.\n    auto cpp_module = py::module_::import(\"widget_module\");\n    REQUIRE(cpp_module.attr(\"add\")(1, 2).cast<int>() == 3);\n\n    // Also verify submodules work\n    REQUIRE(cpp_module.attr(\"sub\").attr(\"add\")(1, 41).cast<int>() == 42);\n\n    // C++ type information is reloaded and can be used in python modules.\n    auto py_module = py::module_::import(\"test_interpreter\");\n    auto py_widget = py_module.attr(\"DerivedWidget\")(\"Hello after restart\");\n    REQUIRE(py_widget.attr(\"the_message\").cast<std::string>() == \"Hello after restart\");\n}\n\nTEST_CASE(\"Execution frame\") {\n    // When the interpreter is embedded, there is no execution frame, but `py::exec`\n    // should still function by using reasonable globals: `__main__.__dict__`.\n    py::exec(\"var = dict(number=42)\");\n    REQUIRE(py::globals()[\"var\"][\"number\"].cast<int>() == 42);\n}\n\nTEST_CASE(\"Threads\") {\n    // Restart interpreter to ensure threads are not initialized\n    py::finalize_interpreter();\n    py::initialize_interpreter();\n\n    constexpr auto num_threads = 10;\n    auto locals = py::dict(\"count\"_a = 0);\n\n    {\n        py::gil_scoped_release gil_release{};\n#if defined(Py_GIL_DISABLED) && PY_VERSION_HEX < 0x030E0000\n        std::mutex mutex;\n#endif\n\n        auto threads = std::vector<std::thread>();\n        for (auto i = 0; i < num_threads; ++i) {\n            threads.emplace_back([&]() {\n                py::gil_scoped_acquire gil{};\n#ifdef Py_GIL_DISABLED\n#    if PY_VERSION_HEX < 0x030E0000\n                // This will not run with the GIL, so it won't deadlock. That's\n                // because of how we run our tests. Be more careful of\n                // deadlocks if the \"free-threaded\" GIL could be enabled (at\n                // runtime).\n                std::lock_guard<std::mutex> lock(mutex);\n#    else\n                // CPython's thread-safe API in no-GIL mode.\n                py::scoped_critical_section lock(locals);\n#    endif\n#endif\n                locals[\"count\"] = locals[\"count\"].cast<int>() + 1;\n            });\n        }\n\n        for (auto &thread : threads) {\n            thread.join();\n        }\n    }\n\n    REQUIRE(locals[\"count\"].cast<int>() == num_threads);\n}\n\n// Scope exit utility https://stackoverflow.com/a/36644501/7255855\nstruct scope_exit {\n    std::function<void()> f_;\n    explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {}\n    ~scope_exit() {\n        if (f_) {\n            f_();\n        }\n    }\n};\n\nTEST_CASE(\"Reload module from file\") {\n    // Disable generation of cached bytecode (.pyc files) for this test, otherwise\n    // Python might pick up an old version from the cache instead of the new versions\n    // of the .py files generated below\n    auto sys = py::module_::import(\"sys\");\n    bool dont_write_bytecode = sys.attr(\"dont_write_bytecode\").cast<bool>();\n    sys.attr(\"dont_write_bytecode\") = true;\n    // Reset the value at scope exit\n    scope_exit reset_dont_write_bytecode(\n        [&]() { sys.attr(\"dont_write_bytecode\") = dont_write_bytecode; });\n\n    std::string module_name = \"test_module_reload\";\n    std::string module_file = module_name + \".py\";\n\n    // Create the module .py file\n    std::ofstream test_module(module_file);\n    test_module << \"def test():\\n\";\n    test_module << \"    return 1\\n\";\n    test_module.close();\n    // Delete the file at scope exit\n    scope_exit delete_module_file([&]() { std::remove(module_file.c_str()); });\n\n    // Import the module from file\n    auto module_ = py::module_::import(module_name.c_str());\n    int result = module_.attr(\"test\")().cast<int>();\n    REQUIRE(result == 1);\n\n    // Update the module .py file with a small change\n    test_module.open(module_file);\n    test_module << \"def test():\\n\";\n    test_module << \"    return 2\\n\";\n    test_module.close();\n\n    // Reload the module\n    module_.reload();\n    result = module_.attr(\"test\")().cast<int>();\n    REQUIRE(result == 2);\n}\n\nTEST_CASE(\"sys.argv gets initialized properly\") {\n    py::finalize_interpreter();\n    {\n        py::scoped_interpreter default_scope;\n        auto module = py::module::import(\"test_interpreter\");\n        auto py_widget = module.attr(\"DerivedWidget\")(\"The question\");\n        const auto &cpp_widget = py_widget.cast<const Widget &>();\n        REQUIRE(cpp_widget.argv0().empty());\n    }\n\n    {\n        char *argv[] = {strdup(\"a.out\")};\n        py::scoped_interpreter argv_scope(true, 1, argv);\n        std::free(argv[0]);\n        auto module = py::module::import(\"test_interpreter\");\n        auto py_widget = module.attr(\"DerivedWidget\")(\"The question\");\n        const auto &cpp_widget = py_widget.cast<const Widget &>();\n        REQUIRE(cpp_widget.argv0() == \"a.out\");\n    }\n    py::initialize_interpreter();\n}\n\nTEST_CASE(\"make_iterator can be called before then after finalizing an interpreter\") {\n    // Reproduction of issue #2101 (https://github.com/pybind/pybind11/issues/2101)\n    py::finalize_interpreter();\n\n    std::vector<int> container;\n    {\n        pybind11::scoped_interpreter g;\n        auto iter = pybind11::make_iterator(container.begin(), container.end());\n    }\n\n    REQUIRE_NOTHROW([&]() {\n        pybind11::scoped_interpreter g;\n        auto iter = pybind11::make_iterator(container.begin(), container.end());\n    }());\n\n    py::initialize_interpreter();\n}\n"
  },
  {
    "path": "tests/test_with_catch/test_interpreter.py",
    "content": "from __future__ import annotations\n\nimport sys\n\nfrom widget_module import Widget\n\n\nclass DerivedWidget(Widget):\n    def __init__(self, message):\n        super().__init__(message)\n\n    def the_answer(self):\n        return 42\n\n    def argv0(self):\n        return sys.argv[0]\n"
  },
  {
    "path": "tests/test_with_catch/test_subinterpreter.cpp",
    "content": "#include <pybind11/embed.h>\n#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n#    include <pybind11/gil_safe_call_once.h>\n#    include <pybind11/subinterpreter.h>\n\n// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to\n// catch 2.0.1; this should be fixed in the next catch release after 2.0.1).\nPYBIND11_WARNING_DISABLE_MSVC(4996)\n\n#    include \"catch_skip.h\"\n\n#    include <catch.hpp>\n#    include <cstdlib>\n#    include <fstream>\n#    include <functional>\n#    include <thread>\n#    include <utility>\n\nnamespace py = pybind11;\nusing namespace py::literals;\n\nbool has_state_dict_internals_obj();\nuintptr_t get_details_as_uintptr();\n\nvoid unsafe_reset_internals_for_single_interpreter() {\n    // NOTE: This code is NOT SAFE unless the caller guarantees no other threads are alive\n    // NOTE: This code is tied to the precise implementation of the internals holder\n\n    // first, unref the thread local internals\n    py::detail::get_internals_pp_manager().unref();\n    py::detail::get_local_internals_pp_manager().unref();\n\n    // we know there are no other interpreters, so we can lower this. SUPER DANGEROUS\n    py::detail::has_seen_non_main_interpreter() = false;\n\n    // now we unref the static global singleton internals\n    py::detail::get_internals_pp_manager().unref();\n    py::detail::get_local_internals_pp_manager().unref();\n\n    // finally, we reload the static global singleton\n    py::detail::get_internals();\n    py::detail::get_local_internals();\n}\n\npy::object &get_dict_type_object() {\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;\n    return storage\n        .call_once_and_store_result(\n            []() -> py::object { return py::module_::import(\"builtins\").attr(\"dict\"); })\n        .get_stored();\n}\n\npy::object &get_ordered_dict_type_object() {\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;\n    return storage\n        .call_once_and_store_result(\n            []() -> py::object { return py::module_::import(\"collections\").attr(\"OrderedDict\"); })\n        .get_stored();\n}\n\npy::object &get_default_dict_type_object() {\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;\n    return storage\n        .call_once_and_store_result(\n            []() -> py::object { return py::module_::import(\"collections\").attr(\"defaultdict\"); })\n        .get_stored();\n}\n\nTEST_CASE(\"Single Subinterpreter\") {\n    unsafe_reset_internals_for_single_interpreter();\n\n    py::module_::import(\"external_module\"); // in the main interpreter\n\n    // Add tags to the modules in the main interpreter and test the basics.\n    py::module_::import(\"__main__\").attr(\"main_tag\") = \"main interpreter\";\n    {\n        auto m = py::module_::import(\"widget_module\");\n        m.attr(\"extension_module_tag\") = \"added to module in main interpreter\";\n\n        REQUIRE(m.attr(\"add\")(1, 2).cast<int>() == 3);\n    }\n    REQUIRE(has_state_dict_internals_obj());\n\n    auto main_int\n        = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n\n    /// Create and switch to a subinterpreter.\n    {\n        py::scoped_subinterpreter ssi;\n\n        // The subinterpreter has internals populated\n        REQUIRE(has_state_dict_internals_obj());\n\n        py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n\n        auto ext_int\n            = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n        py::detail::get_internals();\n        REQUIRE(get_details_as_uintptr() == ext_int);\n        REQUIRE(ext_int != main_int);\n\n        // Modules tags should be gone.\n        REQUIRE_FALSE(py::hasattr(py::module_::import(\"__main__\"), \"tag\"));\n        {\n            auto m = py::module_::import(\"widget_module\");\n            REQUIRE_FALSE(py::hasattr(m, \"extension_module_tag\"));\n\n            // Function bindings should still work.\n            REQUIRE(m.attr(\"add\")(1, 2).cast<int>() == 3);\n        }\n    }\n\n    REQUIRE(py::hasattr(py::module_::import(\"__main__\"), \"main_tag\"));\n    REQUIRE(py::hasattr(py::module_::import(\"widget_module\"), \"extension_module_tag\"));\n    REQUIRE(has_state_dict_internals_obj());\n\n    unsafe_reset_internals_for_single_interpreter();\n}\n\n#    if PY_VERSION_HEX >= 0x030D0000\nTEST_CASE(\"Move Subinterpreter\") {\n    std::unique_ptr<py::subinterpreter> sub(new py::subinterpreter(py::subinterpreter::create()));\n\n    // on this thread, use the subinterpreter and import some non-trivial junk\n    {\n        py::subinterpreter_scoped_activate activate(*sub);\n\n        py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n        py::module_::import(\"datetime\");\n        py::module_::import(\"threading\");\n        py::module_::import(\"external_module\");\n    }\n\n    auto t = std::thread([&]() {\n        // Use it again\n        {\n            py::subinterpreter_scoped_activate activate(*sub);\n            py::module_::import(\"external_module\");\n        }\n        sub.reset();\n    });\n\n    // on 3.14.1+ destructing a sub-interpreter does a stop-the-world.  we need to detach our\n    // thread state in order for that to be possible.\n    {\n        py::gil_scoped_release nogil;\n        t.join();\n    }\n\n    REQUIRE(!sub);\n\n    unsafe_reset_internals_for_single_interpreter();\n}\n#    endif\n\nTEST_CASE(\"GIL Subinterpreter\") {\n\n    PyInterpreterState *main_interp = PyInterpreterState_Get();\n\n    {\n        auto sub = py::subinterpreter::create();\n\n        REQUIRE(main_interp == PyInterpreterState_Get());\n\n        PyInterpreterState *sub_interp = nullptr;\n\n        {\n            py::subinterpreter_scoped_activate activate(sub);\n\n            sub_interp = PyInterpreterState_Get();\n            REQUIRE(sub_interp != main_interp);\n\n            py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n            py::module_::import(\"datetime\");\n            py::module_::import(\"threading\");\n            py::module_::import(\"external_module\");\n\n            {\n                py::subinterpreter_scoped_activate main(py::subinterpreter::main());\n                REQUIRE(PyInterpreterState_Get() == main_interp);\n\n                {\n                    py::gil_scoped_release nogil{};\n                    {\n                        py::gil_scoped_acquire yesgil{};\n                        REQUIRE(PyInterpreterState_Get() == main_interp);\n                    }\n                }\n\n                REQUIRE(PyInterpreterState_Get() == main_interp);\n            }\n\n            REQUIRE(PyInterpreterState_Get() == sub_interp);\n\n            {\n                py::gil_scoped_release nogil{};\n                {\n                    py::gil_scoped_acquire yesgil{};\n                    REQUIRE(PyInterpreterState_Get() == sub_interp);\n                }\n            }\n\n            REQUIRE(PyInterpreterState_Get() == sub_interp);\n        }\n\n        REQUIRE(PyInterpreterState_Get() == main_interp);\n\n        {\n            py::gil_scoped_release nogil{};\n            {\n                py::gil_scoped_acquire yesgil{};\n                REQUIRE(PyInterpreterState_Get() == main_interp);\n            }\n        }\n\n        REQUIRE(PyInterpreterState_Get() == main_interp);\n\n        bool thread_result;\n\n        {\n            thread_result = false;\n            py::gil_scoped_release nogil{};\n            std::thread([&]() {\n                {\n                    py::subinterpreter_scoped_activate ssa{sub};\n                }\n                {\n                    py::gil_scoped_acquire gil{};\n                    thread_result = (PyInterpreterState_Get() == main_interp);\n                }\n            }).join();\n        }\n        REQUIRE(thread_result);\n\n        {\n            thread_result = false;\n            py::gil_scoped_release nogil{};\n            std::thread([&]() {\n                py::gil_scoped_acquire gil{};\n                thread_result = (PyInterpreterState_Get() == main_interp);\n            }).join();\n        }\n        REQUIRE(thread_result);\n    }\n\n    REQUIRE(PyInterpreterState_Get() == main_interp);\n    unsafe_reset_internals_for_single_interpreter();\n}\n\nTEST_CASE(\"Multiple Subinterpreters\") {\n    unsafe_reset_internals_for_single_interpreter();\n\n    // Make sure the module is in the main interpreter and save its pointer\n    auto *main_ext = py::module_::import(\"external_module\").ptr();\n    auto main_int\n        = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n    py::module_::import(\"external_module\").attr(\"multi_interp\") = \"1\";\n\n    {\n        py::subinterpreter si1 = py::subinterpreter::create();\n        std::unique_ptr<py::subinterpreter> psi2;\n\n        PyObject *sub1_ext = nullptr;\n        PyObject *sub2_ext = nullptr;\n        uintptr_t sub1_int = 0;\n        uintptr_t sub2_int = 0;\n\n        {\n            py::subinterpreter_scoped_activate scoped(si1);\n            py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n\n            // The subinterpreter has its own copy of this module which is completely separate from\n            // main\n            sub1_ext = py::module_::import(\"external_module\").ptr();\n            REQUIRE(sub1_ext != main_ext);\n            REQUIRE_FALSE(py::hasattr(py::module_::import(\"external_module\"), \"multi_interp\"));\n            py::module_::import(\"external_module\").attr(\"multi_interp\") = \"2\";\n            // The subinterpreter also has its own internals\n            sub1_int\n                = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n            REQUIRE(sub1_int != main_int);\n\n            // while the old one is active, create a new one\n            psi2.reset(new py::subinterpreter(py::subinterpreter::create()));\n        }\n\n        {\n            py::subinterpreter_scoped_activate scoped(*psi2);\n            py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n\n            // The second subinterpreter is separate from both main and the other subinterpreter\n            sub2_ext = py::module_::import(\"external_module\").ptr();\n            REQUIRE(sub2_ext != main_ext);\n            REQUIRE(sub2_ext != sub1_ext);\n            REQUIRE_FALSE(py::hasattr(py::module_::import(\"external_module\"), \"multi_interp\"));\n            py::module_::import(\"external_module\").attr(\"multi_interp\") = \"3\";\n            // The subinterpreter also has its own internals\n            sub2_int\n                = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n            REQUIRE(sub2_int != main_int);\n            REQUIRE(sub2_int != sub1_int);\n        }\n\n        {\n            py::subinterpreter_scoped_activate scoped(si1);\n            REQUIRE(\n                py::cast<std::string>(py::module_::import(\"external_module\").attr(\"multi_interp\"))\n                == \"2\");\n        }\n\n        // out here we should be in the main interpreter, with the GIL, with the other 2 still\n        // alive\n\n        auto post_int\n            = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n        // Make sure internals went back the way it was before\n        REQUIRE(main_int == post_int);\n\n        REQUIRE(py::cast<std::string>(py::module_::import(\"external_module\").attr(\"multi_interp\"))\n                == \"1\");\n    }\n\n    // now back to just main\n\n    auto post_int\n        = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n    // Make sure internals went back the way it was before\n    REQUIRE(main_int == post_int);\n\n    REQUIRE(py::cast<std::string>(py::module_::import(\"external_module\").attr(\"multi_interp\"))\n            == \"1\");\n\n    unsafe_reset_internals_for_single_interpreter();\n}\n\n// Test that gil_safe_call_once_and_store provides per-interpreter storage.\n// Without the per-interpreter storage fix, the subinterpreter would see the value\n// cached by the main interpreter, which is invalid (different interpreter's object).\nTEST_CASE(\"gil_safe_call_once_and_store per-interpreter isolation\") {\n    unsafe_reset_internals_for_single_interpreter();\n\n    // This static simulates a typical usage pattern where a module caches\n    // an imported object using gil_safe_call_once_and_store.\n    PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;\n\n    // Get the interpreter ID in the main interpreter\n    auto main_interp_id = PyInterpreterState_GetID(PyInterpreterState_Get());\n\n    // Store a value in the main interpreter - we'll store the interpreter ID as a Python int\n    auto &main_value = storage\n                           .call_once_and_store_result([]() {\n                               return py::int_(PyInterpreterState_GetID(PyInterpreterState_Get()));\n                           })\n                           .get_stored();\n    REQUIRE(main_value.cast<int64_t>() == main_interp_id);\n\n    py::object dict_type = get_dict_type_object();\n    py::object ordered_dict_type = get_ordered_dict_type_object();\n    py::object default_dict_type = get_default_dict_type_object();\n\n    int64_t sub_interp_id = -1;\n    int64_t sub_cached_value = -1;\n\n    bool sub_default_dict_type_destroyed = false;\n\n    // Create a subinterpreter and check that it gets its own storage\n    {\n        py::scoped_subinterpreter ssi;\n\n        sub_interp_id = PyInterpreterState_GetID(PyInterpreterState_Get());\n        REQUIRE(sub_interp_id != main_interp_id);\n\n        // Access the same static storage from the subinterpreter.\n        // With per-interpreter storage, this should call the lambda again\n        // and cache a NEW value for this interpreter.\n        // Without per-interpreter storage, this would return main's cached value.\n        auto &sub_value\n            = storage\n                  .call_once_and_store_result([]() {\n                      return py::int_(PyInterpreterState_GetID(PyInterpreterState_Get()));\n                  })\n                  .get_stored();\n\n        sub_cached_value = sub_value.cast<int64_t>();\n\n        // The cached value should be the SUBINTERPRETER's ID, not the main interpreter's.\n        // This would fail without per-interpreter storage.\n        REQUIRE(sub_cached_value == sub_interp_id);\n        REQUIRE(sub_cached_value != main_interp_id);\n\n        py::object sub_dict_type = get_dict_type_object();\n        py::object sub_ordered_dict_type = get_ordered_dict_type_object();\n        py::object sub_default_dict_type = get_default_dict_type_object();\n\n        // Verify that the subinterpreter has its own cached type objects.\n        // For static types, they should be the same object across interpreters.\n        // See also: https://docs.python.org/3/c-api/typeobj.html#static-types\n        REQUIRE(sub_dict_type.is(dict_type));                 // dict is a static type\n        REQUIRE(sub_ordered_dict_type.is(ordered_dict_type)); // OrderedDict is a static type\n        // For heap types, they are dynamically created per-interpreter.\n        // See also: https://docs.python.org/3/c-api/typeobj.html#heap-types\n        REQUIRE_FALSE(sub_default_dict_type.is(default_dict_type)); // defaultdict is a heap type\n\n        // Set up a weakref callback to detect when the subinterpreter's cached default_dict_type\n        // is destroyed so the gil_safe_call_once_and_store storage is not leaked when the\n        // subinterpreter is shutdown.\n        (void) py::weakref(sub_default_dict_type,\n                           py::cpp_function([&](py::handle weakref) -> void {\n                               sub_default_dict_type_destroyed = true;\n                               weakref.dec_ref();\n                           }))\n            .release();\n    }\n\n    // Back in main interpreter, verify main's value is unchanged\n    auto &main_value_after = storage.get_stored();\n    REQUIRE(main_value_after.cast<int64_t>() == main_interp_id);\n\n    // Verify that the types cached in main are unchanged\n    py::object dict_type_after = get_dict_type_object();\n    py::object ordered_dict_type_after = get_ordered_dict_type_object();\n    py::object default_dict_type_after = get_default_dict_type_object();\n    REQUIRE(dict_type_after.is(dict_type));\n    REQUIRE(ordered_dict_type_after.is(ordered_dict_type));\n    REQUIRE(default_dict_type_after.is(default_dict_type));\n\n    // Verify that the subinterpreter's cached default_dict_type was destroyed\n    REQUIRE(sub_default_dict_type_destroyed);\n\n    unsafe_reset_internals_for_single_interpreter();\n}\n\n#    ifdef Py_MOD_PER_INTERPRETER_GIL_SUPPORTED\nTEST_CASE(\"Per-Subinterpreter GIL\") {\n    auto main_int\n        = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n\n    std::atomic<int> started, sync, failure;\n    started = 0;\n    sync = 0;\n    failure = 0;\n\n// REQUIRE throws on failure, so we can't use it within the thread\n#        define T_REQUIRE(status)                                                                 \\\n            do {                                                                                  \\\n                assert(status);                                                                   \\\n                if (!(status))                                                                    \\\n                    ++failure;                                                                    \\\n            } while (0)\n\n    auto &&thread_main = [&](int num) {\n        while (started == 0)\n            std::this_thread::sleep_for(std::chrono::microseconds(1));\n        ++started;\n\n        py::gil_scoped_acquire gil;\n\n        // we have the GIL, we can access the main interpreter\n        auto t_int\n            = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n        T_REQUIRE(t_int == main_int);\n        py::module_::import(\"external_module\").attr(\"multi_interp\") = \"1\";\n\n        auto sub = py::subinterpreter::create();\n\n        {\n            py::subinterpreter_scoped_activate sguard{sub};\n\n            py::list(py::module_::import(\"sys\").attr(\"path\")).append(py::str(\".\"));\n\n            // we have switched to the new interpreter and released the main gil\n\n            // trampoline_module did not provide the per_interpreter_gil tag, so it cannot be\n            // imported\n            bool caught = false;\n            try {\n                py::module_::import(\"trampoline_module\");\n            } catch (pybind11::error_already_set &pe) {\n                T_REQUIRE(pe.matches(PyExc_ImportError));\n                std::string msg(pe.what());\n                T_REQUIRE(msg.find(\"does not support loading in subinterpreters\")\n                          != std::string::npos);\n                caught = true;\n            }\n            T_REQUIRE(caught);\n\n            // widget_module did provide the per_interpreter_gil tag, so it this does not throw\n            try {\n                py::module_::import(\"widget_module\");\n                caught = false;\n            } catch (pybind11::error_already_set &) {\n                caught = true;\n            }\n            T_REQUIRE(!caught);\n\n            // widget_module did provide the per_interpreter_gil tag, so it this does not throw\n            py::module_::import(\"widget_module\");\n\n            T_REQUIRE(!py::hasattr(py::module_::import(\"external_module\"), \"multi_interp\"));\n            py::module_::import(\"external_module\").attr(\"multi_interp\") = std::to_string(num);\n\n            // wait for something to set sync to our thread number\n            // we are holding our subinterpreter's GIL\n            {\n                py::gil_scoped_release nogil;\n                while (sync != num)\n                    std::this_thread::sleep_for(std::chrono::microseconds(1));\n            }\n\n            // now change it so the next thread can move on\n            ++sync;\n\n            // but keep holding the GIL until after the next thread moves on as well\n            {\n                py::gil_scoped_release nogil;\n                while (sync == num + 1)\n                    std::this_thread::sleep_for(std::chrono::microseconds(1));\n            }\n\n            // one last check before quitting the thread, the internals should be different\n            auto sub_int\n                = py::module_::import(\"external_module\").attr(\"internals_at\")().cast<uintptr_t>();\n            T_REQUIRE(sub_int != main_int);\n        }\n    };\n#        undef T_REQUIRE\n\n    std::thread t1(thread_main, 1);\n    std::thread t2(thread_main, 2);\n\n    // we spawned two threads, at this point they are both waiting for started to increase\n    ++started;\n\n    // ok now wait for the threads to start\n    while (started != 3)\n        std::this_thread::sleep_for(std::chrono::microseconds(1));\n\n    // we still hold the main GIL, at this point both threads are waiting on the main GIL\n    // IN THE CASE of free threading, the threads are waiting on sync (because there is no GIL)\n\n    // IF the below code hangs in one of the wait loops, then the child thread GIL behavior did not\n    // function as expected.\n    {\n        // release the GIL and allow the threads to run\n        py::gil_scoped_release nogil;\n\n        // the threads are now waiting on the sync\n        REQUIRE(sync == 0);\n\n        // this will trigger thread 1 and then advance and trigger 2 and then advance\n        sync = 1;\n\n        // wait for thread 2 to advance\n        while (sync != 3)\n            std::this_thread::sleep_for(std::chrono::microseconds(1));\n\n        // we know now that thread 1 has run and may be finishing\n        // and thread 2 is waiting for permission to advance\n\n        // so we move sync so that thread 2 can finish executing\n        ++sync;\n\n        // now wait for both threads to complete\n        t1.join();\n        t2.join();\n    }\n\n    // now we have the gil again, sanity check\n    REQUIRE(py::cast<std::string>(py::module_::import(\"external_module\").attr(\"multi_interp\"))\n            == \"1\");\n\n    unsafe_reset_internals_for_single_interpreter();\n\n    // make sure nothing unexpected happened inside the threads, now that they are completed\n    REQUIRE(failure == 0);\n}\n#    endif // Py_MOD_PER_INTERPRETER_GIL_SUPPORTED\n\n#endif // PYBIND11_HAS_SUBINTERPRETER_SUPPORT\n"
  },
  {
    "path": "tests/test_with_catch/test_trampoline.py",
    "content": "from __future__ import annotations\n\nimport trampoline_module\n\n\ndef func():\n    class Test(trampoline_module.test_override_cache_helper):\n        def func(self):\n            return 42\n\n    return Test()\n\n\ndef func2():\n    class Test(trampoline_module.test_override_cache_helper):\n        pass\n\n    return Test()\n"
  },
  {
    "path": "tests/valgrind-numpy-scipy.supp",
    "content": "# Valgrind suppression file for NumPy & SciPy errors and leaks in pybind11 tests\n#\n# On updating a dependency, to get a list of \"default\" leaks in e.g. NumPy, run\n# `PYTHONMALLOC=malloc valgrind --leak-check=full --show-leak-kinds=definite,indirect python3.9-dbg -c \"import numpy\"`\n# To use these suppression files, add e.g. `--suppressions=valgrind-numpy-scipy.supp`\n\n{\n   Leaks when importing NumPy\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_GC_Alloc\n   fun:_PyObject_GC_Malloc\n   fun:_PyObject_GC_NewVar\n   fun:tuple_alloc\n   fun:PyTuple_Pack\n   ...\n   fun:__pyx_pymod_exec_*\n}\n\n{\n   Leaks when importing NumPy (bis)\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_New\n   fun:PyCode_NewWithPosOnlyArgs\n   fun:PyCode_New\n   ...\n   fun:__pyx_pymod_exec_*\n}\n\n{\n   Leaks when importing NumPy (ter)\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_GC_Alloc\n   fun:_PyObject_GC_Malloc\n   fun:_PyObject_GC_NewVar\n   fun:tuple_alloc\n   fun:_PyTuple_FromArray\n   fun:_PyObject_MakeTpCall\n   fun:_PyObject_VectorcallTstate\n   fun:PyObject_Vectorcall\n   fun:call_function\n   fun:_PyEval_EvalFrameDefault\n   fun:_PyEval_EvalFrame\n   fun:function_code_fastcall\n   fun:_PyFunction_Vectorcall\n}\n\n{\n   Leaks when importing NumPy (quater)\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_GC_Alloc\n   fun:_PyObject_GC_Malloc\n   fun:_PyObject_GC_NewVar\n   fun:tuple_alloc\n   fun:_PyTuple_FromArray\n   fun:_PyObject_MakeTpCall\n   fun:_PyObject_VectorcallTstate\n   fun:_PyObject_CallFunctionVa\n   fun:PyObject_CallFunction\n   fun:PyImport_Import\n}\n\n{\n   Leaks when importing NumPy (quinquies)\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_GC_Alloc\n   fun:_PyObject_GC_Malloc\n   fun:_PyObject_GC_NewVar\n   fun:tuple_alloc\n   fun:PyTuple_New\n   fun:r_object\n   fun:r_object\n   fun:r_object\n   fun:r_object\n}\n\n{\n   Leaks when importing NumPy (sexies)\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyObject_Malloc\n   fun:_PyObject_GC_Alloc\n   fun:_PyObject_GC_Malloc\n   fun:_PyObject_GC_NewVar\n   fun:tuple_alloc\n   fun:PyTuple_New\n   fun:dictiter_iternextitem\n   fun:list_extend\n   fun:_PyList_Extend\n   fun:PySequence_List\n}\n\n{\n   Leak when importing scipy.fft\n   Memcheck:Leak\n   fun:_Znwm\n   fun:PyInit_pypocketfft\n   fun:_PyImport_LoadDynamicModuleWithSpec\n   fun:_imp_create_dynamic_impl*\n   fun:_imp_create_dynamic\n   fun:cfunction_vectorcall_FASTCALL\n   fun:PyVectorcall_Call\n   fun:_PyObject_Call\n   fun:PyObject_Call\n   fun:do_call_core\n   fun:_PyEval_EvalFrameDefault\n   fun:_PyEval_EvalFrame\n   fun:_PyEval_EvalCode\n}\n\n{\n   NumPy leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   ...\n   fun:_buffer_get_info\n   fun:array_getbuffer\n   fun:PyObject_GetBuffer\n   fun:__Pyx__GetBufferAndValidate*\n   fun:__pyx_f_5numpy_6random_13bit_generator_12SeedSequence_mix_entropy\n   fun:__pyx_pw_5numpy_6random_13bit_generator_12SeedSequence_1__init__\n   fun:type_call\n   fun:__Pyx__PyObject_CallOneArg\n   fun:__pyx_pw_5numpy_6random_13bit_generator_12BitGenerator_1__init__\n}\n"
  },
  {
    "path": "tests/valgrind-python.supp",
    "content": "# Valgrind suppression file for CPython errors and leaks in pybind11 tests\n\n# Taken verbatim from https://github.com/python/cpython/blob/3.9/Misc/valgrind-python.supp#L266-L272\n{\n   Uninitialised byte(s) false alarm, see bpo-35561\n   Memcheck:Param\n   epoll_ctl(event)\n   fun:epoll_ctl\n   fun:pyepoll_internal_ctl\n}\n\n{\n   Python leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyMem_RawMalloc\n   fun:PyThread_allocate_lock\n   fun:_PyEval_InitState\n   fun:PyInterpreterState_New\n   ...\n   fun:pyinit_core*\n   fun:Py_InitializeFromConfig\n   fun:pymain_init\n   fun:pymain_main\n}\n\n{\n   Python leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:_PyMem_DebugRawAlloc\n   fun:_PyMem_DebugRawMalloc\n   fun:PyMem_RawMalloc\n   fun:PyThread_allocate_lock\n   fun:_PyRuntimeState_Init_impl\n   fun:_PyRuntimeState_Init\n   fun:_PyRuntime_Initialize\n   fun:pymain_init\n   fun:pymain_main\n   fun:Py_BytesMain\n}\n\n{\n   Python leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyMem_RawMalloc\n   fun:PyThread_allocate_lock\n   fun:_PyImport_AcquireLock\n   fun:_imp_acquire_lock_impl*\n   fun:_imp_acquire_lock\n   fun:cfunction_vectorcall_NOARGS\n   fun:_PyObject_VectorcallTstate\n   fun:PyObject_Vectorcall\n   fun:call_function\n   fun:_PyEval_EvalFrameDefault\n   fun:_PyEval_EvalFrame\n   fun:function_code_fastcall\n}\n\n{\n   Python leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyMem_RawMalloc\n   fun:PyThread_allocate_lock\n   fun:newlockobject\n   ...\n   fun:cfunction_vectorcall_NOARGS\n   fun:_PyObject_VectorcallTstate\n   fun:PyObject_Vectorcall\n   fun:call_function\n   fun:_PyEval_EvalFrameDefault\n   fun:_PyEval_EvalFrame\n   fun:function_code_fastcall\n   fun:_PyFunction_Vectorcall\n}\n\n{\n   Python leaks when spawning a subprocess\n   Memcheck:Leak\n   fun:malloc\n   fun:_PyMem_RawMalloc\n   fun:PyMem_RawMalloc\n   fun:PyThread_allocate_lock\n   fun:rlock_new\n   fun:type_call\n   fun:_PyObject_Call\n   fun:PyObject_Call\n   fun:do_call_core\n   fun:_PyEval_EvalFrameDefault\n   fun:_PyEval_EvalFrame\n   fun:_PyEval_EvalCode\n   fun:_PyFunction_Vectorcall\n}\n\n# Not really CPython-specific, see link\n{\n   dlopen leak (https://stackoverflow.com/questions/1542457/memory-leak-reported-by-valgrind-in-dlopen)\n   Memcheck:Leak\n   fun:malloc\n   ...\n   fun:dl_open_worker\n   fun:_dl_catch_exception\n   fun:_dl_open\n   fun:dlopen_doit\n   fun:_dl_catch_exception\n   fun:_dl_catch_error\n   fun:_dlerror_run\n   fun:dlopen@@GLIBC_2.2.5\n   fun:_PyImport_FindSharedFuncptr\n   fun:_PyImport_LoadDynamicModuleWithSpec\n}\n"
  },
  {
    "path": "tools/FindCatch.cmake",
    "content": "# - Find the Catch test framework or download it (single header)\n#\n# This is a quick module for internal use. It assumes that Catch is\n# REQUIRED and that a minimum version is provided (not EXACT). If\n# a suitable version isn't found locally, the single header file\n# will be downloaded and placed in the build dir: PROJECT_BINARY_DIR.\n#\n# This code sets the following variables:\n#  CATCH_INCLUDE_DIR      - path to catch.hpp\n#  CATCH_VERSION          - version number\n\nif(NOT Catch_FIND_VERSION)\n  message(FATAL_ERROR \"A version number must be specified.\")\nelseif(Catch_FIND_REQUIRED)\n  message(FATAL_ERROR \"This module assumes Catch is not required.\")\nelseif(Catch_FIND_VERSION_EXACT)\n  message(FATAL_ERROR \"Exact version numbers are not supported, only minimum.\")\nendif()\n\n# Extract the version number from catch.hpp\nfunction(_get_catch_version)\n  file(\n    STRINGS \"${CATCH_INCLUDE_DIR}/catch.hpp\" version_line\n    REGEX \"Catch v.*\"\n    LIMIT_COUNT 1)\n  if(version_line MATCHES \"Catch v([0-9]+)\\\\.([0-9]+)\\\\.([0-9]+)\")\n    set(CATCH_VERSION\n        \"${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}\"\n        PARENT_SCOPE)\n  endif()\nendfunction()\n\n# Download the single-header version of Catch\nfunction(_download_catch version destination_dir)\n  message(STATUS \"Downloading catch v${version}...\")\n  set(url https://github.com/philsquared/Catch/releases/download/v${version}/catch.hpp)\n  file(\n    DOWNLOAD ${url} \"${destination_dir}/catch.hpp\"\n    STATUS status\n    LOG log)\n  list(GET status 0 error)\n  if(error)\n    string(REPLACE \"\\n\" \"\\n  \" log \"  ${log}\")\n    message(FATAL_ERROR \"Could not download URL:\\n\" \"  ${url}\\n\" \"Log:\\n\" \"${log}\")\n  endif()\n  set(CATCH_INCLUDE_DIR\n      \"${destination_dir}\"\n      CACHE INTERNAL \"\")\nendfunction()\n\n# Look for catch locally\nfind_path(\n  CATCH_INCLUDE_DIR\n  NAMES catch.hpp\n  PATH_SUFFIXES catch2)\nif(CATCH_INCLUDE_DIR)\n  _get_catch_version()\nendif()\n\n# Download the header if it wasn't found or if it's outdated\nif(NOT CATCH_VERSION OR CATCH_VERSION VERSION_LESS ${Catch_FIND_VERSION})\n  if(DOWNLOAD_CATCH)\n    _download_catch(${Catch_FIND_VERSION} \"${PROJECT_BINARY_DIR}/catch/\")\n    _get_catch_version()\n  else()\n    set(CATCH_FOUND FALSE)\n    return()\n  endif()\nendif()\n\nadd_library(Catch2::Catch2 IMPORTED INTERFACE)\nset_property(TARGET Catch2::Catch2 PROPERTY INTERFACE_INCLUDE_DIRECTORIES \"${CATCH_INCLUDE_DIR}\")\n\nset(CATCH_FOUND TRUE)\n"
  },
  {
    "path": "tools/FindEigen3.cmake",
    "content": "# - Try to find Eigen3 lib\n#\n# This module supports requiring a minimum version, e.g. you can do\n#   find_package(Eigen3 3.1.2)\n# to require version 3.1.2 or newer of Eigen3.\n#\n# Once done this will define\n#\n#  EIGEN3_FOUND - system has eigen lib with correct version\n#  EIGEN3_INCLUDE_DIR - the eigen include directory\n#  EIGEN3_VERSION - eigen version\n\n# Copyright (c) 2006, 2007 Montel Laurent, <montel@kde.org>\n# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>\n# Copyright (c) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n# Redistribution and use is allowed according to the terms of the 2-clause BSD license.\n\nif(NOT Eigen3_FIND_VERSION)\n  if(NOT Eigen3_FIND_VERSION_MAJOR)\n    set(Eigen3_FIND_VERSION_MAJOR 2)\n  endif(NOT Eigen3_FIND_VERSION_MAJOR)\n  if(NOT Eigen3_FIND_VERSION_MINOR)\n    set(Eigen3_FIND_VERSION_MINOR 91)\n  endif(NOT Eigen3_FIND_VERSION_MINOR)\n  if(NOT Eigen3_FIND_VERSION_PATCH)\n    set(Eigen3_FIND_VERSION_PATCH 0)\n  endif(NOT Eigen3_FIND_VERSION_PATCH)\n\n  set(Eigen3_FIND_VERSION\n      \"${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}\")\nendif(NOT Eigen3_FIND_VERSION)\n\nmacro(_eigen3_check_version)\n  file(READ \"${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h\" _eigen3_version_header)\n\n  string(REGEX MATCH \"define[ \\t]+EIGEN_WORLD_VERSION[ \\t]+([0-9]+)\" _eigen3_world_version_match\n               \"${_eigen3_version_header}\")\n  set(EIGEN3_WORLD_VERSION \"${CMAKE_MATCH_1}\")\n  string(REGEX MATCH \"define[ \\t]+EIGEN_MAJOR_VERSION[ \\t]+([0-9]+)\" _eigen3_major_version_match\n               \"${_eigen3_version_header}\")\n  set(EIGEN3_MAJOR_VERSION \"${CMAKE_MATCH_1}\")\n  string(REGEX MATCH \"define[ \\t]+EIGEN_MINOR_VERSION[ \\t]+([0-9]+)\" _eigen3_minor_version_match\n               \"${_eigen3_version_header}\")\n  set(EIGEN3_MINOR_VERSION \"${CMAKE_MATCH_1}\")\n\n  set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION})\n  if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n    set(EIGEN3_VERSION_OK FALSE)\n  else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n    set(EIGEN3_VERSION_OK TRUE)\n  endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n\n  if(NOT EIGEN3_VERSION_OK)\n\n    message(STATUS \"Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, \"\n                   \"but at least version ${Eigen3_FIND_VERSION} is required\")\n  endif(NOT EIGEN3_VERSION_OK)\nendmacro(_eigen3_check_version)\n\nif(EIGEN3_INCLUDE_DIR)\n\n  # in cache already\n  _eigen3_check_version()\n  set(EIGEN3_FOUND ${EIGEN3_VERSION_OK})\n\nelse(EIGEN3_INCLUDE_DIR)\n  if(NOT DEFINED KDE4_INCLUDE_DIR)\n    set(KDE4_INCLUDE_DIR \"\")\n  endif()\n\n  find_path(\n    EIGEN3_INCLUDE_DIR\n    NAMES signature_of_eigen3_matrix_library\n    PATHS ${CMAKE_INSTALL_PREFIX}/include ${KDE4_INCLUDE_DIR}\n    PATH_SUFFIXES eigen3 eigen)\n\n  if(EIGEN3_INCLUDE_DIR)\n    _eigen3_check_version()\n  endif(EIGEN3_INCLUDE_DIR)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK)\n\n  mark_as_advanced(EIGEN3_INCLUDE_DIR)\n\nendif(EIGEN3_INCLUDE_DIR)\n"
  },
  {
    "path": "tools/FindPythonLibsNew.cmake",
    "content": "# - Find python libraries\n# This module finds the libraries corresponding to the Python interpreter\n# FindPythonInterp provides.\n# This code sets the following variables:\n#\n#  PYTHONLIBS_FOUND           - have the Python libs been found\n#  PYTHON_PREFIX              - path to the Python installation\n#  PYTHON_LIBRARIES           - path to the python library\n#  PYTHON_INCLUDE_DIRS        - path to where Python.h is found\n#  PYTHON_MODULE_EXTENSION    - lib extension, e.g. '.so' or '.pyd'\n#  PYTHON_MODULE_PREFIX       - lib name prefix: usually an empty string\n#  PYTHON_SITE_PACKAGES       - path to installation site-packages\n#  PYTHON_IS_DEBUG            - whether the Python interpreter is a debug build\n#\n# Thanks to talljimbo for the patch adding the 'LDVERSION' config\n# variable usage.\n\n#=============================================================================\n# Copyright 2001-2009 Kitware, Inc.\n# Copyright 2012 Continuum Analytics, Inc.\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# * Neither the names of Kitware, Inc., the Insight Software Consortium,\n# nor the names of their contributors may be used to endorse or promote\n# products derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#=============================================================================\n\n# Checking for the extension makes sure that `LibsNew` was found and not just `Libs`.\nif(PYTHONLIBS_FOUND AND PYTHON_MODULE_EXTENSION)\n  return()\nendif()\n\nif(PythonLibsNew_FIND_QUIETLY)\n  set(_pythonlibs_quiet QUIET)\nelse()\n  set(_pythonlibs_quiet \"\")\nendif()\n\nif(PythonLibsNew_FIND_REQUIRED)\n  set(_pythonlibs_required REQUIRED)\nendif()\n\n# Check to see if the `python` command is present and from a virtual\n# environment, conda, or GHA activation - if it is, try to use that.\n\nif(NOT DEFINED PYTHON_EXECUTABLE)\n  if(DEFINED ENV{VIRTUAL_ENV})\n    find_program(\n      PYTHON_EXECUTABLE python\n      PATHS \"$ENV{VIRTUAL_ENV}\" \"$ENV{VIRTUAL_ENV}/bin\"\n      NO_DEFAULT_PATH)\n  elseif(DEFINED ENV{CONDA_PREFIX})\n    find_program(\n      PYTHON_EXECUTABLE python\n      PATHS \"$ENV{CONDA_PREFIX}\" \"$ENV{CONDA_PREFIX}/bin\"\n      NO_DEFAULT_PATH)\n  elseif(DEFINED ENV{pythonLocation})\n    find_program(\n      PYTHON_EXECUTABLE python\n      PATHS \"$ENV{pythonLocation}\" \"$ENV{pythonLocation}/bin\"\n      NO_DEFAULT_PATH)\n  endif()\n  if(NOT PYTHON_EXECUTABLE)\n    unset(PYTHON_EXECUTABLE)\n  endif()\nendif()\n\n# Use the Python interpreter to find the libs.\nif(NOT PythonLibsNew_FIND_VERSION)\n  set(PythonLibsNew_FIND_VERSION \"3.8\")\nendif()\n\nif(NOT CMAKE_VERSION VERSION_LESS \"3.27\")\n  cmake_policy(GET CMP0148 _pybind11_cmp0148)\n  if(NOT _pybind11_cmp0148)\n    message(\n      AUTHOR_WARNING\n        \"Policy CMP0148 is not set: The FindPythonInterp and FindPythonLibs \"\n        \"modules are removed.  Run \\\"cmake --help-policy CMP0148\\\" for policy \"\n        \"details.  Use the cmake_policy command to set the policy and suppress \"\n        \"this warning, or preferably upgrade to using FindPython, either by \"\n        \"calling it explicitly before pybind11, or by setting \"\n        \"PYBIND11_FINDPYTHON ON before pybind11.\")\n  endif()\n  cmake_policy(SET CMP0148 OLD)\n  unset(_pybind11_cmp0148)\nendif()\n\nfind_package(PythonInterp ${PythonLibsNew_FIND_VERSION} ${_pythonlibs_required}\n             ${_pythonlibs_quiet})\n\nif(NOT PYTHONINTERP_FOUND)\n  set(PYTHONLIBS_FOUND FALSE)\n  set(PythonLibsNew_FOUND FALSE)\n  return()\nendif()\n\n# According to https://stackoverflow.com/questions/646518/python-how-to-detect-debug-interpreter\n# testing whether sys has the gettotalrefcount function is a reliable, cross-platform\n# way to detect a CPython debug interpreter.\n#\n# The library suffix is from the config var LDVERSION sometimes, otherwise\n# VERSION. VERSION will typically be like \"2.7\" on unix, and \"27\" on windows.\nexecute_process(\n  COMMAND\n    \"${PYTHON_EXECUTABLE}\" \"-c\" \"\nimport sys;import struct;\nimport sysconfig as s\nUSE_SYSCONFIG = sys.version_info >= (3, 10)\nif not USE_SYSCONFIG:\n    from distutils import sysconfig as ds\nprint('.'.join(str(v) for v in sys.version_info));\nprint(sys.prefix);\nif USE_SYSCONFIG:\n    scheme = s.get_default_scheme()\n    if scheme == 'posix_local':\n        # Debian's default scheme installs to /usr/local/ but we want to find headers in /usr/\n        scheme = 'posix_prefix'\n    print(s.get_path('platinclude', scheme))\n    print(s.get_path('platlib'))\n    print(s.get_config_var('EXT_SUFFIX') or s.get_config_var('SO'))\nelse:\n    print(ds.get_python_inc(plat_specific=True));\n    print(ds.get_python_lib(plat_specific=True));\n    print(ds.get_config_var('EXT_SUFFIX') or ds.get_config_var('SO'));\nprint(hasattr(sys, 'gettotalrefcount')+0);\nprint(struct.calcsize('@P'));\nprint(s.get_config_var('LDVERSION') or s.get_config_var('VERSION'));\nprint(s.get_config_var('LIBDIR') or '');\nprint(s.get_config_var('MULTIARCH') or '');\n\"\n  RESULT_VARIABLE _PYTHON_SUCCESS\n  OUTPUT_VARIABLE _PYTHON_VALUES\n  ERROR_VARIABLE _PYTHON_ERROR_VALUE)\n\nif(NOT _PYTHON_SUCCESS MATCHES 0)\n  if(PythonLibsNew_FIND_REQUIRED)\n    message(FATAL_ERROR \"Python config failure:\\n${_PYTHON_ERROR_VALUE}\")\n  endif()\n  set(PYTHONLIBS_FOUND FALSE)\n  set(PythonLibsNew_FOUND FALSE)\n  return()\nendif()\n\noption(\n  PYBIND11_PYTHONLIBS_OVERWRITE\n  \"Overwrite cached values read from Python library (classic search). Turn off if cross-compiling and manually setting these values.\"\n  ON)\n# Can manually set values when cross-compiling\nmacro(_PYBIND11_GET_IF_UNDEF lst index name)\n  if(PYBIND11_PYTHONLIBS_OVERWRITE OR NOT DEFINED \"${name}\")\n    list(GET \"${lst}\" \"${index}\" \"${name}\")\n  endif()\nendmacro()\n\n# Convert the process output into a list\nif(WIN32)\n  string(REGEX REPLACE \"\\\\\\\\\" \"/\" _PYTHON_VALUES ${_PYTHON_VALUES})\nendif()\nstring(REGEX REPLACE \";\" \"\\\\\\\\;\" _PYTHON_VALUES ${_PYTHON_VALUES})\nstring(REGEX REPLACE \"\\n\" \";\" _PYTHON_VALUES ${_PYTHON_VALUES})\n_pybind11_get_if_undef(_PYTHON_VALUES 0 _PYTHON_VERSION_LIST)\n_pybind11_get_if_undef(_PYTHON_VALUES 1 PYTHON_PREFIX)\n_pybind11_get_if_undef(_PYTHON_VALUES 2 PYTHON_INCLUDE_DIR)\n_pybind11_get_if_undef(_PYTHON_VALUES 3 PYTHON_SITE_PACKAGES)\n_pybind11_get_if_undef(_PYTHON_VALUES 5 PYTHON_IS_DEBUG)\n_pybind11_get_if_undef(_PYTHON_VALUES 6 PYTHON_SIZEOF_VOID_P)\n_pybind11_get_if_undef(_PYTHON_VALUES 7 PYTHON_LIBRARY_SUFFIX)\n_pybind11_get_if_undef(_PYTHON_VALUES 8 PYTHON_LIBDIR)\n_pybind11_get_if_undef(_PYTHON_VALUES 9 PYTHON_MULTIARCH)\n\nlist(GET _PYTHON_VALUES 4 _PYTHON_MODULE_EXT_SUFFIX)\nif(PYBIND11_PYTHONLIBS_OVERWRITE OR NOT DEFINED PYTHON_MODULE_DEBUG_POSTFIX)\n  get_filename_component(PYTHON_MODULE_DEBUG_POSTFIX \"${_PYTHON_MODULE_EXT_SUFFIX}\" NAME_WE)\nendif()\nif(PYBIND11_PYTHONLIBS_OVERWRITE OR NOT DEFINED PYTHON_MODULE_EXTENSION)\n  get_filename_component(PYTHON_MODULE_EXTENSION \"${_PYTHON_MODULE_EXT_SUFFIX}\" EXT)\n  if((NOT \"$ENV{SETUPTOOLS_EXT_SUFFIX}\" STREQUAL \"\") AND (NOT \"$ENV{SETUPTOOLS_EXT_SUFFIX}\"\n                                                          STREQUAL \"${PYTHON_MODULE_EXTENSION}\"))\n    message(\n      AUTHOR_WARNING,\n      \"SETUPTOOLS_EXT_SUFFIX is set to \\\"$ENV{SETUPTOOLS_EXT_SUFFIX}\\\", \"\n      \"but the auto-calculated Python extension suffix is \\\"${PYTHON_MODULE_EXTENSION}\\\". \"\n      \"This may cause problems when importing the Python extensions. \"\n      \"If you are using cross-compiling Python, you may need to \"\n      \"set PYTHON_MODULE_EXTENSION manually.\")\n  endif()\nendif()\n\n# Make sure the Python has the same pointer-size as the chosen compiler\n# Skip if CMAKE_SIZEOF_VOID_P is not defined\n# This should be skipped for (non-Apple) cross-compiles (like EMSCRIPTEN)\nif(NOT _PYBIND11_CROSSCOMPILING\n   AND CMAKE_SIZEOF_VOID_P\n   AND (NOT \"${PYTHON_SIZEOF_VOID_P}\" STREQUAL \"${CMAKE_SIZEOF_VOID_P}\"))\n  if(PythonLibsNew_FIND_REQUIRED)\n    math(EXPR _PYTHON_BITS \"${PYTHON_SIZEOF_VOID_P} * 8\")\n    math(EXPR _CMAKE_BITS \"${CMAKE_SIZEOF_VOID_P} * 8\")\n    message(FATAL_ERROR \"Python config failure: Python is ${_PYTHON_BITS}-bit, \"\n                        \"chosen compiler is  ${_CMAKE_BITS}-bit\")\n  endif()\n  set(PYTHONLIBS_FOUND FALSE)\n  set(PythonLibsNew_FOUND FALSE)\n  return()\nendif()\n\n# The built-in FindPython didn't always give the version numbers\nstring(REGEX REPLACE \"\\\\.\" \";\" _PYTHON_VERSION_LIST ${_PYTHON_VERSION_LIST})\nlist(GET _PYTHON_VERSION_LIST 0 PYTHON_VERSION_MAJOR)\nlist(GET _PYTHON_VERSION_LIST 1 PYTHON_VERSION_MINOR)\nlist(GET _PYTHON_VERSION_LIST 2 PYTHON_VERSION_PATCH)\nset(PYTHON_VERSION \"${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}.${PYTHON_VERSION_PATCH}\")\n\n# Make sure all directory separators are '/'\nstring(REGEX REPLACE \"\\\\\\\\\" \"/\" PYTHON_PREFIX \"${PYTHON_PREFIX}\")\nstring(REGEX REPLACE \"\\\\\\\\\" \"/\" PYTHON_INCLUDE_DIR \"${PYTHON_INCLUDE_DIR}\")\nstring(REGEX REPLACE \"\\\\\\\\\" \"/\" PYTHON_SITE_PACKAGES \"${PYTHON_SITE_PACKAGES}\")\n\nif(DEFINED PYTHON_LIBRARY)\n  # Don't write to PYTHON_LIBRARY if it's already set\nelseif(CMAKE_HOST_WIN32)\n  set(PYTHON_LIBRARY \"${PYTHON_PREFIX}/libs/python${PYTHON_LIBRARY_SUFFIX}.lib\")\n\n  # when run in a venv, PYTHON_PREFIX points to it. But the libraries remain in the\n  # original python installation. They may be found relative to PYTHON_INCLUDE_DIR.\n  if(NOT EXISTS \"${PYTHON_LIBRARY}\")\n    get_filename_component(_PYTHON_ROOT ${PYTHON_INCLUDE_DIR} DIRECTORY)\n    set(PYTHON_LIBRARY \"${_PYTHON_ROOT}/libs/python${PYTHON_LIBRARY_SUFFIX}.lib\")\n  endif()\n\n  # if we are in MSYS & MINGW, and we didn't find windows python lib, look for system python lib\n  if(DEFINED ENV{MSYSTEM}\n     AND MINGW\n     AND NOT EXISTS \"${PYTHON_LIBRARY}\")\n    if(PYTHON_MULTIARCH)\n      set(_PYTHON_LIBS_SEARCH \"${PYTHON_LIBDIR}/${PYTHON_MULTIARCH}\" \"${PYTHON_LIBDIR}\")\n    else()\n      set(_PYTHON_LIBS_SEARCH \"${PYTHON_LIBDIR}\")\n    endif()\n    unset(PYTHON_LIBRARY)\n    find_library(\n      PYTHON_LIBRARY\n      NAMES \"python${PYTHON_LIBRARY_SUFFIX}\"\n      PATHS ${_PYTHON_LIBS_SEARCH}\n      NO_DEFAULT_PATH)\n  endif()\n\n  # raise an error if the python libs are still not found.\n  if(NOT EXISTS \"${PYTHON_LIBRARY}\")\n    message(FATAL_ERROR \"Python libraries not found\")\n  endif()\n\nelse()\n  if(PYTHON_MULTIARCH)\n    set(_PYTHON_LIBS_SEARCH \"${PYTHON_LIBDIR}/${PYTHON_MULTIARCH}\" \"${PYTHON_LIBDIR}\")\n  else()\n    set(_PYTHON_LIBS_SEARCH \"${PYTHON_LIBDIR}\")\n  endif()\n  #message(STATUS \"Searching for Python libs in ${_PYTHON_LIBS_SEARCH}\")\n  # Probably this needs to be more involved. It would be nice if the config\n  # information the python interpreter itself gave us were more complete.\n  find_library(\n    PYTHON_LIBRARY\n    NAMES \"python${PYTHON_LIBRARY_SUFFIX}\"\n    PATHS ${_PYTHON_LIBS_SEARCH}\n    NO_DEFAULT_PATH)\n\n  # If all else fails, just set the name/version and let the linker figure out the path.\n  if(NOT PYTHON_LIBRARY)\n    set(PYTHON_LIBRARY python${PYTHON_LIBRARY_SUFFIX})\n  endif()\nendif()\n\nmark_as_advanced(PYTHON_LIBRARY PYTHON_INCLUDE_DIR)\n\n# We use PYTHON_INCLUDE_DIR, PYTHON_LIBRARY and PYTHON_DEBUG_LIBRARY for the\n# cache entries because they are meant to specify the location of a single\n# library. We now set the variables listed by the documentation for this\n# module.\nset(PYTHON_INCLUDE_DIRS \"${PYTHON_INCLUDE_DIR}\")\nset(PYTHON_LIBRARIES \"${PYTHON_LIBRARY}\")\nif(NOT PYTHON_DEBUG_LIBRARY)\n  set(PYTHON_DEBUG_LIBRARY \"\")\nendif()\nset(PYTHON_DEBUG_LIBRARIES \"${PYTHON_DEBUG_LIBRARY}\")\n\nfind_package_message(PYTHON \"Found PythonLibs: ${PYTHON_LIBRARIES}\"\n                     \"${PYTHON_EXECUTABLE}${PYTHON_VERSION_STRING}\")\n\nset(PYTHONLIBS_FOUND TRUE)\nset(PythonLibsNew_FOUND TRUE)\n\nif(NOT PYTHON_MODULE_PREFIX)\n  set(PYTHON_MODULE_PREFIX \"\")\nendif()\n"
  },
  {
    "path": "tools/JoinPaths.cmake",
    "content": "# This module provides function for joining paths\n# known from most languages\n#\n# SPDX-License-Identifier: (MIT OR CC0-1.0)\n# Copyright 2020 Jan Tojnar\n# https://github.com/jtojnar/cmake-snips\n#\n# Modelled after Python’s os.path.join\n# https://docs.python.org/3.7/library/os.path.html#os.path.join\n# Windows not supported\nfunction(join_paths joined_path first_path_segment)\n    set(temp_path \"${first_path_segment}\")\n    foreach(current_segment IN LISTS ARGN)\n        if(NOT (\"${current_segment}\" STREQUAL \"\"))\n            if(IS_ABSOLUTE \"${current_segment}\")\n                set(temp_path \"${current_segment}\")\n            else()\n                set(temp_path \"${temp_path}/${current_segment}\")\n            endif()\n        endif()\n    endforeach()\n    set(${joined_path} \"${temp_path}\" PARENT_SCOPE)\nendfunction()\n"
  },
  {
    "path": "tools/check-style.sh",
    "content": "#!/bin/bash\n#\n# Script to check include/test code for common pybind11 code style errors.\n#\n# This script currently checks for\n#\n# 1. missing space between keyword and parenthesis, e.g.: for(, if(, while(\n# 2. Missing space between right parenthesis and brace, e.g. 'for (...){'\n# 3. opening brace on its own line. It should always be on the same line as the\n#    if/while/for/do statement.\n#\n# Invoke as: tools/check-style.sh <filenames>\n#\n\ncheck_style_errors=0\nIFS=$'\\n'\n\n\nfound=\"$(grep '\\<\\(if\\|for\\|while\\|catch\\)(\\|){' \"$@\" -rn --color=always)\"\nif [ -n \"$found\" ]; then\n    echo -e '\\033[31;01mError: found the following coding style problems:\\033[0m'\n    check_style_errors=1\n    echo \"${found//^/    /}\"\nfi\n\nfound=\"$(awk '\nfunction prefix(filename, lineno) {\n    return \"    \\033[35m\" filename \"\\033[36m:\\033[32m\" lineno \"\\033[36m:\\033[0m\"\n}\nfunction mark(pattern, string) { sub(pattern, \"\\033[01;31m&\\033[0m\", string); return string }\nlast && /^\\s*{/ {\n    print prefix(FILENAME, FNR-1) mark(\"\\\\)\\\\s*$\", last)\n    print prefix(FILENAME, FNR)   mark(\"^\\\\s*{\", $0)\n    last=\"\"\n}\n{ last = /(if|for|while|catch|switch)\\s*\\(.*\\)\\s*$/ ? $0 : \"\" }\n' \"$(find include -type f)\" \"$@\")\"\nif [ -n \"$found\" ]; then\n    check_style_errors=1\n    echo -e '\\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\\033[0m'\n    echo \"$found\"\nfi\n\nexit $check_style_errors\n"
  },
  {
    "path": "tools/cmake_uninstall.cmake.in",
    "content": "# Source: https://gitlab.kitware.com/cmake/community/-/wikis/FAQ#can-i-do-make-uninstall-with-cmake\n\nif(NOT EXISTS \"@CMAKE_BINARY_DIR@/install_manifest.txt\")\n  message(FATAL_ERROR \"Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt\")\nendif()\n\nfile(READ \"@CMAKE_BINARY_DIR@/install_manifest.txt\" files)\nstring(REGEX REPLACE \"\\n\" \";\" files \"${files}\")\nforeach(file ${files})\n  message(STATUS \"Uninstalling $ENV{DESTDIR}${file}\")\n  if(IS_SYMLINK \"$ENV{DESTDIR}${file}\" OR EXISTS \"$ENV{DESTDIR}${file}\")\n    exec_program(\n      \"@CMAKE_COMMAND@\" ARGS\n      \"-E remove \\\"$ENV{DESTDIR}${file}\\\"\"\n      OUTPUT_VARIABLE rm_out\n      RETURN_VALUE rm_retval)\n    if(NOT \"${rm_retval}\" STREQUAL 0)\n      message(FATAL_ERROR \"Problem when removing $ENV{DESTDIR}${file}\")\n    endif()\n  else(IS_SYMLINK \"$ENV{DESTDIR}${file}\" OR EXISTS \"$ENV{DESTDIR}${file}\")\n    message(STATUS \"File $ENV{DESTDIR}${file} does not exist.\")\n  endif()\nendforeach()\n"
  },
  {
    "path": "tools/codespell_ignore_lines_from_errors.py",
    "content": "\"\"\"Simple script for rebuilding .codespell-ignore-lines\n\nUsage:\n\ncat < /dev/null > .codespell-ignore-lines\npre-commit run --all-files codespell >& /tmp/codespell_errors.txt\npython3 tools/codespell_ignore_lines_from_errors.py /tmp/codespell_errors.txt > .codespell-ignore-lines\n\ngit diff to review changes, then commit, push.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\n\ndef run(args: list[str]) -> None:\n    assert len(args) == 1, \"codespell_errors.txt\"\n    cache = {}\n    done = set()\n    with open(args[0]) as f:\n        lines = f.read().splitlines()\n\n    for line in sorted(lines):\n        i = line.find(\" ==> \")\n        if i > 0:\n            flds = line[:i].split(\":\")\n            if len(flds) >= 2:\n                filename, line_num = flds[:2]\n                if filename not in cache:\n                    with open(filename) as f:\n                        cache[filename] = f.read().splitlines()\n                supp = cache[filename][int(line_num) - 1]\n                if supp not in done:\n                    print(supp)\n                    done.add(supp)\n\n\nif __name__ == \"__main__\":\n    run(args=sys.argv[1:])\n"
  },
  {
    "path": "tools/libsize.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\n\n# Internal build script for generating debugging test .so size.\n# Usage:\n#     python libsize.py file.so save.txt -- displays the size of file.so and, if save.txt exists, compares it to the\n#                                           size in it, then overwrites save.txt with the new size for future runs.\n\nif len(sys.argv) != 3:\n    sys.exit(\"Invalid arguments: usage: python libsize.py file.so save.txt\")\n\nlib = sys.argv[1]\nsave = sys.argv[2]\n\nif not os.path.exists(lib):\n    sys.exit(f\"Error: requested file ({lib}) does not exist\")\n\nlibsize = os.path.getsize(lib)\n\nprint(\"------\", os.path.basename(lib), \"file size:\", libsize, end=\"\")\n\nif os.path.exists(save):\n    with open(save) as sf:\n        oldsize = int(sf.readline())\n\n    if oldsize > 0:\n        change = libsize - oldsize\n        if change == 0:\n            print(\" (no change)\")\n        else:\n            print(f\" (change of {change:+} bytes = {change / oldsize:+.2%})\")\nelse:\n    print()\n\nwith open(save, \"w\") as sf:\n    sf.write(str(libsize))\n"
  },
  {
    "path": "tools/make_changelog.py",
    "content": "#!/usr/bin/env -S uv run\n\n# /// script\n# dependencies = [\"ghapi\", \"rich\"]\n# ///\n\nfrom __future__ import annotations\n\nimport re\n\nimport ghapi.all\nfrom rich import print\nfrom rich.syntax import Syntax\n\nMD_ENTRY = re.compile(\n    r\"\"\"\n    \\#\\#\\ Suggested\\ changelog\\ entry:     # Match the heading exactly\n    (?:\\s*<!--.*?-->)?                     # Optionally match one comment\n    (?P<content>.*?)                       # Lazily capture content until...\n    (?=                                    # Lookahead for one of the following:\n        ^-{3,}\\s*$                         #   A line with 3 or more dashes\n      | ^<!--\\s*readthedocs                #   A comment starting with 'readthedocs'\n      | ^\\#\\#                              #   A new heading\n      | \\Z                                 #   End of string\n    )\n    \"\"\",\n    re.DOTALL | re.VERBOSE | re.MULTILINE,\n)\nprint()\n\n\napi = ghapi.all.GhApi(owner=\"pybind\", repo=\"pybind11\")\n\nissues_pages = ghapi.page.paged(\n    api.issues.list_for_repo, labels=\"needs changelog\", state=\"closed\"\n)\nissues = (issue for page in issues_pages for issue in page)\nmissing = []\nold = []\ncats_descr = {\n    \"feat\": \"New Features\",\n    \"feat(types)\": \"\",\n    \"feat(cmake)\": \"\",\n    \"fix\": \"Bug fixes\",\n    \"fix(types)\": \"\",\n    \"fix(cmake)\": \"\",\n    \"fix(free-threading)\": \"\",\n    \"docs\": \"Documentation\",\n    \"tests\": \"Tests\",\n    \"ci\": \"CI\",\n    \"chore\": \"Other\",\n    \"chore(cmake)\": \"\",\n    \"unknown\": \"Uncategorised\",\n}\ncats: dict[str, list[str]] = {c: [] for c in cats_descr}\n\nfor issue in issues:\n    if \"```rst\" in issue.body:\n        old.append(issue)\n        continue\n\n    changelog = MD_ENTRY.search(issue.body or \"\")\n    if not changelog:\n        missing.append(issue)\n        continue\n\n    msg = changelog.group(\"content\").strip()\n    if not msg:\n        missing.append(issue)\n        continue\n    if msg.startswith(\"* \"):\n        msg = msg[2:]\n    if not msg.startswith(\"- \"):\n        msg = \"- \" + msg\n    if not msg.endswith(\".\"):\n        msg += \".\"\n    if msg == \"- Placeholder.\":\n        missing.append(issue)\n        continue\n\n    msg += f\"\\n  [#{issue.number}]({issue.html_url})\"\n    for cat, cat_list in cats.items():\n        if issue.title.lower().startswith(f\"{cat}:\"):\n            cat_list.append(msg)\n            break\n    else:\n        cats[\"unknown\"].append(msg)\n\nfor cat, msgs in cats.items():\n    if msgs:\n        desc = cats_descr[cat]\n        print(f\"[bold]{desc}:\" if desc else f\"<!-- {cat} -->\")\n        print()\n        for msg in msgs:\n            print(Syntax(msg, \"md\", theme=\"ansi_light\", word_wrap=True))\n            print()\n        print()\n\nif missing:\n    print()\n    print(\"[blue]\" + \"-\" * 30)\n    print()\n\n    for issue in missing:\n        print(f\"[red bold]Missing:[/red bold][red] {issue.title}\")\n        print(f\"[red]  {issue.html_url}\\n\")\n\n    print(\"[bold]Template:\\n\")\n    msg = \"## Suggested changelog entry:\"\n    print(Syntax(msg, \"md\", theme=\"ansi_light\"))\n\nif old:\n    print()\n    print(\"[red]\" + \"-\" * 30)\n    print()\n\n    for issue in old:\n        print(f\"[red bold]Old:[/red bold][red] {issue.title}\")\n        print(f\"[red]  {issue.html_url}\\n\")\n\nprint()\n"
  },
  {
    "path": "tools/make_global.py",
    "content": "#!/usr/bin/env -S uv run -q\n\n# /// script\n# dependencies = [\"tomlkit\"]\n# ///\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\nimport tomlkit\n\nDIR = Path(__file__).parent.resolve()\nPYPROJECT = DIR.parent / \"pyproject.toml\"\n\n\ndef get_global() -> str:\n    pyproject = tomlkit.parse(PYPROJECT.read_text())\n    del pyproject[\"tool\"][\"scikit-build\"][\"generate\"]\n    del pyproject[\"project\"][\"entry-points\"]\n    del pyproject[\"project\"][\"scripts\"]\n    del pyproject[\"tool\"][\"scikit-build\"][\"metadata\"][\"optional-dependencies\"]\n    pyproject[\"project\"][\"name\"] = \"pybind11-global\"\n    pyproject[\"tool\"][\"scikit-build\"][\"experimental\"] = True\n    pyproject[\"tool\"][\"scikit-build\"][\"wheel\"][\"install-dir\"] = \"/data\"\n    pyproject[\"tool\"][\"scikit-build\"][\"wheel\"][\"packages\"] = []\n\n    result = tomlkit.dumps(pyproject)\n    assert isinstance(result, str)\n    return result\n\n\nif __name__ == \"__main__\":\n    print(get_global())\n"
  },
  {
    "path": "tools/pybind11.pc.in",
    "content": "prefix=@prefix_for_pc_file@\nincludedir=@includedir_for_pc_file@\n\nName: @PROJECT_NAME@\nDescription: Seamless operability between C++11 and Python\nVersion: @PROJECT_VERSION@\nCflags: -I${includedir}\n"
  },
  {
    "path": "tools/pybind11Common.cmake",
    "content": "#[======================================================[.rst\n\nAdds the following targets::\n\n    pybind11::pybind11 - link to Python headers and pybind11::headers\n    pybind11::module - Adds module links\n    pybind11::embed - Adds embed links\n    pybind11::lto - Link time optimizations (only if CMAKE_INTERPROCEDURAL_OPTIMIZATION is not set)\n    pybind11::thin_lto - Link time optimizations (only if CMAKE_INTERPROCEDURAL_OPTIMIZATION is not set)\n    pybind11::python_link_helper - Adds link to Python libraries\n    pybind11::windows_extras - MSVC bigobj and mp for building multithreaded\n    pybind11::opt_size - avoid optimizations that increase code size\n\nAdds the following functions::\n\n    pybind11_strip(target) - strip target after building on linux/macOS\n    pybind11_find_import(module) - See if a module is installed.\n\n#]======================================================]\n\n# If we are in subdirectory mode, all IMPORTED targets must be GLOBAL. If we\n# are in CONFIG mode, they should be \"normal\" targets instead.\n# In CMake 3.11+ you can promote a target to global after you create it,\n# which might be simpler than this check.\nget_property(\n  is_config\n  TARGET pybind11::headers\n  PROPERTY IMPORTED)\n\nif(NOT is_config)\n  include_guard(GLOBAL)\n  set(optional_global GLOBAL)\nelse()\n  include_guard(DIRECTORY)\n  set(optional_global \"\")\nendif()\n\n# If not run in Python mode, we still would like this to at least\n# include pybind11's include directory:\nset(pybind11_INCLUDE_DIRS\n    \"${pybind11_INCLUDE_DIR}\"\n    CACHE INTERNAL \"Include directory for pybind11 (Python not requested)\")\n\n# CMP0190 prohibits calling FindPython with both Interpreter and Development components\n# when cross-compiling, unless the CMAKE_CROSSCOMPILING_EMULATOR variable is defined.\nif(CMAKE_VERSION VERSION_GREATER_EQUAL \"4.1\")\n  cmake_policy(GET CMP0190 _pybind11_cmp0190)\n  if(_pybind11_cmp0190 STREQUAL \"NEW\")\n    set(PYBIND11_USE_CROSSCOMPILING \"ON\")\n  endif()\nendif()\n\nif(CMAKE_CROSSCOMPILING\n   AND PYBIND11_USE_CROSSCOMPILING\n   AND NOT DEFINED CMAKE_CROSSCOMPILING_EMULATOR)\n  set(_PYBIND11_CROSSCOMPILING\n      ON\n      CACHE INTERNAL \"\")\nelse()\n  set(_PYBIND11_CROSSCOMPILING\n      OFF\n      CACHE INTERNAL \"\")\nendif()\n\n# --------------------- Shared targets ----------------------------\n\n# Build an interface library target:\nadd_library(pybind11::pybind11 IMPORTED INTERFACE ${optional_global})\nset_property(\n  TARGET pybind11::pybind11\n  APPEND\n  PROPERTY INTERFACE_LINK_LIBRARIES pybind11::headers)\n\n# Build a module target:\nadd_library(pybind11::module IMPORTED INTERFACE ${optional_global})\nset_property(\n  TARGET pybind11::module\n  APPEND\n  PROPERTY INTERFACE_LINK_LIBRARIES pybind11::pybind11)\n\n# Build an embed library target:\nadd_library(pybind11::embed IMPORTED INTERFACE ${optional_global})\nset_property(\n  TARGET pybind11::embed\n  APPEND\n  PROPERTY INTERFACE_LINK_LIBRARIES pybind11::pybind11)\n\n# -------------- emscripten requires exceptions enabled -------------\n# _pybind11_no_exceptions is a private mechanism to disable this addition.\n# Please open an issue if you need to use it; it will be removed if no one\n# needs it.\nif(CMAKE_SYSTEM_NAME MATCHES Emscripten AND NOT _pybind11_no_exceptions)\n  if(is_config)\n    set(_tmp_config_target pybind11::pybind11_headers)\n  else()\n    set(_tmp_config_target pybind11_headers)\n  endif()\n\n  set_property(\n    TARGET ${_tmp_config_target}\n    APPEND\n    PROPERTY INTERFACE_LINK_OPTIONS -fexceptions)\n  set_property(\n    TARGET ${_tmp_config_target}\n    APPEND\n    PROPERTY INTERFACE_COMPILE_OPTIONS -fexceptions)\n  unset(_tmp_config_target)\nendif()\n\n# --------------------------- link helper ---------------------------\n\nadd_library(pybind11::python_link_helper IMPORTED INTERFACE ${optional_global})\n\nset_property(\n  TARGET pybind11::python_link_helper\n  APPEND\n  PROPERTY INTERFACE_LINK_OPTIONS \"$<$<PLATFORM_ID:Darwin>:LINKER:-undefined,dynamic_lookup>\")\n\n# ------------------------ Windows extras -------------------------\n\nadd_library(pybind11::windows_extras IMPORTED INTERFACE ${optional_global})\n\nif(MSVC) # That's also clang-cl\n  # /bigobj is needed for bigger binding projects due to the limit to 64k\n  # addressable sections\n  set_property(\n    TARGET pybind11::windows_extras\n    APPEND\n    PROPERTY INTERFACE_COMPILE_OPTIONS $<$<COMPILE_LANGUAGE:CXX>:/bigobj>)\n\n  # /MP enables multithreaded builds (relevant when there are many files) for MSVC\n  if(\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"MSVC\") # no Clang no Intel\n    # Only set these options for C++ files.  This is important so that, for\n    # instance, projects that include other types of source files like CUDA\n    # .cu files don't get these options propagated to nvcc since that would\n    # cause the build to fail.\n    set_property(\n      TARGET pybind11::windows_extras\n      APPEND\n      PROPERTY INTERFACE_COMPILE_OPTIONS $<$<NOT:$<CONFIG:Debug>>:$<$<COMPILE_LANGUAGE:CXX>:/MP>>)\n  endif()\nendif()\n\n# ----------------------- Optimize binary size --------------------------\n\nadd_library(pybind11::opt_size IMPORTED INTERFACE ${optional_global})\n\nif(MSVC)\n  set(PYBIND11_OPT_SIZE /Os)\nelse()\n  set(PYBIND11_OPT_SIZE -Os)\nendif()\n\nset_property(\n  TARGET pybind11::opt_size\n  APPEND\n  PROPERTY INTERFACE_COMPILE_OPTIONS $<$<CONFIG:Release>:${PYBIND11_OPT_SIZE}>\n           $<$<CONFIG:MinSizeRel>:${PYBIND11_OPT_SIZE}>\n           $<$<CONFIG:RelWithDebInfo>:${PYBIND11_OPT_SIZE}>)\n\n# ----------------------- Legacy option --------------------------\n\n# Warn or error if old variable name used\nif(PYBIND11_CPP_STANDARD)\n  string(REGEX MATCH [[..$]] VAL \"${PYBIND11_CPP_STANDARD}\")\n  if(CMAKE_CXX_STANDARD)\n    if(NOT CMAKE_CXX_STANDARD STREQUAL VAL)\n      message(WARNING \"CMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD} does not match \"\n                      \"PYBIND11_CPP_STANDARD=${PYBIND11_CPP_STANDARD}, \"\n                      \"please remove PYBIND11_CPP_STANDARD from your cache\")\n    endif()\n  else()\n    set(supported_standards 11 14 17 20)\n    if(\"${VAL}\" IN_LIST supported_standards)\n      message(WARNING \"USE -DCMAKE_CXX_STANDARD=${VAL} instead of PYBIND11_CPP_STANDARD\")\n      set(CMAKE_CXX_STANDARD\n          ${VAL}\n          CACHE STRING \"From PYBIND11_CPP_STANDARD\")\n    else()\n      message(FATAL_ERROR \"PYBIND11_CPP_STANDARD should be replaced with CMAKE_CXX_STANDARD \"\n                          \"(last two chars: ${VAL} not understood as a valid CXX std)\")\n    endif()\n  endif()\nendif()\n\n# --------------------- Python specifics -------------------------\n\n# CMake 3.27 removes the classic FindPythonInterp if CMP0148 is NEW\nif(CMAKE_VERSION VERSION_LESS \"3.27\")\n  set(_pybind11_missing_old_python \"OLD\")\nelse()\n  cmake_policy(GET CMP0148 _pybind11_missing_old_python)\nendif()\n\n# Check to see which Python mode we are in, new, old, or no python\nif(PYBIND11_NOPYTHON)\n  set(_pybind11_nopython ON)\n  # We won't use new FindPython if PYBIND11_FINDPYTHON is defined and falselike\n  # Otherwise, we use if FindPythonLibs is missing or if FindPython was already used\nelseif(\n  (NOT DEFINED PYBIND11_FINDPYTHON\n   OR PYBIND11_FINDPYTHON STREQUAL \"COMPAT\"\n   OR PYBIND11_FINDPYTHON)\n  AND (_pybind11_missing_old_python STREQUAL \"NEW\"\n       OR PYBIND11_FINDPYTHON STREQUAL \"COMPAT\"\n       OR PYBIND11_FINDPYTHON\n       OR Python_FOUND\n       OR Python3_FOUND\n      ))\n\n  # New mode\n  if(Python_FOUND OR Python3_FOUND)\n    include(\"${CMAKE_CURRENT_LIST_DIR}/pybind11NewTools.cmake\")\n  else()\n    include(\"${CMAKE_CURRENT_LIST_DIR}/pybind11NewTools.cmake\")\n\n    if(PYBIND11_FINDPYTHON STREQUAL \"COMPAT\")\n      message(\n        \"Using compatibility mode for Python, set PYBIND11_FINDPYTHON to NEW/OLD to silence this message\"\n      )\n      set(PYTHON_EXECUTABLE \"${Python_EXECUTABLE}\")\n      set(PYTHON_INCLUDE_DIR \"${Python_INCLUDE_DIR}\")\n      set(Python_INCLUDE_DIRS \"${Python_INCLUDE_DIRS}\")\n      set(PYTHON_LIBRARY \"${Python_LIBRARY}\")\n      set(PYTHON_LIBRARIES \"${Python_LIBRARIES}\")\n      set(PYTHON_VERSION \"${Python_VERSION}\")\n      set(PYTHON_VERSION_STRING \"${Python_VERSION_STRING}\")\n      set(PYTHON_VERSION_MAJOR \"${Python_VERSION_MAJOR}\")\n      set(PYTHON_VERSION_MINOR \"${Python_VERSION_MINOR}\")\n      set(PYTHON_VERSION_PATCH \"${Python_VERSION_PATCH}\")\n    endif()\n  endif()\n\nelse()\n\n  # Classic mode\n  include(\"${CMAKE_CURRENT_LIST_DIR}/pybind11Tools.cmake\")\n\nendif()\n\n# --------------------- pybind11_find_import -------------------------------\n\nif(NOT _pybind11_nopython AND NOT _PYBIND11_CROSSCOMPILING)\n  # Check to see if modules are importable. Use REQUIRED to force an error if\n  # one of the modules is not found. <package_name>_FOUND will be set if the\n  # package was found (underscores replace dashes if present). QUIET will hide\n  # the found message, and VERSION will require a minimum version. A successful\n  # find will cache the result.\n  function(pybind11_find_import PYPI_NAME)\n    # CMake variables need underscores (PyPI doesn't care)\n    string(REPLACE \"-\" \"_\" NORM_PYPI_NAME \"${PYPI_NAME}\")\n\n    # Return if found previously\n    if(${NORM_PYPI_NAME}_FOUND)\n      return()\n    endif()\n\n    set(options \"REQUIRED;QUIET\")\n    set(oneValueArgs \"VERSION\")\n    cmake_parse_arguments(ARG \"${options}\" \"${oneValueArgs}\" \"\" ${ARGN})\n\n    if(ARG_REQUIRED)\n      set(status_level FATAL_ERROR)\n    else()\n      set(status_level WARNING)\n    endif()\n\n    execute_process(\n      COMMAND\n        ${${_Python}_EXECUTABLE} -c \"\ntry:\n    from importlib.metadata import version\nexcept ImportError:\n    from pkg_resources import get_distribution\n    def version(s):\n        return get_distribution(s).version\nprint(version('${PYPI_NAME}'))\n        \"\n      RESULT_VARIABLE RESULT_PRESENT\n      OUTPUT_VARIABLE PKG_VERSION\n      ERROR_QUIET)\n\n    string(STRIP \"${PKG_VERSION}\" PKG_VERSION)\n\n    # If a result is present, this failed\n    if(RESULT_PRESENT)\n      set(${NORM_PYPI_NAME}_FOUND\n          ${NORM_PYPI_NAME}-NOTFOUND\n          CACHE INTERNAL \"\")\n      # Always warn or error\n      message(\n        ${status_level}\n        \"Missing: ${PYPI_NAME} ${ARG_VERSION}\\nTry: ${${_Python}_EXECUTABLE} -m pip install ${PYPI_NAME}\"\n      )\n    else()\n      if(ARG_VERSION AND PKG_VERSION VERSION_LESS ARG_VERSION)\n        message(\n          ${status_level}\n          \"Version incorrect: ${PYPI_NAME} ${PKG_VERSION} found, ${ARG_VERSION} required - try upgrading\"\n        )\n      else()\n        set(${NORM_PYPI_NAME}_FOUND\n            YES\n            CACHE INTERNAL \"\")\n        set(${NORM_PYPI_NAME}_VERSION\n            ${PKG_VERSION}\n            CACHE INTERNAL \"\")\n      endif()\n      if(NOT ARG_QUIET)\n        message(STATUS \"Found ${PYPI_NAME} ${PKG_VERSION}\")\n      endif()\n    endif()\n    if(NOT ARG_VERSION OR (NOT PKG_VERSION VERSION_LESS ARG_VERSION))\n      # We have successfully found a good version, cache to avoid calling again.\n    endif()\n  endfunction()\nendif()\n\n# --------------------- LTO -------------------------------\n\ninclude(CheckCXXCompilerFlag)\n\n# Checks whether the given CXX/linker flags can compile and link a cxx file.\n# cxxflags and linkerflags are lists of flags to use.  The result variable is a\n# unique variable name for each set of flags: the compilation result will be\n# cached base on the result variable.  If the flags work, sets them in\n# cxxflags_out/linkerflags_out internal cache variables (in addition to\n# ${result}).\nfunction(_pybind11_return_if_cxx_and_linker_flags_work result cxxflags linkerflags cxxflags_out\n         linkerflags_out)\n  set(CMAKE_REQUIRED_LIBRARIES ${linkerflags})\n  check_cxx_compiler_flag(\"${cxxflags}\" ${result})\n  if(${result})\n    set(${cxxflags_out}\n        \"${cxxflags}\"\n        PARENT_SCOPE)\n    set(${linkerflags_out}\n        \"${linkerflags}\"\n        PARENT_SCOPE)\n  endif()\nendfunction()\n\nfunction(_pybind11_generate_lto target prefer_thin_lto)\n  if(MINGW)\n    message(STATUS \"${target} disabled (problems with undefined symbols for MinGW for now)\")\n    return()\n  endif()\n\n  if(CMAKE_CXX_COMPILER_ID MATCHES \"GNU|Clang\")\n    set(cxx_append \"\")\n    set(linker_append \"\")\n    if(CMAKE_CXX_COMPILER_ID MATCHES \"Clang\" AND NOT APPLE)\n      # Clang Gold plugin does not support -Os; append -O3 to MinSizeRel builds to override it\n      set(linker_append \";$<$<CONFIG:MinSizeRel>:-O3>\")\n    elseif(CMAKE_CXX_COMPILER_ID MATCHES \"GNU\" AND NOT MINGW)\n      set(cxx_append \";-fno-fat-lto-objects\")\n    endif()\n\n    if(prefer_thin_lto)\n      set(thin \"=thin\")\n    else()\n      set(thin \"\")\n    endif()\n\n    if(CMAKE_SYSTEM_PROCESSOR MATCHES \"ppc64le\" OR CMAKE_SYSTEM_PROCESSOR MATCHES \"mips64\")\n      # Do nothing\n    elseif(CMAKE_SYSTEM_NAME MATCHES Emscripten)\n      # This compile is very costly when cross-compiling, so set this without checking\n      set(PYBIND11_LTO_CXX_FLAGS \"-flto${thin}${cxx_append}\")\n      set(PYBIND11_LTO_LINKER_FLAGS \"-flto${thin}${linker_append}\")\n    elseif(CMAKE_CXX_COMPILER_ID MATCHES \"Clang\")\n      _pybind11_return_if_cxx_and_linker_flags_work(\n        HAS_FLTO_THIN \"-flto${thin}${cxx_append}\" \"-flto${thin}${linker_append}\"\n        PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n    endif()\n    if(NOT HAS_FLTO_THIN)\n      _pybind11_return_if_cxx_and_linker_flags_work(\n        HAS_FLTO_AUTO \"-flto=auto${cxx_append}\" \"-flto=auto${linker_append}\"\n        PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n    endif()\n    if(NOT HAS_FLTO_AUTO)\n      _pybind11_return_if_cxx_and_linker_flags_work(\n        HAS_FLTO \"-flto${cxx_append}\" \"-flto${linker_append}\" PYBIND11_LTO_CXX_FLAGS\n        PYBIND11_LTO_LINKER_FLAGS)\n    endif()\n  elseif(CMAKE_CXX_COMPILER_ID MATCHES \"IntelLLVM\")\n    # IntelLLVM equivalent to LTO is called IPO; also IntelLLVM is WIN32/UNIX\n    # WARNING/HELP WANTED: This block of code is currently not covered by pybind11 GitHub Actions!\n    if(WIN32)\n      _pybind11_return_if_cxx_and_linker_flags_work(\n        HAS_INTEL_IPO \"-Qipo\" \"-Qipo\" PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n    else()\n      _pybind11_return_if_cxx_and_linker_flags_work(\n        HAS_INTEL_IPO \"-ipo\" \"-ipo\" PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n    endif()\n  elseif(CMAKE_CXX_COMPILER_ID MATCHES \"Intel\")\n    # Intel equivalent to LTO is called IPO\n    _pybind11_return_if_cxx_and_linker_flags_work(HAS_INTEL_IPO \"-ipo\" \"-ipo\"\n                                                  PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n  elseif(MSVC)\n    # cmake only interprets libraries as linker flags when they start with a - (otherwise it\n    # converts /LTCG to \\LTCG as if it was a Windows path).  Luckily MSVC supports passing flags\n    # with - instead of /, even if it is a bit non-standard:\n    _pybind11_return_if_cxx_and_linker_flags_work(HAS_MSVC_GL_LTCG \"/GL\" \"-LTCG\"\n                                                  PYBIND11_LTO_CXX_FLAGS PYBIND11_LTO_LINKER_FLAGS)\n  endif()\n\n  # Enable LTO flags if found, except for Debug builds\n  if(PYBIND11_LTO_CXX_FLAGS)\n    # CONFIG takes multiple values in CMake 3.19+, until then we have to use OR\n    set(is_debug \"$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>\")\n    set(not_debug \"$<NOT:${is_debug}>\")\n    set(cxx_lang \"$<COMPILE_LANGUAGE:CXX>\")\n    set(genex \"$<AND:${not_debug},${cxx_lang}>\")\n    set_property(\n      TARGET ${target}\n      APPEND\n      PROPERTY INTERFACE_COMPILE_OPTIONS \"$<${genex}:${PYBIND11_LTO_CXX_FLAGS}>\")\n    if(CMAKE_PROJECT_NAME STREQUAL \"pybind11\")\n      message(STATUS \"${target} enabled\")\n    endif()\n  else()\n    if(CMAKE_PROJECT_NAME STREQUAL \"pybind11\")\n      message(STATUS \"${target} disabled (not supported by the compiler and/or linker)\")\n    endif()\n  endif()\n\n  if(PYBIND11_LTO_LINKER_FLAGS)\n    set_property(\n      TARGET ${target}\n      APPEND\n      PROPERTY INTERFACE_LINK_OPTIONS \"$<${not_debug}:${PYBIND11_LTO_LINKER_FLAGS}>\")\n  endif()\nendfunction()\n\nif(NOT DEFINED CMAKE_INTERPROCEDURAL_OPTIMIZATION)\n  add_library(pybind11::lto IMPORTED INTERFACE ${optional_global})\n  _pybind11_generate_lto(pybind11::lto FALSE)\n\n  add_library(pybind11::thin_lto IMPORTED INTERFACE ${optional_global})\n  _pybind11_generate_lto(pybind11::thin_lto TRUE)\nendif()\n\n# ---------------------- pybind11_strip -----------------------------\n\nfunction(pybind11_strip target_name)\n  # Strip unnecessary sections of the binary on Linux/macOS\n  if(CMAKE_STRIP)\n    if(APPLE)\n      set(x_opt -x)\n    endif()\n\n    add_custom_command(\n      TARGET ${target_name}\n      POST_BUILD\n      COMMAND ${CMAKE_STRIP} ${x_opt} $<TARGET_FILE:${target_name}>)\n  endif()\nendfunction()\n"
  },
  {
    "path": "tools/pybind11Config.cmake.in",
    "content": "#[=============================================================================[.rst:\n\npybind11Config.cmake\n####################\n\nExported variables\n==================\n\nThis module sets the following variables in your project:\n\n``pybind11_FOUND``\n  true if pybind11 and all required components found on the system\n``pybind11_VERSION``\n  pybind11 version in format Major.Minor.Release\n``pybind11_VERSION_TYPE``\n  pybind11 version type (``dev*`` or empty for a release)\n``pybind11_INCLUDE_DIRS``\n  Directories where pybind11 and python headers are located.\n``pybind11_INCLUDE_DIR``\n  Directory where pybind11 headers are located.\n``pybind11_DEFINITIONS``\n  Definitions necessary to use pybind11, namely USING_pybind11.\n``pybind11_LIBRARIES``\n  Compile flags and python libraries (as needed) to link against.\n``pybind11_LIBRARY``\n  Empty.\n\nAvailable components: None\n\n\nExported targets\n================\n\nIf pybind11 is found, this module defines the following ``IMPORTED``\ninterface library targets:\n\n``pybind11::module``\n  for extension modules.\n``pybind11::embed``\n  for embedding the Python interpreter.\n\nPython headers, libraries (as needed by platform), and the C++ standard\nare attached to the target.\n\nAdvanced targets are also supplied - these are primary for users building\ncomplex applications, and they are available in all modes:\n\n``pybind11::headers``\n  Just the pybind11 headers and minimum compile requirements.\n``pybind11::pybind11``\n  Python headers too.\n``pybind11::python_link_helper``\n  Just the \"linking\" part of ``pybind11:module``, for CMake < 3.15.\n``pybind11::thin_lto``\n  An alternative to ``INTERPROCEDURAL_OPTIMIZATION``.\n``pybind11::lto``\n  An alternative to ``INTERPROCEDURAL_OPTIMIZATION`` (also avoids thin LTO on clang).\n``pybind11::windows_extras``\n  Adds bigobj and mp for MSVC.\n\nModes\n=====\n\nThere are two modes provided; classic, which is built on the old Python\ndiscovery packages in CMake, or the new FindPython mode, which uses FindPython\nfrom 3.12+ forward (3.15+ _highly_ recommended). If you set the minimum or\nmaximum version of CMake to 3.27+, then FindPython is the default (since\nFindPythonInterp/FindPythonLibs has been removed via policy `CMP0148`).\n\nStarting in pybind11 3.0, the new mode is the default, but we provide backward\ncompatible names (``PYTHON_*`` vs. the new ``Python_*`` names). Set the mode\nexplicitly to avoid the compatibility defines. You can specify this mode\nexplicitly by setting ``PYBIND11_FINDPYTHON`` to ``COMPAT``, but if you are changing\nyour CMakeLists anyway, please just use the ``ON`` mode. A future release may\ndefault to ``ON``.\n\nNew FindPython mode\n^^^^^^^^^^^^^^^^^^^\n\nTo activate this mode, either call ``find_package(Python COMPONENTS Interpreter Development)``\nbefore finding this package, or set the ``PYBIND11_FINDPYTHON`` variable to ON. In this mode,\nyou can either use the basic targets, or use the FindPython tools:\n\n.. code-block:: cmake\n\n  find_package(Python COMPONENTS Interpreter Development)\n  find_package(pybind11 CONFIG)\n\n  # pybind11 method:\n  pybind11_add_module(MyModule1 src1.cpp)\n\n  # Python method:\n  Python_add_library(MyModule2 src2.cpp)\n  target_link_libraries(MyModule2 PUBLIC pybind11::headers)\n  set_target_properties(MyModule2 PROPERTIES\n                                  INTERPROCEDURAL_OPTIMIZATION ON\n                                  CXX_VISIBILITY_PRESET hidden\n                                  VISIBILITY_INLINES_HIDDEN ON)\n\nIf you build targets yourself, you may be interested in stripping the output\nfor reduced size; this is the one other feature that the helper function gives you.\n\nClassic mode\n^^^^^^^^^^^^\n\nSet PythonLibsNew variables to influence python detection and\nCMAKE_CXX_STANDARD to influence standard setting.\n\n.. code-block:: cmake\n\n  find_package(pybind11 CONFIG REQUIRED)\n\n  # Create an extension module\n  add_library(mylib MODULE main.cpp)\n  target_link_libraries(mylib PUBLIC pybind11::module)\n\n  # Or embed the Python interpreter into an executable\n  add_executable(myexe main.cpp)\n  target_link_libraries(myexe PUBLIC pybind11::embed)\n\n\nHints\n=====\n\nThe following variables can be set to guide the search for this package:\n\n``pybind11_DIR``\n  CMake variable, set to directory containing this Config file.\n``CMAKE_PREFIX_PATH``\n  CMake variable, set to root directory of this package.\n``PATH``\n  Environment variable, set to bin directory of this package.\n``CMAKE_DISABLE_FIND_PACKAGE_pybind11``\n  CMake variable, disables ``find_package(pybind11)`` when not ``REQUIRED``,\n  perhaps to force internal build.\n\nCommands\n========\n\npybind11_add_module\n^^^^^^^^^^^^^^^^^^^\n\nThis module defines the following commands to assist with creating Python modules:\n\n.. code-block:: cmake\n\n  pybind11_add_module(<target>\n    [STATIC|SHARED|MODULE]\n    [THIN_LTO] [OPT_SIZE] [NO_EXTRAS] [WITHOUT_SOABI]\n    <files>...\n    )\n\nAdd a module and setup all helpers. You can select the type of the library; the\ndefault is ``MODULE``. There are several options:\n\n``OPT_SIZE``\n  Optimize for size, even if the ``CMAKE_BUILD_TYPE`` is not ``MinSizeRel``.\n``THIN_LTO``\n  Use thin LTO instead of regular if there's a choice (pybind11's selection\n  is disabled if ``CMAKE_INTERPROCEDURAL_OPTIMIZATIONS`` is set).\n``WITHOUT_SOABI``\n  Disable the SOABI component (``PYBIND11_FINDPYTHON`` mode only).\n``NO_EXTRAS``\n  Disable all extras, exit immediately after making the module.\n\npybind11_strip\n^^^^^^^^^^^^^^\n\n.. code-block:: cmake\n\n  pybind11_strip(<target>)\n\nStrip a target after building it (linux/macOS), called by ``pybind11_add_module``.\n\npybind11_extension\n^^^^^^^^^^^^^^^^^^\n\n.. code-block:: cmake\n\n    pybind11_extension(<target>)\n\nSets the Python extension name correctly for Python on your platform, called by\n``pybind11_add_module``.\n\npybind11_find_import(module)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code-block:: cmake\n\n    pybind11_find_import(<module> [VERSION <number>] [REQUIRED] [QUIET])\n\nSee if a module is installed. Use the registered name (the one on PyPI). You\ncan specify a ``VERSION``, and you can specify ``REQUIRED`` or ``QUIET``. Only available if\n``NOPYTHON`` mode is not active.  Sets ``module_VERSION`` and ``module_FOUND``. Caches the\nresult once a valid install is found.\n\nSuggested usage\n===============\n\nUsing ``find_package`` with version info is not recommended except for release versions.\n\n.. code-block:: cmake\n\n  find_package(pybind11 CONFIG)\n  find_package(pybind11 2.9 EXACT CONFIG REQUIRED)\n\n#]=============================================================================]\n@PACKAGE_INIT@\n\n# Location of pybind11/pybind11.h\n# This will be relative unless explicitly set as absolute\nset(pybind11_INCLUDE_DIR \"@pybind11_INCLUDEDIR@\")\n\nset(pybind11_LIBRARY \"\")\nset(pybind11_DEFINITIONS USING_pybind11)\nset(pybind11_VERSION_TYPE \"@pybind11_VERSION_TYPE@\")\n\ncheck_required_components(pybind11)\n\nif(TARGET pybind11::python_link_helper)\n  # This has already been setup elsewhere, such as with a previous call or\n  # add_subdirectory\n  return()\nendif()\n\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/pybind11Targets.cmake\")\n\n# Easier to use / remember\nadd_library(pybind11::headers IMPORTED INTERFACE)\nset_target_properties(pybind11::headers PROPERTIES INTERFACE_LINK_LIBRARIES\n                                                   pybind11::pybind11_headers)\n\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/pybind11Common.cmake\")\n\nif(NOT pybind11_FIND_QUIETLY)\n  message(\n    STATUS\n      \"Found pybind11: ${pybind11_INCLUDE_DIR} (found version \\\"${pybind11_VERSION}${pybind11_VERSION_TYPE}\\\")\"\n  )\nendif()\n"
  },
  {
    "path": "tools/pybind11GuessPythonExtSuffix.cmake",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\nfunction(pybind11_guess_python_module_extension python)\n\n  # The SETUPTOOLS_EXT_SUFFIX environment variable takes precedence:\n  if(NOT DEFINED PYTHON_MODULE_EXT_SUFFIX AND DEFINED ENV{SETUPTOOLS_EXT_SUFFIX})\n    message(\n      STATUS\n        \"Getting Python extension suffix from ENV{SETUPTOOLS_EXT_SUFFIX}: $ENV{SETUPTOOLS_EXT_SUFFIX}\"\n    )\n    set(PYTHON_MODULE_EXT_SUFFIX\n        \"$ENV{SETUPTOOLS_EXT_SUFFIX}\"\n        CACHE\n          STRING\n          \"Extension suffix for Python extension modules (Initialized from SETUPTOOLS_EXT_SUFFIX)\")\n  endif()\n\n  # The final extension depends on the system\n  set(_PY_BUILD_EXTENSION \"${CMAKE_SHARED_MODULE_SUFFIX}\")\n  if(CMAKE_SYSTEM_NAME STREQUAL \"Windows\")\n    set(_PY_BUILD_EXTENSION \".pyd\")\n  endif()\n\n  # If running under scikit-build-core, use the SKBUILD_SOABI variable:\n  if(NOT DEFINED PYTHON_MODULE_EXT_SUFFIX AND DEFINED SKBUILD_SOABI)\n    message(STATUS \"Determining Python extension suffix based on SKBUILD_SOABI: ${SKBUILD_SOABI}\")\n    set(PYTHON_MODULE_EXT_SUFFIX \".${SKBUILD_SOABI}${_PY_BUILD_EXTENSION}\")\n  endif()\n\n  # If that didn't work, use the Python_SOABI variable:\n  if(NOT DEFINED PYTHON_MODULE_EXT_SUFFIX AND DEFINED ${python}_SOABI)\n    message(\n      STATUS \"Determining Python extension suffix based on ${python}_SOABI: ${${python}_SOABI}\")\n    # If the SOABI already has an extension, use it as the full suffix\n    # (used for debug versions of Python on Windows)\n    if(${python}_SOABI MATCHES \"\\\\.\")\n      set(PYTHON_MODULE_EXT_SUFFIX \"${${python}_SOABI}\")\n      # If the SOABI is empty, this is usually a bug, but we generate a\n      # correct extension anyway, which is the best we can do\n    elseif(\"${${python}_SOABI}\" STREQUAL \"\")\n      message(\n        WARNING\n          \"${python}_SOABI is defined but empty. You may want to set PYTHON_MODULE_EXT_SUFFIX explicitly.\"\n      )\n      set(PYTHON_MODULE_EXT_SUFFIX \"${_PY_BUILD_EXTENSION}\")\n      # Otherwise, add the system-dependent extension to it\n    else()\n      set(PYTHON_MODULE_EXT_SUFFIX \".${${python}_SOABI}${_PY_BUILD_EXTENSION}\")\n    endif()\n  endif()\n\n  # If we could not deduce the extension suffix, unset the results:\n  if(NOT DEFINED PYTHON_MODULE_EXT_SUFFIX)\n    unset(PYTHON_MODULE_DEBUG_POSTFIX CACHE)\n    unset(PYTHON_MODULE_EXTENSION CACHE)\n    unset(PYTHON_IS_DEBUG CACHE)\n    return()\n  endif()\n\n  # Sanity checks:\n  if(${python}_SOABI AND NOT (PYTHON_MODULE_EXT_SUFFIX STREQUAL ${python}_SOABI\n                              OR PYTHON_MODULE_EXT_SUFFIX MATCHES \"\\\\.${${python}_SOABI}\\\\.\"))\n    message(\n      WARNING\n        \"Python extension suffix (${PYTHON_MODULE_EXT_SUFFIX}) does not match ${python}_SOABI (${${python}_SOABI}).\"\n    )\n  endif()\n\n  # Separate file name postfix from extension: (https://github.com/pybind/pybind11/issues/4699)\n  get_filename_component(_PYTHON_MODULE_DEBUG_POSTFIX \"${PYTHON_MODULE_EXT_SUFFIX}\" NAME_WE)\n  get_filename_component(_PYTHON_MODULE_EXTENSION \"${PYTHON_MODULE_EXT_SUFFIX}\" EXT)\n\n  # Try to deduce the debug ABI from the extension suffix:\n  if(NOT DEFINED _PYTHON_IS_DEBUG)\n    if(_PYTHON_MODULE_EXTENSION MATCHES \"^\\\\.(cpython-|cp|pypy)[0-9]+dm?-\"\n       OR _PYTHON_MODULE_DEBUG_POSTFIX MATCHES \"^_d\")\n      set(_PYTHON_IS_DEBUG On)\n    else()\n      set(_PYTHON_IS_DEBUG Off)\n    endif()\n  endif()\n\n  # Return results\n  set(PYTHON_MODULE_DEBUG_POSTFIX\n      \"${_PYTHON_MODULE_DEBUG_POSTFIX}\"\n      CACHE INTERNAL \"\")\n  set(PYTHON_MODULE_EXTENSION\n      \"${_PYTHON_MODULE_EXTENSION}\"\n      CACHE INTERNAL \"\")\n  set(PYTHON_IS_DEBUG\n      \"${_PYTHON_IS_DEBUG}\"\n      CACHE INTERNAL \"\")\n\nendfunction()\n"
  },
  {
    "path": "tools/pybind11NewTools.cmake",
    "content": "# tools/pybind11NewTools.cmake -- Build system for the pybind11 modules\n#\n# Copyright (c) 2020 Wenzel Jakob <wenzel@inf.ethz.ch> and Henry Schreiner\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\ninclude_guard(DIRECTORY)\n\nget_property(\n  is_config\n  TARGET pybind11::headers\n  PROPERTY IMPORTED)\n\nif(pybind11_FIND_QUIETLY)\n  set(_pybind11_quiet QUIET)\nelse()\n  set(_pybind11_quiet \"\")\nendif()\n\nif(NOT Python_FOUND AND NOT Python3_FOUND)\n  if(NOT DEFINED Python_FIND_IMPLEMENTATIONS)\n    set(Python_FIND_IMPLEMENTATIONS CPython PyPy)\n  endif()\n\n  # GitHub Actions like activation\n  if(NOT DEFINED Python_ROOT_DIR AND DEFINED ENV{pythonLocation})\n    set(Python_ROOT_DIR \"$ENV{pythonLocation}\")\n  endif()\n\n  # Interpreter should not be found when cross-compiling\n  if(_PYBIND11_CROSSCOMPILING)\n    set(_pybind11_interp_component \"\")\n  else()\n    set(_pybind11_interp_component Interpreter)\n  endif()\n\n  # Development.Module support (required for manylinux) started in 3.18\n  if(CMAKE_VERSION VERSION_LESS 3.18)\n    set(_pybind11_dev_component Development)\n  else()\n    set(_pybind11_dev_component Development.Module OPTIONAL_COMPONENTS Development.Embed)\n  endif()\n\n  # Callers need to be able to access Python_EXECUTABLE\n  set(_pybind11_global_keyword \"\")\n  if(NOT is_config AND NOT DEFINED Python_ARTIFACTS_INTERACTIVE)\n    set(Python_ARTIFACTS_INTERACTIVE TRUE)\n    if(NOT CMAKE_VERSION VERSION_LESS 3.24)\n      set(_pybind11_global_keyword \"GLOBAL\")\n    endif()\n  endif()\n\n  find_package(\n    Python 3.8 REQUIRED COMPONENTS ${_pybind11_interp_component} ${_pybind11_dev_component}\n                                   ${_pybind11_quiet} ${_pybind11_global_keyword})\n\n  # If we are in submodule mode, export the Python targets to global targets.\n  # If this behavior is not desired, FindPython _before_ pybind11.\n  if(NOT is_config\n     AND Python_ARTIFACTS_INTERACTIVE\n     AND _pybind11_global_keyword STREQUAL \"\")\n    if(TARGET Python::Python)\n      set_property(TARGET Python::Python PROPERTY IMPORTED_GLOBAL TRUE)\n    endif()\n    if(TARGET Python::Interpreter)\n      set_property(TARGET Python::Interpreter PROPERTY IMPORTED_GLOBAL TRUE)\n    endif()\n    if(TARGET Python::Module)\n      set_property(TARGET Python::Module PROPERTY IMPORTED_GLOBAL TRUE)\n    endif()\n  endif()\n\n  # Explicitly export version for callers (including our own functions)\n  if(NOT is_config AND Python_ARTIFACTS_INTERACTIVE)\n    set(Python_VERSION\n        \"${Python_VERSION}\"\n        CACHE INTERNAL \"\")\n    set(Python_VERSION_MAJOR\n        \"${Python_VERSION_MAJOR}\"\n        CACHE INTERNAL \"\")\n    set(Python_VERSION_MINOR\n        \"${Python_VERSION_MINOR}\"\n        CACHE INTERNAL \"\")\n    set(Python_VERSION_PATCH\n        \"${Python_VERSION_PATCH}\"\n        CACHE INTERNAL \"\")\n  endif()\nendif()\n\nif(Python_FOUND)\n  set(_Python\n      Python\n      CACHE INTERNAL \"\" FORCE)\nelseif(Python3_FOUND)\n  set(_Python\n      Python3\n      CACHE INTERNAL \"\" FORCE)\nendif()\n\nif(PYBIND11_MASTER_PROJECT)\n  if(${_Python}_INTERPRETER_ID MATCHES \"PyPy\")\n    message(STATUS \"PyPy ${${_Python}_PyPy_VERSION} (Py ${${_Python}_VERSION})\")\n  else()\n    message(STATUS \"${_Python} ${${_Python}_VERSION}\")\n  endif()\nendif()\n\nif(NOT _PYBIND11_CROSSCOMPILING AND DEFINED ${_Python}_EXECUTABLE)\n  if(DEFINED PYBIND11_PYTHON_EXECUTABLE_LAST AND NOT ${_Python}_EXECUTABLE STREQUAL\n                                                 PYBIND11_PYTHON_EXECUTABLE_LAST)\n    # Detect changes to the Python version/binary in subsequent CMake runs, and refresh config if needed\n    unset(PYTHON_IS_DEBUG CACHE)\n    unset(PYTHON_MODULE_EXTENSION CACHE)\n  endif()\n\n  set(PYBIND11_PYTHON_EXECUTABLE_LAST\n      \"${${_Python}_EXECUTABLE}\"\n      CACHE INTERNAL \"Python executable during the last CMake run\")\n\n  if(NOT DEFINED PYTHON_IS_DEBUG)\n    # Debug check - see https://stackoverflow.com/questions/646518/python-how-to-detect-debug-Interpreter\n    execute_process(\n      COMMAND \"${${_Python}_EXECUTABLE}\" \"-c\"\n              \"import sys; sys.exit(hasattr(sys, 'gettotalrefcount'))\"\n      RESULT_VARIABLE _PYTHON_IS_DEBUG)\n    set(PYTHON_IS_DEBUG\n        \"${_PYTHON_IS_DEBUG}\"\n        CACHE INTERNAL \"Python debug status\")\n  endif()\n\n  # Get the suffix - SO is deprecated, should use EXT_SUFFIX, but this is\n  # required for PyPy3 (as of 7.3.1)\n  if(NOT DEFINED PYTHON_MODULE_EXTENSION OR NOT DEFINED PYTHON_MODULE_DEBUG_POSTFIX)\n    execute_process(\n      COMMAND\n        \"${${_Python}_EXECUTABLE}\" \"-c\"\n        \"import sys, importlib; s = importlib.import_module('distutils.sysconfig' if sys.version_info < (3, 10) else 'sysconfig'); print(s.get_config_var('EXT_SUFFIX') or s.get_config_var('SO'))\"\n      OUTPUT_VARIABLE _PYTHON_MODULE_EXT_SUFFIX\n      ERROR_VARIABLE _PYTHON_MODULE_EXT_SUFFIX_ERR\n      OUTPUT_STRIP_TRAILING_WHITESPACE)\n\n    if(_PYTHON_MODULE_EXT_SUFFIX STREQUAL \"\")\n      message(\n        FATAL_ERROR\n          \"pybind11 could not query the module file extension, likely the 'distutils'\"\n          \"package is not installed. Full error message:\\n${_PYTHON_MODULE_EXT_SUFFIX_ERR}\")\n    endif()\n\n    # This needs to be available for the pybind11_extension function\n    if(NOT DEFINED PYTHON_MODULE_DEBUG_POSTFIX)\n      get_filename_component(_PYTHON_MODULE_DEBUG_POSTFIX \"${_PYTHON_MODULE_EXT_SUFFIX}\" NAME_WE)\n      set(PYTHON_MODULE_DEBUG_POSTFIX\n          \"${_PYTHON_MODULE_DEBUG_POSTFIX}\"\n          CACHE INTERNAL \"\")\n    endif()\n\n    if(NOT DEFINED PYTHON_MODULE_EXTENSION)\n      get_filename_component(_PYTHON_MODULE_EXTENSION \"${_PYTHON_MODULE_EXT_SUFFIX}\" EXT)\n      set(PYTHON_MODULE_EXTENSION\n          \"${_PYTHON_MODULE_EXTENSION}\"\n          CACHE INTERNAL \"\")\n      if((NOT \"$ENV{SETUPTOOLS_EXT_SUFFIX}\" STREQUAL \"\")\n         AND (NOT \"$ENV{SETUPTOOLS_EXT_SUFFIX}\" STREQUAL \"${PYTHON_MODULE_EXTENSION}\"))\n        message(\n          AUTHOR_WARNING,\n          \"SETUPTOOLS_EXT_SUFFIX is set to \\\"$ENV{SETUPTOOLS_EXT_SUFFIX}\\\", \"\n          \"but the auto-calculated Python extension suffix is \\\"${PYTHON_MODULE_EXTENSION}\\\". \"\n          \"This may cause problems when importing the Python extensions. \"\n          \"If you are using cross-compiling Python, you may need to \"\n          \"set PYTHON_MODULE_EXTENSION manually.\")\n      endif()\n    endif()\n  endif()\nelse()\n  if(NOT DEFINED PYTHON_IS_DEBUG\n     OR NOT DEFINED PYTHON_MODULE_EXTENSION\n     OR NOT DEFINED PYTHON_MODULE_DEBUG_POSTFIX)\n    include(\"${CMAKE_CURRENT_LIST_DIR}/pybind11GuessPythonExtSuffix.cmake\")\n    pybind11_guess_python_module_extension(\"${_Python}\")\n  endif()\n  if(NOT DEFINED PYTHON_IS_DEBUG\n     OR NOT DEFINED PYTHON_MODULE_EXTENSION\n     OR NOT DEFINED PYTHON_MODULE_DEBUG_POSTFIX)\n    message(\n      FATAL_ERROR\n        \"A Python interpreter was not found, or you are cross-compiling, and the \"\n        \"PYTHON_IS_DEBUG, PYTHON_MODULE_EXTENSION and PYTHON_MODULE_DEBUG_POSTFIX \"\n        \"variables could not be guessed. Set these variables appropriately before \"\n        \"loading pybind11 (e.g. in your CMake toolchain file)\")\n  endif()\nendif()\n\n# Python debug libraries expose slightly different objects before 3.8\n# https://docs.python.org/3.6/c-api/intro.html#debugging-builds\n# https://stackoverflow.com/questions/39161202/how-to-work-around-missing-pymodule-create2-in-amd64-win-python35-d-lib\nif(PYTHON_IS_DEBUG)\n  set_property(\n    TARGET pybind11::pybind11\n    APPEND\n    PROPERTY INTERFACE_COMPILE_DEFINITIONS Py_DEBUG)\nendif()\n\n# Check on every access - since Python can change - do nothing in that case.\n\nif(DEFINED ${_Python}_INCLUDE_DIRS)\n  # Only add Python for build - must be added during the import for config\n  # since it has to be re-discovered.\n  #\n  # This needs to be a target to be included after the local pybind11\n  # directory, just in case there there is an installed pybind11 sitting\n  # next to Python's includes. It also ensures Python is a SYSTEM library.\n  add_library(pybind11::python_headers INTERFACE IMPORTED)\n  set_property(\n    TARGET pybind11::python_headers PROPERTY INTERFACE_INCLUDE_DIRECTORIES\n                                             \"$<BUILD_INTERFACE:${${_Python}_INCLUDE_DIRS}>\")\n  set_property(\n    TARGET pybind11::pybind11\n    APPEND\n    PROPERTY INTERFACE_LINK_LIBRARIES pybind11::python_headers)\n  set(pybind11_INCLUDE_DIRS\n      \"${pybind11_INCLUDE_DIR}\" \"${${_Python}_INCLUDE_DIRS}\"\n      CACHE INTERNAL \"Directories where pybind11 and possibly Python headers are located\")\nendif()\n\n# In CMake 3.18+, you can find these separately, so include an if\nif(TARGET ${_Python}::Python)\n  set_property(\n    TARGET pybind11::embed\n    APPEND\n    PROPERTY INTERFACE_LINK_LIBRARIES ${_Python}::Python)\nendif()\n\nif(TARGET ${_Python}::Module)\n  # On Android, older versions of CMake don't know that modules need to link against\n  # libpython, so Python::Module will be an INTERFACE target with no associated library\n  # files.\n  get_target_property(module_target_type ${_Python}::Module TYPE)\n  if(ANDROID AND module_target_type STREQUAL INTERFACE_LIBRARY)\n    target_link_libraries(${_Python}::Module INTERFACE ${${_Python}_LIBRARIES})\n  endif()\n\n  set_property(\n    TARGET pybind11::module\n    APPEND\n    PROPERTY INTERFACE_LINK_LIBRARIES ${_Python}::Module)\nelse()\n  set_property(\n    TARGET pybind11::module\n    APPEND\n    PROPERTY INTERFACE_LINK_LIBRARIES pybind11::python_link_helper)\nendif()\n\n# WITHOUT_SOABI and WITH_SOABI will disable the custom extension handling used by pybind11.\n# WITH_SOABI is passed on to python_add_library.\nfunction(pybind11_add_module target_name)\n  cmake_parse_arguments(PARSE_ARGV 1 ARG\n                        \"STATIC;SHARED;MODULE;THIN_LTO;OPT_SIZE;NO_EXTRAS;WITHOUT_SOABI\" \"\" \"\")\n\n  if(ARG_STATIC)\n    set(lib_type STATIC)\n  elseif(ARG_SHARED)\n    set(lib_type SHARED)\n  else()\n    set(lib_type MODULE)\n  endif()\n\n  if(\"${_Python}\" STREQUAL \"Python\")\n    python_add_library(${target_name} ${lib_type} ${ARG_UNPARSED_ARGUMENTS})\n  elseif(\"${_Python}\" STREQUAL \"Python3\")\n    python3_add_library(${target_name} ${lib_type} ${ARG_UNPARSED_ARGUMENTS})\n  else()\n    message(FATAL_ERROR \"Cannot detect FindPython version: ${_Python}\")\n  endif()\n\n  target_link_libraries(${target_name} PRIVATE pybind11::headers)\n\n  if(lib_type STREQUAL \"MODULE\")\n    target_link_libraries(${target_name} PRIVATE pybind11::module)\n  else()\n    target_link_libraries(${target_name} PRIVATE pybind11::embed)\n  endif()\n\n  # -fvisibility=hidden is required to allow multiple modules compiled against\n  # different pybind versions to work properly, and for some features (e.g.\n  # py::module_local).  We force it on everything inside the `pybind11`\n  # namespace; also turning it on for a pybind module compilation here avoids\n  # potential warnings or issues from having mixed hidden/non-hidden types.\n  if(NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET)\n    set_target_properties(${target_name} PROPERTIES CXX_VISIBILITY_PRESET \"hidden\")\n  endif()\n\n  if(NOT DEFINED CMAKE_CUDA_VISIBILITY_PRESET)\n    set_target_properties(${target_name} PROPERTIES CUDA_VISIBILITY_PRESET \"hidden\")\n  endif()\n\n  # If we don't pass a WITH_SOABI or WITHOUT_SOABI, use our own default handling of extensions\n  if(NOT ARG_WITHOUT_SOABI AND NOT \"WITH_SOABI\" IN_LIST ARG_UNPARSED_ARGUMENTS)\n    pybind11_extension(${target_name})\n  endif()\n\n  if(ARG_NO_EXTRAS)\n    return()\n  endif()\n\n  if(NOT DEFINED CMAKE_INTERPROCEDURAL_OPTIMIZATION)\n    if(ARG_THIN_LTO)\n      target_link_libraries(${target_name} PRIVATE pybind11::thin_lto)\n    else()\n      target_link_libraries(${target_name} PRIVATE pybind11::lto)\n    endif()\n  endif()\n\n  if(DEFINED CMAKE_BUILD_TYPE) # see https://github.com/pybind/pybind11/issues/4454\n    # Use case-insensitive comparison to match the result of $<CONFIG:cfgs>\n    string(TOUPPER \"${CMAKE_BUILD_TYPE}\" uppercase_CMAKE_BUILD_TYPE)\n    if(NOT MSVC AND NOT \"${uppercase_CMAKE_BUILD_TYPE}\" MATCHES DEBUG|RELWITHDEBINFO|NONE)\n      # Strip unnecessary sections of the binary on Linux/macOS\n      pybind11_strip(${target_name})\n    endif()\n  endif()\n\n  if(MSVC)\n    target_link_libraries(${target_name} PRIVATE pybind11::windows_extras)\n  endif()\n\n  if(ARG_OPT_SIZE)\n    target_link_libraries(${target_name} PRIVATE pybind11::opt_size)\n  endif()\nendfunction()\n\nfunction(pybind11_extension name)\n  # The extension is precomputed\n  set_target_properties(\n    ${name}\n    PROPERTIES PREFIX \"\"\n               DEBUG_POSTFIX \"${PYTHON_MODULE_DEBUG_POSTFIX}\"\n               SUFFIX \"${PYTHON_MODULE_EXTENSION}\")\nendfunction()\n"
  },
  {
    "path": "tools/pybind11Tools.cmake",
    "content": "# tools/pybind11Tools.cmake -- Build system for the pybind11 modules\n#\n# Copyright (c) 2020 Wenzel Jakob <wenzel.jakob@epfl.ch>\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\ninclude_guard(DIRECTORY)\n\nif(pybind11_FIND_QUIETLY)\n  set(_pybind11_quiet QUIET)\nelse()\n  set(_pybind11_quiet \"\")\nendif()\n\n# If this is the first run, PYTHON_VERSION can stand in for PYBIND11_PYTHON_VERSION\nif(NOT DEFINED PYBIND11_PYTHON_VERSION AND DEFINED PYTHON_VERSION)\n  message(WARNING \"Set PYBIND11_PYTHON_VERSION to search for a specific version, not \"\n                  \"PYTHON_VERSION (which is an output). Assuming that is what you \"\n                  \"meant to do and continuing anyway.\")\n  set(PYBIND11_PYTHON_VERSION\n      \"${PYTHON_VERSION}\"\n      CACHE STRING \"Python version to use for compiling modules\")\n  unset(PYTHON_VERSION)\n  unset(PYTHON_VERSION CACHE)\nelseif(DEFINED PYBIND11_PYTHON_VERSION)\n  # If this is set as a normal variable, promote it\n  set(PYBIND11_PYTHON_VERSION\n      \"${PYBIND11_PYTHON_VERSION}\"\n      CACHE STRING \"Python version to use for compiling modules\")\nelse()\n  # Make an empty cache variable.\n  set(PYBIND11_PYTHON_VERSION\n      \"\"\n      CACHE STRING \"Python version to use for compiling modules\")\nendif()\n\n# A user can set versions manually too\nset(Python_ADDITIONAL_VERSIONS\n    \"3.12;3.11;3.10;3.9;3.8\"\n    CACHE INTERNAL \"\")\n\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_CURRENT_LIST_DIR}\")\nfind_package(PythonLibsNew ${PYBIND11_PYTHON_VERSION} MODULE REQUIRED ${_pybind11_quiet})\nlist(REMOVE_AT CMAKE_MODULE_PATH -1)\n\n# Makes a normal variable a cached variable\nmacro(_PYBIND11_PROMOTE_TO_CACHE NAME)\n  set(_tmp_ptc \"${${NAME}}\")\n  # CMake 3.21 complains if a cached variable is shadowed by a normal one\n  unset(${NAME})\n  set(${NAME}\n      \"${_tmp_ptc}\"\n      CACHE INTERNAL \"\")\nendmacro()\n\n# Cache variables so pybind11_add_module can be used in parent projects\n_pybind11_promote_to_cache(PYTHON_INCLUDE_DIRS)\n_pybind11_promote_to_cache(PYTHON_LIBRARIES)\n_pybind11_promote_to_cache(PYTHON_MODULE_PREFIX)\n_pybind11_promote_to_cache(PYTHON_MODULE_EXTENSION)\n_pybind11_promote_to_cache(PYTHON_MODULE_DEBUG_POSTFIX)\n_pybind11_promote_to_cache(PYTHON_VERSION_MAJOR)\n_pybind11_promote_to_cache(PYTHON_VERSION_MINOR)\n_pybind11_promote_to_cache(PYTHON_VERSION)\n_pybind11_promote_to_cache(PYTHON_IS_DEBUG)\n\nif(PYBIND11_MASTER_PROJECT)\n  if(PYTHON_MODULE_EXTENSION MATCHES \"pypy\")\n    if(NOT DEFINED PYPY_VERSION)\n      execute_process(\n        COMMAND ${PYTHON_EXECUTABLE} -c\n                [=[import sys; sys.stdout.write(\".\".join(map(str, sys.pypy_version_info[:3])))]=]\n        OUTPUT_VARIABLE pypy_version)\n      set(PYPY_VERSION\n          ${pypy_version}\n          CACHE INTERNAL \"\")\n    endif()\n    message(STATUS \"PYPY ${PYPY_VERSION} (Py ${PYTHON_VERSION})\")\n  else()\n    message(STATUS \"PYTHON ${PYTHON_VERSION}\")\n  endif()\nendif()\n\n# Only add Python for build - must be added during the import for config since\n# it has to be re-discovered.\n#\n# This needs to be an target to it is included after the local pybind11\n# directory, just in case there are multiple versions of pybind11, we want the\n# one we expect.\nadd_library(pybind11::python_headers INTERFACE IMPORTED)\nset_property(TARGET pybind11::python_headers PROPERTY INTERFACE_INCLUDE_DIRECTORIES\n                                                      \"$<BUILD_INTERFACE:${PYTHON_INCLUDE_DIRS}>\")\nset_property(\n  TARGET pybind11::pybind11\n  APPEND\n  PROPERTY INTERFACE_LINK_LIBRARIES pybind11::python_headers)\n\nset(pybind11_INCLUDE_DIRS\n    \"${pybind11_INCLUDE_DIR}\" \"${PYTHON_INCLUDE_DIRS}\"\n    CACHE INTERNAL \"Directories where pybind11 and possibly Python headers are located\")\n\n# Python debug libraries expose slightly different objects before 3.8\n# https://docs.python.org/3.6/c-api/intro.html#debugging-builds\n# https://stackoverflow.com/questions/39161202/how-to-work-around-missing-pymodule-create2-in-amd64-win-python35-d-lib\nif(PYTHON_IS_DEBUG)\n  set_property(\n    TARGET pybind11::pybind11\n    APPEND\n    PROPERTY INTERFACE_COMPILE_DEFINITIONS Py_DEBUG)\nendif()\n\n# The IMPORTED INTERFACE library here is to ensure that \"debug\" and \"release\" get processed outside\n# of a generator expression - https://gitlab.kitware.com/cmake/cmake/-/issues/18424, as they are\n# target_link_library keywords rather than real libraries.\nadd_library(pybind11::_ClassicPythonLibraries IMPORTED INTERFACE)\ntarget_link_libraries(pybind11::_ClassicPythonLibraries INTERFACE ${PYTHON_LIBRARIES})\ntarget_link_libraries(\n  pybind11::module\n  INTERFACE\n    pybind11::python_link_helper\n    \"$<$<OR:$<PLATFORM_ID:Windows>,$<PLATFORM_ID:Cygwin>,$<PLATFORM_ID:Android>>:pybind11::_ClassicPythonLibraries>\"\n)\n\ntarget_link_libraries(pybind11::embed INTERFACE pybind11::pybind11\n                                                pybind11::_ClassicPythonLibraries)\n\nfunction(pybind11_extension name)\n  # The prefix and extension are provided by FindPythonLibsNew.cmake\n  set_target_properties(\n    ${name}\n    PROPERTIES PREFIX \"${PYTHON_MODULE_PREFIX}\"\n               DEBUG_POSTFIX \"${PYTHON_MODULE_DEBUG_POSTFIX}\"\n               SUFFIX \"${PYTHON_MODULE_EXTENSION}\")\nendfunction()\n\n# Build a Python extension module:\n# pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]\n#                     [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])\n#\nfunction(pybind11_add_module target_name)\n  set(options \"MODULE;SHARED;EXCLUDE_FROM_ALL;NO_EXTRAS;SYSTEM;THIN_LTO;OPT_SIZE\")\n  cmake_parse_arguments(ARG \"${options}\" \"\" \"\" ${ARGN})\n\n  if(ARG_MODULE AND ARG_SHARED)\n    message(FATAL_ERROR \"Can't be both MODULE and SHARED\")\n  elseif(ARG_SHARED)\n    set(lib_type SHARED)\n  else()\n    set(lib_type MODULE)\n  endif()\n\n  if(ARG_EXCLUDE_FROM_ALL)\n    set(exclude_from_all EXCLUDE_FROM_ALL)\n  else()\n    set(exclude_from_all \"\")\n  endif()\n\n  add_library(${target_name} ${lib_type} ${exclude_from_all} ${ARG_UNPARSED_ARGUMENTS})\n\n  target_link_libraries(${target_name} PRIVATE pybind11::module)\n\n  if(ARG_SYSTEM)\n    message(\n      STATUS\n        \"Warning: this does not have an effect - use NO_SYSTEM_FROM_IMPORTED if using imported targets\"\n    )\n  endif()\n\n  pybind11_extension(${target_name})\n\n  # -fvisibility=hidden is required to allow multiple modules compiled against\n  # different pybind versions to work properly, and for some features (e.g.\n  # py::module_local).  We force it on everything inside the `pybind11`\n  # namespace; also turning it on for a pybind module compilation here avoids\n  # potential warnings or issues from having mixed hidden/non-hidden types.\n  if(NOT DEFINED CMAKE_CXX_VISIBILITY_PRESET)\n    set_target_properties(${target_name} PROPERTIES CXX_VISIBILITY_PRESET \"hidden\")\n  endif()\n\n  if(NOT DEFINED CMAKE_CUDA_VISIBILITY_PRESET)\n    set_target_properties(${target_name} PROPERTIES CUDA_VISIBILITY_PRESET \"hidden\")\n  endif()\n\n  if(ARG_NO_EXTRAS)\n    return()\n  endif()\n\n  if(NOT DEFINED CMAKE_INTERPROCEDURAL_OPTIMIZATION)\n    if(ARG_THIN_LTO)\n      target_link_libraries(${target_name} PRIVATE pybind11::thin_lto)\n    else()\n      target_link_libraries(${target_name} PRIVATE pybind11::lto)\n    endif()\n  endif()\n\n  if(DEFINED CMAKE_BUILD_TYPE) # see https://github.com/pybind/pybind11/issues/4454\n    # Use case-insensitive comparison to match the result of $<CONFIG:cfgs>\n    string(TOUPPER \"${CMAKE_BUILD_TYPE}\" uppercase_CMAKE_BUILD_TYPE)\n    if(NOT MSVC AND NOT \"${uppercase_CMAKE_BUILD_TYPE}\" MATCHES DEBUG|RELWITHDEBINFO|NONE)\n      pybind11_strip(${target_name})\n    endif()\n  endif()\n\n  if(MSVC)\n    target_link_libraries(${target_name} PRIVATE pybind11::windows_extras)\n  endif()\n\n  if(ARG_OPT_SIZE)\n    target_link_libraries(${target_name} PRIVATE pybind11::opt_size)\n  endif()\nendfunction()\n\n# Provide general way to call common Python commands in \"common\" file.\nset(_Python\n    PYTHON\n    CACHE INTERNAL \"\" FORCE)\n"
  },
  {
    "path": "tools/test-pybind11GuessPythonExtSuffix.cmake",
    "content": "cmake_minimum_required(VERSION 3.15...4.2)\n\n# Tests for pybind11_guess_python_module_extension\n# Run using `cmake -P tools/test-pybind11GuessPythonExtSuffix.cmake`\n\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/pybind11GuessPythonExtSuffix.cmake\")\n\nmacro(expect_streq actual expected)\n  if(NOT \"${actual}\" STREQUAL \"${expected}\")\n    message(SEND_ERROR \"Fail\\n *** actual:   '${actual}'\\n *** expected: '${expected}'\")\n  endif()\nendmacro()\n\nmacro(expect_false actual)\n  if(\"${actual}\")\n    message(SEND_ERROR \"Fail\\n *** actual:   '${actual}'\\n *** expected: false\")\n  endif()\nendmacro()\n\nmacro(expect_true actual)\n  if(NOT \"${actual}\")\n    message(SEND_ERROR \"Fail\\n *** actual:   '${actual}'\\n *** expected: true\")\n  endif()\nendmacro()\n\n# Windows\nset(CMAKE_SYSTEM_NAME \"Windows\")\nset(CMAKE_SHARED_MODULE_SUFFIX \".dll\")\n\nset(Python3_SOABI \"\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cp311-win_arm64\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cp311-win_arm64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cp311d-win_arm64\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cp311d-win_arm64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_true(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"pypy310-pp73-win_amd64\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".pypy310-pp73-win_amd64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"_d.cp311-win_amd64.pyd\") # This is a quirk of FindPython3\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cp311-win_amd64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"_d\")\nexpect_true(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nunset(Python3_SOABI)\nset(ENV{SETUPTOOLS_EXT_SUFFIX} \".cp39-win_arm64.pyd\") # Set by cibuildwheel\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cp39-win_arm64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\nunset(ENV{SETUPTOOLS_EXT_SUFFIX})\n\nset(Python3_SOABI \"cp311-win_arm64\")\nset(ENV{SETUPTOOLS_EXT_SUFFIX} \"\") # Should not be used\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cp311-win_arm64.pyd\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\nunset(ENV{SETUPTOOLS_EXT_SUFFIX})\n\n# Check the priority of the possible suffix sources.\nset(ENV{SETUPTOOLS_EXT_SUFFIX} \".from-setuptools.pyd\")\nset(SKBUILD_SOABI \"from-skbuild\")\nset(Python3_SOABI \"from-python3\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".from-setuptools.pyd\")\n\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\nunset(ENV{SETUPTOOLS_EXT_SUFFIX})\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".from-skbuild.pyd\")\n\nunset(SKBUILD_SOABI)\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".from-python3.pyd\")\n\nset(Python3_SOABI \"\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".pyd\")\n\nunset(Python3_SOABI)\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \"\")\n\n# macOS\nset(CMAKE_SYSTEM_NAME \"Darwin\")\nset(CMAKE_SHARED_MODULE_SUFFIX \".so\")\n\nset(Python3_SOABI \"\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cpython-312-darwin\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cpython-312-darwin.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cpython-312d-darwin\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cpython-312d-darwin.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_true(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\n# Linux\nset(CMAKE_SYSTEM_NAME \"Linux\")\nset(CMAKE_SHARED_MODULE_SUFFIX \".so\")\n\nset(Python3_SOABI \"\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cpython-312-arm-linux-gnueabihf\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cpython-312-arm-linux-gnueabihf.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"cpython-312d-arm-linux-gnueabihf\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".cpython-312d-arm-linux-gnueabihf.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_true(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"pypy310-pp73-x86_64-linux-gnu\")\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".pypy310-pp73-x86_64-linux-gnu.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_false(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n\nset(Python3_SOABI \"pypy310d-pp73-x86_64-linux-gnu\")\n# TODO: I'm not sure if this is the right SOABI for PyPy debug builds\npybind11_guess_python_module_extension(\"Python3\")\nexpect_streq(\"${PYTHON_MODULE_EXTENSION}\" \".pypy310d-pp73-x86_64-linux-gnu.so\")\nexpect_streq(\"${PYTHON_MODULE_DEBUG_POSTFIX}\" \"\")\nexpect_true(\"${PYTHON_IS_DEBUG}\")\nunset(PYTHON_MODULE_EXT_SUFFIX)\nunset(PYTHON_MODULE_EXT_SUFFIX CACHE)\n"
  }
]