Merge pull request #328 from Alexander-N/kwargs

Fix **kwargs
This commit is contained in:
Yuji Kanagawa 2019-01-28 12:53:27 +09:00 committed by GitHub
commit 20dbf542c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 1 deletions

View File

@ -45,7 +45,7 @@ pub fn parse_fn_args<'p>(
) -> PyResult<()> {
let nargs = args.len();
let nkeywords = kwargs.map_or(0, |d| d.len());
if !accept_args && (nargs + nkeywords > params.len()) {
if !accept_args && !accept_kwargs && (nargs + nkeywords > params.len()) {
return Err(TypeError::py_err(format!(
"{}{} takes at most {} argument{} ({} given)",
fname.unwrap_or("function"),

View File

@ -0,0 +1,52 @@
#![feature(custom_attribute)]
#![feature(specialization)]
extern crate pyo3;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#[macro_use]
mod common;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[staticmethod]
#[args(args = "*")]
fn test_args(args: &PyTuple) -> PyResult<&PyTuple> {
Ok(args)
}
#[staticmethod]
#[args(kwargs = "**")]
fn test_kwargs(kwargs: Option<&PyDict>) -> PyResult<Option<&PyDict>> {
Ok(kwargs)
}
}
#[test]
fn variable_args() {
let gil = Python::acquire_gil();
let py = gil.python();
let my_obj = py.get_type::<MyClass>();
py_assert!(py, my_obj, "my_obj.test_args() == ()");
py_assert!(py, my_obj, "my_obj.test_args(1) == (1,)");
py_assert!(py, my_obj, "my_obj.test_args(1, 2) == (1, 2)");
}
#[test]
fn variable_kwargs() {
let gil = Python::acquire_gil();
let py = gil.python();
let my_obj = py.get_type::<MyClass>();
py_assert!(py, my_obj, "my_obj.test_kwargs() == None");
py_assert!(py, my_obj, "my_obj.test_kwargs(test=1) == {'test': 1}");
py_assert!(
py,
my_obj,
"my_obj.test_kwargs(test1=1, test2=2) == {'test1':1, 'test2':2}"
);
}