Skip to content

Commit

Permalink
Use Ident::parse_any for name attributes
Browse files Browse the repository at this point in the history
This makes it possible to use rust keywords as the name of python class
methods and standalone functions. For example:

```
struct MyClass {
}

impl MyClass {
    #[new]
    fn new() -> Self {
        MyClass {}
    }

    #[pyo3(name = "struct")]
    fn struct_method(&self) -> usize {
        42
    }
}

fn struct_function() -> usize {
    42
}
```

From the [`syn::Ident`
documentation](https://docs.rs/syn/2.0.66/syn/struct.Ident.html):

> An identifier constructed with `Ident::new` is permitted to be a Rust
keyword, though parsing one through its
[`Parse`](https://docs.rs/syn/2.0.66/syn/parse/trait.Parse.html)
implementation rejects Rust keywords. Use `input.call(Ident::parse_any)`
when parsing to match the behaviour of `Ident::new`.

Fixes issue #4225
  • Loading branch information
Databean committed Jun 2, 2024
1 parent 5d47c4a commit d7a7811
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
1 change: 1 addition & 0 deletions newsfragments/4226.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixes a compile error when declaring a standalone function or class method with a Python name that is a Rust keyword.
3 changes: 2 additions & 1 deletion pyo3-macros-backend/src/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned,
Expand Down Expand Up @@ -72,7 +73,7 @@ pub struct NameLitStr(pub Ident);
impl Parse for NameLitStr {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let string_literal: LitStr = input.parse()?;
if let Ok(ident) = string_literal.parse() {
if let Ok(ident) = string_literal.parse_with(Ident::parse_any) {
Ok(NameLitStr(ident))
} else {
bail_spanned!(string_literal.span() => "expected a single identifier in double quotes")
Expand Down
30 changes: 30 additions & 0 deletions tests/test_class_basics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,36 @@ fn custom_names() {
});
}

#[pyclass(name = "loop")]
struct ClassRustKeywords {
#[pyo3(name = "unsafe", get, set)]
unsafe_variable: usize,
}

#[pymethods]
impl ClassRustKeywords {
#[pyo3(name = "struct")]
fn struct_method(&self) {}

#[staticmethod]
#[pyo3(name = "type")]
fn type_method() {}
}

#[test]
fn keyword_names() {
Python::with_gil(|py| {
let typeobj = py.get_type_bound::<ClassRustKeywords>();
py_assert!(py, typeobj, "typeobj.__name__ == 'loop'");
py_assert!(py, typeobj, "typeobj.struct.__name__ == 'struct'");
py_assert!(py, typeobj, "typeobj.type.__name__ == 'type'");
py_assert!(py, typeobj, "typeobj.unsafe.__name__ == 'unsafe'");
py_assert!(py, typeobj, "not hasattr(typeobj, 'unsafe_variable')");
py_assert!(py, typeobj, "not hasattr(typeobj, 'struct_method')");
py_assert!(py, typeobj, "not hasattr(typeobj, 'type_method')");
});
}

#[pyclass]
struct RawIdents {
#[pyo3(get, set)]
Expand Down
12 changes: 12 additions & 0 deletions tests/test_pyfunction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ use pyo3::types::{self, PyCFunction};
#[path = "../src/tests/common.rs"]
mod common;

#[pyfunction(name = "struct")]
fn struct_function() {}

#[test]
fn test_rust_keyword_name() {
Python::with_gil(|py| {
let f = wrap_pyfunction_bound!(struct_function)(py).unwrap();

py_assert!(py, f, "f.__name__ == 'struct'");
});
}

#[pyfunction(signature = (arg = true))]
fn optional_bool(arg: Option<bool>) -> String {
format!("{:?}", arg)
Expand Down

0 comments on commit d7a7811

Please sign in to comment.