Skip to content

Commit

Permalink
document and test raw idents with signature
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Oct 22, 2022
1 parent cf53228 commit 775e917
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
12 changes: 12 additions & 0 deletions guide/src/function/signature.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,18 @@ num=44
num=-1
```

> Note: for keywords like `struct`, to use it as a function argument, use "raw ident" syntax `r#struct` in both the signature and the function definition:
>
> ```rust
> # !#[allow(unused_code)]
> # use pyo3::prelude::*;
> #[pyfunction(signature = (r#struct = "foo"))]
> fn method_with_keyword<'a>(&self, r#struct: &'a str) {
> # let _ = r#struct;
> /* ... */
> }
> ```
## Deprecated form
The `#[pyfunction]` macro can take the argument specification directly, but this method is deprecated in PyO3 0.18 because the `#[pyo3(signature)]` option offers a simpler syntax and better validation.
Expand Down
4 changes: 2 additions & 2 deletions pyo3-macros-backend/src/pyfunction/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,11 +348,11 @@ impl<'a> FunctionSignature<'a> {
let mut next_argument_checked = |name: &syn::Ident| match args_iter.next() {
Some(fn_arg) => {
ensure_spanned!(
name == &fn_arg.name.unraw(),
name == fn_arg.name,
name.span() => format!(
"expected argument from function definition `{}` but got argument `{}`",
fn_arg.name.unraw(),
name,
name.unraw(),
)
);
Ok(fn_arg)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,11 @@ impl r#RawIdents {

#[classattr]
const r#CLASS_ATTR_CONST: i32 = 6;

#[pyo3(signature = (r#struct = "foo"))]
fn method_with_keyword<'a>(&self, r#struct: &'a str) -> &'a str {
r#struct
}
}

#[test]
Expand Down Expand Up @@ -1377,6 +1382,10 @@ fn test_raw_idents() {
assert raw_idents_type.class_attr_fn == 5
assert raw_idents_type.CLASS_ATTR_CONST == 6
assert instance.method_with_keyword() == "foo"
assert instance.method_with_keyword("bar") == "bar"
assert instance.method_with_keyword(struct="baz") == "baz"
"#
);
})
Expand Down

0 comments on commit 775e917

Please sign in to comment.