/usr/share/doc/pybind11-doc/html/advanced/functions.html is in pybind11-doc 2.0.1-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | <!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Functions — pybind11 2.0.1 documentation</title>
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/theme_overrides.css" type="text/css" />
<link rel="index" title="Index"
href="../genindex.html"/>
<link rel="search" title="Search" href="../search.html"/>
<link rel="top" title="pybind11 2.0.1 documentation" href="../index.html"/>
<link rel="next" title="Classes" href="classes.html"/>
<link rel="prev" title="Build systems" href="../compiling.html"/>
<script src="../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../index.html" class="icon icon-home"> pybind11
</a>
<div class="version">
2.0
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../intro.html">About this project</a></li>
<li class="toctree-l1"><a class="reference internal" href="../changelog.html">Changelog</a></li>
</ul>
<p class="caption"><span class="caption-text">The Basics</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../basics.html">First steps</a></li>
<li class="toctree-l1"><a class="reference internal" href="../classes.html">Object-oriented code</a></li>
<li class="toctree-l1"><a class="reference internal" href="../compiling.html">Build systems</a></li>
</ul>
<p class="caption"><span class="caption-text">Advanced Topics</span></p>
<ul class="current">
<li class="toctree-l1 current"><a class="current reference internal" href="#">Functions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#return-value-policies">Return value policies</a></li>
<li class="toctree-l2"><a class="reference internal" href="#additional-call-policies">Additional call policies</a></li>
<li class="toctree-l2"><a class="reference internal" href="#python-objects-as-arguments">Python objects as arguments</a></li>
<li class="toctree-l2"><a class="reference internal" href="#accepting-args-and-kwargs">Accepting *args and **kwargs</a></li>
<li class="toctree-l2"><a class="reference internal" href="#default-arguments-revisited">Default arguments revisited</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="classes.html">Classes</a></li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">Exceptions</a></li>
<li class="toctree-l1"><a class="reference internal" href="smart_ptrs.html">Smart pointers</a></li>
<li class="toctree-l1"><a class="reference internal" href="cast/index.html">Type conversions</a></li>
<li class="toctree-l1"><a class="reference internal" href="pycpp/index.html">Python C++ interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="misc.html">Miscellaneous</a></li>
</ul>
<p class="caption"><span class="caption-text">Extra Information</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../faq.html">Frequently asked questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../benchmark.html">Benchmark</a></li>
<li class="toctree-l1"><a class="reference internal" href="../limitations.html">Limitations</a></li>
<li class="toctree-l1"><a class="reference internal" href="../reference.html">Reference</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">pybind11</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> »</li>
<li>Functions</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/advanced/functions.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="functions">
<h1>Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h1>
<p>Before proceeding with this section, make sure that you are already familiar
with the basics of binding functions and classes, as explained in <a class="reference internal" href="../basics.html"><span class="doc">First steps</span></a>
and <a class="reference internal" href="../classes.html"><span class="doc">Object-oriented code</span></a>. The following guide is applicable to both free and member
functions, i.e. <em>methods</em> in Python.</p>
<div class="section" id="return-value-policies">
<h2>Return value policies<a class="headerlink" href="#return-value-policies" title="Permalink to this headline">¶</a></h2>
<p>Python and C++ use fundamentally different ways of managing the memory and
lifetime of objects managed by them. This can lead to issues when creating
bindings for functions that return a non-trivial type. Just by looking at the
type information, it is not clear whether Python should take charge of the
returned value and eventually free its resources, or if this is handled on the
C++ side. For this reason, pybind11 provides a several <cite>return value policy</cite>
annotations that can be passed to the <a class="reference internal" href="../reference.html#_CPPv2I0DpEN6module3defEPKcRR4FuncDpRR5Extra" title="module::def"><code class="xref cpp cpp-func docutils literal"><span class="pre">module::def()</span></code></a> and
<code class="xref cpp cpp-func docutils literal"><span class="pre">class_::def()</span></code> functions. The default policy is
<code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::automatic</span></code>.</p>
<p>Return value policies are tricky, and it’s very important to get them right.
Just to illustrate what can go wrong, consider the following simple example:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="cm">/* Function declaration */</span>
<span class="n">Data</span> <span class="o">*</span><span class="nf">get_data</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">_data</span><span class="p">;</span> <span class="cm">/* (pointer to a static data structure) */</span> <span class="p">}</span>
<span class="p">...</span>
<span class="cm">/* Binding code */</span>
<span class="n">m</span><span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"get_data"</span><span class="p">,</span> <span class="o">&</span><span class="n">get_data</span><span class="p">);</span> <span class="c1">// <-- KABOOM, will cause crash when called from Python</span>
</pre></div>
</div>
<p>What’s going on here? When <code class="docutils literal"><span class="pre">get_data()</span></code> is called from Python, the return
value (a native C++ type) must be wrapped to turn it into a usable Python type.
In this case, the default return value policy (<code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::automatic</span></code>)
causes pybind11 to assume ownership of the static <code class="docutils literal"><span class="pre">_data</span></code> instance.</p>
<p>When Python’s garbage collector eventually deletes the Python
wrapper, pybind11 will also attempt to delete the C++ instance (via <code class="docutils literal"><span class="pre">operator</span>
<span class="pre">delete()</span></code>) due to the implied ownership. At this point, the entire application
will come crashing down, though errors could also be more subtle and involve
silent data corruption.</p>
<p>In the above example, the policy <code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::reference</span></code> should have
been specified so that the global data instance is only <em>referenced</em> without any
implied transfer of ownership, i.e.:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">m</span><span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"get_data"</span><span class="p">,</span> <span class="o">&</span><span class="n">get_data</span><span class="p">,</span> <span class="n">return_value_policy</span><span class="o">::</span><span class="n">reference</span><span class="p">);</span>
</pre></div>
</div>
<p>On the other hand, this is not the right policy for many other situations,
where ignoring ownership could lead to resource leaks.
As a developer using pybind11, it’s important to be familiar with the different
return value policies, including which situation calls for which one of them.
The following table provides an overview of available policies:</p>
<table border="1" class="docutils">
<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Return value policy</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::take_ownership</span></code></td>
<td>Reference an existing object (i.e. do not create a new copy) and take
ownership. Python will call the destructor and delete operator when the
object’s reference count reaches zero. Undefined behavior ensues when the
C++ side does the same, or when the data was not dynamically allocated.</td>
</tr>
<tr class="row-odd"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::copy</span></code></td>
<td>Create a new copy of the returned object, which will be owned by Python.
This policy is comparably safe because the lifetimes of the two instances
are decoupled.</td>
</tr>
<tr class="row-even"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::move</span></code></td>
<td>Use <code class="docutils literal"><span class="pre">std::move</span></code> to move the return value contents into a new instance
that will be owned by Python. This policy is comparably safe because the
lifetimes of the two instances (move source and destination) are decoupled.</td>
</tr>
<tr class="row-odd"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::reference</span></code></td>
<td>Reference an existing object, but do not take ownership. The C++ side is
responsible for managing the object’s lifetime and deallocating it when
it is no longer used. Warning: undefined behavior will ensue when the C++
side deletes an object that is still referenced and used by Python.</td>
</tr>
<tr class="row-even"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::reference_internal</span></code></td>
<td>Indicates that the lifetime of the return value is tied to the lifetime
of a parent object, namely the implicit <code class="docutils literal"><span class="pre">this</span></code>, or <code class="docutils literal"><span class="pre">self</span></code> argument of
the called method or property. Internally, this policy works just like
<code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::reference</span></code> but additionally applies a
<code class="docutils literal"><span class="pre">keep_alive<0,</span> <span class="pre">1></span></code> <em>call policy</em> (described in the next section) that
prevents the parent object from being garbage collected as long as the
return value is referenced by Python. This is the default policy for
property getters created via <code class="docutils literal"><span class="pre">def_property</span></code>, <code class="docutils literal"><span class="pre">def_readwrite</span></code>, etc.</td>
</tr>
<tr class="row-odd"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::automatic</span></code></td>
<td>This is the default return value policy, which falls back to the policy
<code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::take_ownership</span></code> when the return value is a
pointer. Otherwise, it uses <code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value::move</span></code> or
<code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value::copy</span></code> for rvalue and lvalue references, respectively.
See above for a description of what all of these different policies do.</td>
</tr>
<tr class="row-even"><td><code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::automatic_reference</span></code></td>
<td>As above, but use policy <code class="xref cpp cpp-enum docutils literal"><span class="pre">return_value_policy::reference</span></code> when the
return value is a pointer. This is the default conversion policy for
function arguments when calling Python functions manually from C++ code
(i.e. via handle::operator()). You probably won’t need to use this.</td>
</tr>
</tbody>
</table>
<p>Return value policies can also be applied to properties:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">class_</span><span class="o"><</span><span class="n">MyClass</span><span class="o">></span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">"MyClass"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def_property</span><span class="p">(</span><span class="s">"data"</span><span class="p">,</span> <span class="o">&</span><span class="n">MyClass</span><span class="o">::</span><span class="n">getData</span><span class="p">,</span> <span class="o">&</span><span class="n">MyClass</span><span class="o">::</span><span class="n">setData</span><span class="p">,</span>
<span class="n">py</span><span class="o">::</span><span class="n">return_value_policy</span><span class="o">::</span><span class="n">copy</span><span class="p">);</span>
</pre></div>
</div>
<p>Technically, the code above applies the policy to both the getter and the
setter function, however, the setter doesn’t really care about <em>return</em>
value policies which makes this a convenient terse syntax. Alternatively,
targeted arguments can be passed through the <code class="xref cpp cpp-class docutils literal"><span class="pre">cpp_function</span></code> constructor:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">class_</span><span class="o"><</span><span class="n">MyClass</span><span class="o">></span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">"MyClass"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def_property</span><span class="p">(</span><span class="s">"data"</span>
<span class="n">py</span><span class="o">::</span><span class="n">cpp_function</span><span class="p">(</span><span class="o">&</span><span class="n">MyClass</span><span class="o">::</span><span class="n">getData</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">return_value_policy</span><span class="o">::</span><span class="n">copy</span><span class="p">),</span>
<span class="n">py</span><span class="o">::</span><span class="n">cpp_function</span><span class="p">(</span><span class="o">&</span><span class="n">MyClass</span><span class="o">::</span><span class="n">setData</span><span class="p">)</span>
<span class="p">);</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Code with invalid return value policies might access unitialized memory or
free data structures multiple times, which can lead to hard-to-debug
non-determinism and segmentation faults, hence it is worth spending the
time to understand all the different options in the table above.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">One important aspect of the above policies is that they only apply to
instances which pybind11 has <em>not</em> seen before, in which case the policy
clarifies essential questions about the return value’s lifetime and
ownership. When pybind11 knows the instance already (as identified by its
type and address in memory), it will return the existing Python object
wrapper rather than creating a new copy.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The next section on <a class="reference internal" href="#call-policies"><span class="std std-ref">Additional call policies</span></a> discusses <em>call policies</em> that can be
specified <em>in addition</em> to a return value policy from the list above. Call
policies indicate reference relationships that can involve both return values
and parameters of functions.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">As an alternative to elaborate call policies and lifetime management logic,
consider using smart pointers (see the section on <a class="reference internal" href="smart_ptrs.html#id1"><span class="std std-ref">Custom smart pointers</span></a> for
details). Smart pointers can tell whether an object is still referenced from
C++ or Python, which generally eliminates the kinds of inconsistencies that
can lead to crashes or undefined behavior. For functions returning smart
pointers, it is not necessary to specify a return value policy.</p>
</div>
</div>
<div class="section" id="additional-call-policies">
<span id="call-policies"></span><h2>Additional call policies<a class="headerlink" href="#additional-call-policies" title="Permalink to this headline">¶</a></h2>
<p>In addition to the above return value policies, further <cite>call policies</cite> can be
specified to indicate dependencies between parameters. There is currently just
one policy named <code class="docutils literal"><span class="pre">keep_alive<Nurse,</span> <span class="pre">Patient></span></code>, which indicates that the
argument with index <code class="docutils literal"><span class="pre">Patient</span></code> should be kept alive at least until the
argument with index <code class="docutils literal"><span class="pre">Nurse</span></code> is freed by the garbage collector. Argument
indices start at one, while zero refers to the return value. For methods, index
<code class="docutils literal"><span class="pre">1</span></code> refers to the implicit <code class="docutils literal"><span class="pre">this</span></code> pointer, while regular arguments begin at
index <code class="docutils literal"><span class="pre">2</span></code>. Arbitrarily many call policies can be specified. When a <code class="docutils literal"><span class="pre">Nurse</span></code>
with value <code class="docutils literal"><span class="pre">None</span></code> is detected at runtime, the call policy does nothing.</p>
<p>This feature internally relies on the ability to create a <em>weak reference</em> to
the nurse object, which is permitted by all classes exposed via pybind11. When
the nurse object does not support weak references, an exception will be thrown.</p>
<p>Consider the following example: here, the binding code for a list append
operation ties the lifetime of the newly added element to the underlying
container:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">py</span><span class="o">::</span><span class="n">class_</span><span class="o"><</span><span class="n">List</span><span class="o">></span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">"List"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"append"</span><span class="p">,</span> <span class="o">&</span><span class="n">List</span><span class="o">::</span><span class="n">append</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">keep_alive</span><span class="o"><</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="o">></span><span class="p">());</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal"><span class="pre">keep_alive</span></code> is analogous to the <code class="docutils literal"><span class="pre">with_custodian_and_ward</span></code> (if Nurse,
Patient != 0) and <code class="docutils literal"><span class="pre">with_custodian_and_ward_postcall</span></code> (if Nurse/Patient ==
0) policies from Boost.Python.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The file <code class="file docutils literal"><span class="pre">tests/test_keep_alive.cpp</span></code> contains a complete example
that demonstrates using <code class="xref cpp cpp-class docutils literal"><span class="pre">keep_alive</span></code> in more detail.</p>
</div>
</div>
<div class="section" id="python-objects-as-arguments">
<span id="python-objects-as-args"></span><h2>Python objects as arguments<a class="headerlink" href="#python-objects-as-arguments" title="Permalink to this headline">¶</a></h2>
<p>pybind11 exposes all major Python types using thin C++ wrapper classes. These
wrapper classes can also be used as parameters of functions in bindings, which
makes it possible to directly work with native Python types on the C++ side.
For instance, the following statement iterates over a Python <code class="docutils literal"><span class="pre">dict</span></code>:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">print_dict</span><span class="p">(</span><span class="n">py</span><span class="o">::</span><span class="n">dict</span> <span class="n">dict</span><span class="p">)</span> <span class="p">{</span>
<span class="cm">/* Easily interact with Python types */</span>
<span class="k">for</span> <span class="p">(</span><span class="k">auto</span> <span class="nl">item</span> <span class="p">:</span> <span class="n">dict</span><span class="p">)</span>
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"key="</span> <span class="o"><<</span> <span class="n">item</span><span class="p">.</span><span class="n">first</span> <span class="o"><<</span> <span class="s">", "</span>
<span class="o"><<</span> <span class="s">"value="</span> <span class="o"><<</span> <span class="n">item</span><span class="p">.</span><span class="n">second</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>It can be exported:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">m</span><span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"print_dict"</span><span class="p">,</span> <span class="o">&</span><span class="n">print_dict</span><span class="p">);</span>
</pre></div>
</div>
<p>And used in Python as usual:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">print_dict</span><span class="p">({</span><span class="s1">'foo'</span><span class="p">:</span> <span class="mi">123</span><span class="p">,</span> <span class="s1">'bar'</span><span class="p">:</span> <span class="s1">'hello'</span><span class="p">})</span>
<span class="go">key=foo, value=123</span>
<span class="go">key=bar, value=hello</span>
</pre></div>
</div>
<p>For more information on using Python objects in C++, see <a class="reference internal" href="pycpp/index.html"><span class="doc">Python C++ interface</span></a>.</p>
</div>
<div class="section" id="accepting-args-and-kwargs">
<h2>Accepting *args and **kwargs<a class="headerlink" href="#accepting-args-and-kwargs" title="Permalink to this headline">¶</a></h2>
<p>Python provides a useful mechanism to define functions that accept arbitrary
numbers of arguments and keyword arguments:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generic</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="o">...</span> <span class="c1"># do something with args and kwargs</span>
</pre></div>
</div>
<p>Such functions can also be created using pybind11:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">generic</span><span class="p">(</span><span class="n">py</span><span class="o">::</span><span class="n">args</span> <span class="n">args</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">kwargs</span> <span class="n">kwargs</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">/// .. do something with args</span>
<span class="k">if</span> <span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
<span class="c1">/// .. do something with kwargs</span>
<span class="p">}</span>
<span class="c1">/// Binding code</span>
<span class="n">m</span><span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"generic"</span><span class="p">,</span> <span class="o">&</span><span class="n">generic</span><span class="p">);</span>
</pre></div>
</div>
<p>The class <code class="docutils literal"><span class="pre">py::args</span></code> derives from <code class="docutils literal"><span class="pre">py::tuple</span></code> and <code class="docutils literal"><span class="pre">py::kwargs</span></code> derives
from <code class="docutils literal"><span class="pre">py::dict</span></code>. Note that the <code class="docutils literal"><span class="pre">kwargs</span></code> argument is invalid if no keyword
arguments were actually provided. Please refer to the other examples for
details on how to iterate over these, and on how to cast their entries into
C++ objects. A demonstration is also available in
<code class="docutils literal"><span class="pre">tests/test_kwargs_and_defaults.cpp</span></code>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Unlike Python, pybind11 does not allow combining normal parameters with the
<code class="docutils literal"><span class="pre">args</span></code> / <code class="docutils literal"><span class="pre">kwargs</span></code> special parameters.</p>
</div>
</div>
<div class="section" id="default-arguments-revisited">
<h2>Default arguments revisited<a class="headerlink" href="#default-arguments-revisited" title="Permalink to this headline">¶</a></h2>
<p>The section on <a class="reference internal" href="../basics.html#default-args"><span class="std std-ref">Default arguments</span></a> previously discussed basic usage of default
arguments using pybind11. One noteworthy aspect of their implementation is that
default arguments are converted to Python objects right at declaration time.
Consider the following example:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">py</span><span class="o">::</span><span class="n">class_</span><span class="o"><</span><span class="n">MyClass</span><span class="o">></span><span class="p">(</span><span class="s">"MyClass"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"myFunction"</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">arg</span><span class="p">(</span><span class="s">"arg"</span><span class="p">)</span> <span class="o">=</span> <span class="n">SomeType</span><span class="p">(</span><span class="mi">123</span><span class="p">));</span>
</pre></div>
</div>
<p>In this case, pybind11 must already be set up to deal with values of the type
<code class="docutils literal"><span class="pre">SomeType</span></code> (via a prior instantiation of <code class="docutils literal"><span class="pre">py::class_<SomeType></span></code>), or an
exception will be thrown.</p>
<p>Another aspect worth highlighting is that the “preview” of the default argument
in the function signature is generated using the object’s <code class="docutils literal"><span class="pre">__repr__</span></code> method.
If not available, the signature may not be very helpful, e.g.:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span></span><span class="go">FUNCTIONS</span>
<span class="gp">...</span>
<span class="go">| myFunction(...)</span>
<span class="go">| Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>The first way of addressing this is by defining <code class="docutils literal"><span class="pre">SomeType.__repr__</span></code>.
Alternatively, it is possible to specify the human-readable preview of the
default argument manually using the <code class="docutils literal"><span class="pre">arg_v</span></code> notation:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">py</span><span class="o">::</span><span class="n">class_</span><span class="o"><</span><span class="n">MyClass</span><span class="o">></span><span class="p">(</span><span class="s">"MyClass"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"myFunction"</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">arg_v</span><span class="p">(</span><span class="s">"arg"</span><span class="p">,</span> <span class="n">SomeType</span><span class="p">(</span><span class="mi">123</span><span class="p">),</span> <span class="s">"SomeType(123)"</span><span class="p">));</span>
</pre></div>
</div>
<p>Sometimes it may be necessary to pass a null pointer value as a default
argument. In this case, remember to cast it to the underlying type in question,
like so:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span></span><span class="n">py</span><span class="o">::</span><span class="n">class_</span><span class="o"><</span><span class="n">MyClass</span><span class="o">></span><span class="p">(</span><span class="s">"MyClass"</span><span class="p">)</span>
<span class="p">.</span><span class="n">def</span><span class="p">(</span><span class="s">"myFunction"</span><span class="p">,</span> <span class="n">py</span><span class="o">::</span><span class="n">arg</span><span class="p">(</span><span class="s">"arg"</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">SomeType</span> <span class="o">*</span><span class="p">)</span> <span class="k">nullptr</span><span class="p">);</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="classes.html" class="btn btn-neutral float-right" title="Classes" accesskey="n">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="../compiling.html" class="btn btn-neutral" title="Build systems" accesskey="p"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, Wenzel Jakob.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../',
VERSION:'2.0.1',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html>
|