Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Functions implemented with macro are not treated as python methods in block #[pymethod] #2862

Closed
n0b0dyCN opened this issue Jan 6, 2023 · 2 comments · Fixed by #3491
Closed

Comments

@n0b0dyCN
Copy link

n0b0dyCN commented Jan 6, 2023

Bug Description

Example code:

use pyo3::prelude::*;

#[pyclass]
pub struct A;

macro_rules! impl_method {
    ($fn:ident) => {
        pub fn $fn(&self) -> PyResult<()> {
            println!("{}", stringify!($fn));
            Ok(())
        }
    };
}

#[pymethods]
impl A {
    pub fn a(&self) -> PyResult<()> {
        println!("a");
        Ok(())
    }

    impl_method!(b);
    impl_method!(c);
}

#[pymodule]
fn pyo3_example(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_class::<A>()?;
    Ok(())
}

Test python code:

from pyo3_example import A

print(dir(A))

Expect behaviour: function a, b and c should be printed.

Current behavious: only function a is printed.

Steps to Reproduce

For quick reproduce, clone repo https://github.com/n0b0dyCN/pyo3_example and follow readme.

Backtrace

No response

Your operating system and version

Linux MY_HOST_NAME 5.15.0-56-generic #62~20.04.1-Ubuntu SMP Tue Nov 22 21:24:20 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Your Python version (python --version)

Python 3.8.10

Your Rust version (rustc --version)

rustc 1.65.0-nightly (d394408fb 2022-08-07)

Your PyO3 version

0.17.3

How did you install python? Did you use a virtualenv?

use python -m venv

Additional Info

No response

@n0b0dyCN n0b0dyCN added the bug label Jan 6, 2023
@davidhewitt
Copy link
Member

This is known and a fundamental limitation of how Rust macros work. The pymethods macro just sees the unexpanded impl_method! syntax. Instead you should create a bigger impl_methods! macro which expands to a #[pymethods].

We can improve the documentation and error for this case.

@n0b0dyCN
Copy link
Author

n0b0dyCN commented Jan 9, 2023

This is known and a fundamental limitation of how Rust macros work. The pymethods macro just sees the unexpanded impl_method! syntax. Instead you should create a bigger impl_methods! macro which expands to a #[pymethods].

We can improve the documentation and error for this case.

Thanks for your reply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants