Skip to content

Commit 41ba6f9

Browse files
docs: Include example of calling with PyDict for kwargs (PyO3#5078)
* Include example of calling with PyDict for kwargs Resolve PyO3#1462 * remove empty line --------- Co-authored-by: Icxolu <[email protected]>
1 parent caf35f9 commit 41ba6f9

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

guide/src/python-from-rust/function-calls.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,13 @@ fn main() -> PyResult<()> {
5959

6060
## Creating keyword arguments
6161

62-
For the `call` and `call_method` APIs, `kwargs` are `Option<&Bound<'py, PyDict>>`, so can either be `None` or `Some(&dict)`. You can use the [`IntoPyDict`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.IntoPyDict.html) trait to convert other dict-like containers, e.g. `HashMap` or `BTreeMap`, as well as tuples with up to 10 elements and `Vec`s where each element is a two-element tuple.
62+
For the `call` and `call_method` APIs, `kwargs` are `Option<&Bound<'py, PyDict>>`, so can either be `None` or `Some(&dict)`. You can use the [`IntoPyDict`]({{#PYO3_DOCS_URL}}/pyo3/types/trait.IntoPyDict.html) trait to convert other dict-like containers, e.g. `HashMap` or `BTreeMap`, as well as tuples with up to 10 elements and `Vec`s where each element is a two-element tuple. To pass keyword arguments of different types, construct a `PyDict` object.
6363

6464
```rust
6565
use pyo3::prelude::*;
66-
use pyo3::types::IntoPyDict;
66+
use pyo3::types::{PyDict, IntoPyDict};
6767
use std::collections::HashMap;
68-
use pyo3_ffi::c_str;
68+
use pyo3::ffi::c_str;
6969

7070
fn main() -> PyResult<()> {
7171
let key1 = "key1";
@@ -102,7 +102,13 @@ fn main() -> PyResult<()> {
102102
kwargs.insert(key1, 1);
103103
fun.call(py, (), Some(&kwargs.into_py_dict(py)?))?;
104104

105+
// pass arguments of different types as PyDict
106+
let kwargs = PyDict::new(py);
107+
kwargs.set_item(key1, val1)?;
108+
kwargs.set_item(key2, "string")?;
109+
fun.call(py, (), Some(&kwargs))?;
110+
105111
Ok(())
106112
})
107113
}
108-
```
114+
```

0 commit comments

Comments
 (0)