PyO3 / pyo3

Rust bindings for the Python interpreter
https://pyo3.rs
Other
11.47k stars 694 forks source link

Use `Ident::parse_any` for `name` attributes #4226

Closed Databean closed 1 month ago

Databean commented 1 month ago

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:

An identifier constructed with Ident::new is permitted to be a Rust keyword, though parsing one through its Parse implementation rejects Rust keywords. Use input.call(Ident::parse_any) when parsing to match the behaviour of Ident::new.

Fixes issue #4225

adamreichold commented 1 month ago

Could you please add your example as a test case so that we do not regress on this in the future? Thank!

(It would be nice if it covered as many places as possible, e.g. functions, methods, properties, etc.)

Databean commented 1 month ago

Added test cases and a newsfragments entry.