github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/docs/advanced/misc.rst (about)

     1  Miscellaneous
     2  #############
     3  
     4  .. _macro_notes:
     5  
     6  General notes regarding convenience macros
     7  ==========================================
     8  
     9  pybind11 provides a few convenience macros such as
    10  :func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERRIDE_*``. Since these
    11  are "just" macros that are evaluated in the preprocessor (which has no concept
    12  of types), they *will* get confused by commas in a template argument; for
    13  example, consider:
    14  
    15  .. code-block:: cpp
    16  
    17      PYBIND11_OVERRIDE(MyReturnType<T1, T2>, Class<T3, T4>, func)
    18  
    19  The limitation of the C preprocessor interprets this as five arguments (with new
    20  arguments beginning after each comma) rather than three.  To get around this,
    21  there are two alternatives: you can use a type alias, or you can wrap the type
    22  using the ``PYBIND11_TYPE`` macro:
    23  
    24  .. code-block:: cpp
    25  
    26      // Version 1: using a type alias
    27      using ReturnType = MyReturnType<T1, T2>;
    28      using ClassType = Class<T3, T4>;
    29      PYBIND11_OVERRIDE(ReturnType, ClassType, func);
    30  
    31      // Version 2: using the PYBIND11_TYPE macro:
    32      PYBIND11_OVERRIDE(PYBIND11_TYPE(MyReturnType<T1, T2>),
    33                        PYBIND11_TYPE(Class<T3, T4>), func)
    34  
    35  The ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.
    36  
    37  .. _gil:
    38  
    39  Global Interpreter Lock (GIL)
    40  =============================
    41  
    42  The Python C API dictates that the Global Interpreter Lock (GIL) must always
    43  be held by the current thread to safely access Python objects. As a result,
    44  when Python calls into C++ via pybind11 the GIL must be held, and pybind11
    45  will never implicitly release the GIL.
    46  
    47  .. code-block:: cpp
    48  
    49      void my_function() {
    50          /* GIL is held when this function is called from Python */
    51      }
    52  
    53      PYBIND11_MODULE(example, m) {
    54          m.def("my_function", &my_function);
    55      }
    56  
    57  pybind11 will ensure that the GIL is held when it knows that it is calling
    58  Python code. For example, if a Python callback is passed to C++ code via
    59  ``std::function``, when C++ code calls the function the built-in wrapper
    60  will acquire the GIL before calling the Python callback. Similarly, the
    61  ``PYBIND11_OVERRIDE`` family of macros will acquire the GIL before calling
    62  back into Python.
    63  
    64  When writing C++ code that is called from other C++ code, if that code accesses
    65  Python state, it must explicitly acquire and release the GIL.
    66  
    67  The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
    68  used to acquire and release the global interpreter lock in the body of a C++
    69  function call. In this way, long-running C++ code can be parallelized using
    70  multiple Python threads, **but great care must be taken** when any
    71  :class:`gil_scoped_release` appear: if there is any way that the C++ code
    72  can access Python objects, :class:`gil_scoped_acquire` should be used to
    73  reacquire the GIL. Taking :ref:`overriding_virtuals` as an example, this
    74  could be realized as follows (important changes highlighted):
    75  
    76  .. code-block:: cpp
    77      :emphasize-lines: 8,30,31
    78  
    79      class PyAnimal : public Animal {
    80      public:
    81          /* Inherit the constructors */
    82          using Animal::Animal;
    83  
    84          /* Trampoline (need one for each virtual function) */
    85          std::string go(int n_times) {
    86              /* PYBIND11_OVERRIDE_PURE will acquire the GIL before accessing Python state */
    87              PYBIND11_OVERRIDE_PURE(
    88                  std::string, /* Return type */
    89                  Animal,      /* Parent class */
    90                  go,          /* Name of function */
    91                  n_times      /* Argument(s) */
    92              );
    93          }
    94      };
    95  
    96      PYBIND11_MODULE(example, m) {
    97          py::class_<Animal, PyAnimal> animal(m, "Animal");
    98          animal
    99              .def(py::init<>())
   100              .def("go", &Animal::go);
   101  
   102          py::class_<Dog>(m, "Dog", animal)
   103              .def(py::init<>());
   104  
   105          m.def("call_go", [](Animal *animal) -> std::string {
   106              // GIL is held when called from Python code. Release GIL before
   107              // calling into (potentially long-running) C++ code
   108              py::gil_scoped_release release;
   109              return call_go(animal);
   110          });
   111      }
   112  
   113  The ``call_go`` wrapper can also be simplified using the ``call_guard`` policy
   114  (see :ref:`call_policies`) which yields the same result:
   115  
   116  .. code-block:: cpp
   117  
   118      m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
   119  
   120  
   121  Common Sources Of Global Interpreter Lock Errors
   122  ==================================================================
   123  
   124  Failing to properly hold the Global Interpreter Lock (GIL) is one of the
   125  more common sources of bugs within code that uses pybind11. If you are
   126  running into GIL related errors, we highly recommend you consult the
   127  following checklist.
   128  
   129  - Do you have any global variables that are pybind11 objects or invoke
   130    pybind11 functions in either their constructor or destructor? You are generally
   131    not allowed to invoke any Python function in a global static context. We recommend
   132    using lazy initialization and then intentionally leaking at the end of the program.
   133  
   134  - Do you have any pybind11 objects that are members of other C++ structures? One
   135    commonly overlooked requirement is that pybind11 objects have to increase their reference count
   136    whenever their copy constructor is called. Thus, you need to be holding the GIL to invoke
   137    the copy constructor of any C++ class that has a pybind11 member. This can sometimes be very
   138    tricky to track for complicated programs Think carefully when you make a pybind11 object
   139    a member in another struct.
   140  
   141  - C++ destructors that invoke Python functions can be particularly troublesome as
   142    destructors can sometimes get invoked in weird and unexpected circumstances as a result
   143    of exceptions.
   144  
   145  - You should try running your code in a debug build. That will enable additional assertions
   146    within pybind11 that will throw exceptions on certain GIL handling errors
   147    (reference counting operations).
   148  
   149  Binding sequence data types, iterators, the slicing protocol, etc.
   150  ==================================================================
   151  
   152  Please refer to the supplemental example for details.
   153  
   154  .. seealso::
   155  
   156      The file :file:`tests/test_sequences_and_iterators.cpp` contains a
   157      complete example that shows how to bind a sequence data type, including
   158      length queries (``__len__``), iterators (``__iter__``), the slicing
   159      protocol and other kinds of useful operations.
   160  
   161  
   162  Partitioning code over multiple extension modules
   163  =================================================
   164  
   165  It's straightforward to split binding code over multiple extension modules,
   166  while referencing types that are declared elsewhere. Everything "just" works
   167  without any special precautions. One exception to this rule occurs when
   168  extending a type declared in another extension module. Recall the basic example
   169  from Section :ref:`inheritance`.
   170  
   171  .. code-block:: cpp
   172  
   173      py::class_<Pet> pet(m, "Pet");
   174      pet.def(py::init<const std::string &>())
   175         .def_readwrite("name", &Pet::name);
   176  
   177      py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
   178          .def(py::init<const std::string &>())
   179          .def("bark", &Dog::bark);
   180  
   181  Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
   182  whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
   183  course that the variable ``pet`` is not available anymore though it is needed
   184  to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
   185  However, it can be acquired as follows:
   186  
   187  .. code-block:: cpp
   188  
   189      py::object pet = (py::object) py::module_::import("basic").attr("Pet");
   190  
   191      py::class_<Dog>(m, "Dog", pet)
   192          .def(py::init<const std::string &>())
   193          .def("bark", &Dog::bark);
   194  
   195  Alternatively, you can specify the base class as a template parameter option to
   196  ``class_``, which performs an automated lookup of the corresponding Python
   197  type. Like the above code, however, this also requires invoking the ``import``
   198  function once to ensure that the pybind11 binding code of the module ``basic``
   199  has been executed:
   200  
   201  .. code-block:: cpp
   202  
   203      py::module_::import("basic");
   204  
   205      py::class_<Dog, Pet>(m, "Dog")
   206          .def(py::init<const std::string &>())
   207          .def("bark", &Dog::bark);
   208  
   209  Naturally, both methods will fail when there are cyclic dependencies.
   210  
   211  Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
   212  via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
   213  required for proper pybind11 functionality, can interfere with the ability to
   214  access types defined in another extension module.  Working around this requires
   215  manually exporting types that are accessed by multiple extension modules;
   216  pybind11 provides a macro to do just this:
   217  
   218  .. code-block:: cpp
   219  
   220      class PYBIND11_EXPORT Dog : public Animal {
   221          ...
   222      };
   223  
   224  Note also that it is possible (although would rarely be required) to share arbitrary
   225  C++ objects between extension modules at runtime. Internal library data is shared
   226  between modules using capsule machinery [#f6]_ which can be also utilized for
   227  storing, modifying and accessing user-defined data. Note that an extension module
   228  will "see" other extensions' data if and only if they were built with the same
   229  pybind11 version. Consider the following example:
   230  
   231  .. code-block:: cpp
   232  
   233      auto data = reinterpret_cast<MyData *>(py::get_shared_data("mydata"));
   234      if (!data)
   235          data = static_cast<MyData *>(py::set_shared_data("mydata", new MyData(42)));
   236  
   237  If the above snippet was used in several separately compiled extension modules,
   238  the first one to be imported would create a ``MyData`` instance and associate
   239  a ``"mydata"`` key with a pointer to it. Extensions that are imported later
   240  would be then able to access the data behind the same pointer.
   241  
   242  .. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
   243  
   244  Module Destructors
   245  ==================
   246  
   247  pybind11 does not provide an explicit mechanism to invoke cleanup code at
   248  module destruction time. In rare cases where such functionality is required, it
   249  is possible to emulate it using Python capsules or weak references with a
   250  destruction callback.
   251  
   252  .. code-block:: cpp
   253  
   254      auto cleanup_callback = []() {
   255          // perform cleanup here -- this function is called with the GIL held
   256      };
   257  
   258      m.add_object("_cleanup", py::capsule(cleanup_callback));
   259  
   260  This approach has the potential downside that instances of classes exposed
   261  within the module may still be alive when the cleanup callback is invoked
   262  (whether this is acceptable will generally depend on the application).
   263  
   264  Alternatively, the capsule may also be stashed within a type object, which
   265  ensures that it not called before all instances of that type have been
   266  collected:
   267  
   268  .. code-block:: cpp
   269  
   270      auto cleanup_callback = []() { /* ... */ };
   271      m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
   272  
   273  Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
   274  Python, which may be undesirable from an API standpoint (a premature explicit
   275  call from Python might lead to undefined behavior). Yet another approach that
   276  avoids this issue involves weak reference with a cleanup callback:
   277  
   278  .. code-block:: cpp
   279  
   280      // Register a callback function that is invoked when the BaseClass object is collected
   281      py::cpp_function cleanup_callback(
   282          [](py::handle weakref) {
   283              // perform cleanup here -- this function is called with the GIL held
   284  
   285              weakref.dec_ref(); // release weak reference
   286          }
   287      );
   288  
   289      // Create a weak reference with a cleanup callback and initially leak it
   290      (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
   291  
   292  .. note::
   293  
   294      PyPy does not garbage collect objects when the interpreter exits. An alternative
   295      approach (which also works on CPython) is to use the :py:mod:`atexit` module [#f7]_,
   296      for example:
   297  
   298      .. code-block:: cpp
   299  
   300          auto atexit = py::module_::import("atexit");
   301          atexit.attr("register")(py::cpp_function([]() {
   302              // perform cleanup here -- this function is called with the GIL held
   303          }));
   304  
   305      .. [#f7] https://docs.python.org/3/library/atexit.html
   306  
   307  
   308  Generating documentation using Sphinx
   309  =====================================
   310  
   311  Sphinx [#f4]_ has the ability to inspect the signatures and documentation
   312  strings in pybind11-based extension modules to automatically generate beautiful
   313  documentation in a variety formats. The python_example repository [#f5]_ contains a
   314  simple example repository which uses this approach.
   315  
   316  There are two potential gotchas when using this approach: first, make sure that
   317  the resulting strings do not contain any :kbd:`TAB` characters, which break the
   318  docstring parsing routines. You may want to use C++11 raw string literals,
   319  which are convenient for multi-line comments. Conveniently, any excess
   320  indentation will be automatically be removed by Sphinx. However, for this to
   321  work, it is important that all lines are indented consistently, i.e.:
   322  
   323  .. code-block:: cpp
   324  
   325      // ok
   326      m.def("foo", &foo, R"mydelimiter(
   327          The foo function
   328  
   329          Parameters
   330          ----------
   331      )mydelimiter");
   332  
   333      // *not ok*
   334      m.def("foo", &foo, R"mydelimiter(The foo function
   335  
   336          Parameters
   337          ----------
   338      )mydelimiter");
   339  
   340  By default, pybind11 automatically generates and prepends a signature to the docstring of a function
   341  registered with ``module_::def()`` and ``class_::def()``. Sometimes this
   342  behavior is not desirable, because you want to provide your own signature or remove
   343  the docstring completely to exclude the function from the Sphinx documentation.
   344  The class ``options`` allows you to selectively suppress auto-generated signatures:
   345  
   346  .. code-block:: cpp
   347  
   348      PYBIND11_MODULE(example, m) {
   349          py::options options;
   350          options.disable_function_signatures();
   351  
   352          m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
   353      }
   354  
   355  pybind11 also appends all members of an enum to the resulting enum docstring.
   356  This default behavior can be disabled by using the ``disable_enum_members_docstring()``
   357  function of the ``options`` class.
   358  
   359  With ``disable_user_defined_docstrings()`` all user defined docstrings of
   360  ``module_::def()``, ``class_::def()`` and ``enum_()`` are disabled, but the
   361  function signatures and enum members are included in the docstring, unless they
   362  are disabled separately.
   363  
   364  Note that changes to the settings affect only function bindings created during the
   365  lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
   366  the default settings are restored to prevent unwanted side effects.
   367  
   368  .. [#f4] http://www.sphinx-doc.org
   369  .. [#f5] http://github.com/pybind/python_example
   370  
   371  .. _avoiding-cpp-types-in-docstrings:
   372  
   373  Avoiding C++ types in docstrings
   374  ================================
   375  
   376  Docstrings are generated at the time of the declaration, e.g. when ``.def(...)`` is called.
   377  At this point parameter and return types should be known to pybind11.
   378  If a custom type is not exposed yet through a ``py::class_`` constructor or a custom type caster,
   379  its C++ type name will be used instead to generate the signature in the docstring:
   380  
   381  .. code-block:: text
   382  
   383       |  __init__(...)
   384       |      __init__(self: example.Foo, arg0: ns::Bar) -> None
   385                                                ^^^^^^^
   386  
   387  
   388  This limitation can be circumvented by ensuring that C++ classes are registered with pybind11
   389  before they are used as a parameter or return type of a function:
   390  
   391  .. code-block:: cpp
   392  
   393      PYBIND11_MODULE(example, m) {
   394  
   395          auto pyFoo = py::class_<ns::Foo>(m, "Foo");
   396          auto pyBar = py::class_<ns::Bar>(m, "Bar");
   397  
   398          pyFoo.def(py::init<const ns::Bar&>());
   399          pyBar.def(py::init<const ns::Foo&>());
   400      }