Search code examples
rustpyo3

Calling from Python Rust function with kwargs fails


I am struggling to get kwargs to work. I understand that just like #[args(args="*")] is for args, #[args(kwargs="**")] is for kwargs.

However when I pack the following using pyo3-pack and try to call test1 with any arguments I get the error MyClass.test1()() takes at most 0 argument (1 given).

What am I doing wrong?

#![feature(custom_attribute)]
#![feature(specialization)]

use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};

#[pyclass]
struct MyClass {}

#[pymethods]
impl MyClass {
    #[staticmethod]
    #[args(kwargs = "**")]
    fn test1(kwargs: Option<&PyDict>) -> PyResult<()> {
        if let Some(kwargs) = kwargs {
            for kwarg in kwargs {
                println!("{:?}", kwarg);
            }
        } else {
            println!("kwargs is none");
        }
        Ok(())
    }

    #[staticmethod]
    #[args(args = "*")]
    fn test2(args: &PyTuple) -> PyResult<()> {
        for arg in args {
            println!("{:?}", arg);
        }
        Ok(())
    }
}


#[pymodule]
fn test123(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<MyClass>()?;
    Ok(())
}

Solution

  • I’m pretty sure this is a bug in PyO3: this check seems to be adding nkeywords for no reason. File a GitHub issue and see what the maintainers say.