Open Databean opened 1 month ago
Created #4226 to fix this issue.
This is also already possibly by using a raw identifier:
#[pyo3(name = "r#struct")]
fn struct_method(&self) -> usize {
42
}
This is also already possibly by using a raw identifier:
#[pyo3(name = "r#struct")] fn struct_method(&self) -> usize { 42 }
This does work for the method, thanks:
>> import pyo3_example >> m = pyo3_example.MyClass() >> m.struct() 42
But it does not work for the standalone function:
>> import pyo3_example >> pyo3_example.struct() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'pyo3_example' has no attribute 'struct'. Did you mean: 'r#struct'? >> pyo3_example.r#struct Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'pyo3_example' has no attribute 'r' >> pyo3_example["r#struct"] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'module' object is not subscriptable
#[pyo3(name = r#struct)]
doesn't work either, still givingerror: expected string literal --> src/lib.rs:21:15 | 21 | #[pyo3(name = r#struct)] | ^^^^^^^^
It does work for standalone functions, if you use the raw identifier for the function itself:
#[pyfunction]
fn r#struct() -> usize {
42
}
The syntax for the pyo3
attribute is (notice the quotes):
#[pyfunction]
#[pyo3(name = "r#struct")]
fn some_function -> usize {
42
}
But this currently does also not work, but I would consider that a bug (I did track that down already, so fixing that should be easy).
I'd hope that name = "r#struct"
shouldn't be necessary, as I mostly view the r#
bit as a syntax ugly that's necessary to escape the parser handling keywords when not wanted. So my personal take is that I'd probably prefer
#[pyfunction]
#[pyo3(name = "r#struct")]
fn some_function -> usize {
42
}
to continue to be invalid.
Just for reference, your example is not invalid (in the sense that is does compile just fine), it just produces no usable function on the Python side.
😬
Bug Description
Using a rust keyword as the name of a function, e.g.
#[pyo3(name = "<struct>")]
results in a compilation error.Steps to Reproduce
Sample program:
Backtrace
Your operating system and version
Your Python version (
python --version
)Python 3.12.3
Your Rust version (
rustc --version
)rustc 1.80.0-nightly (867900499 2024-05-23)
Your PyO3 version
0.21.2
How did you install python? Did you use a virtualenv?
Additional Info
struct
is not a reserved word in Python, so it works normally as Python code: