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

Give a method a different name from it's signature #1242

Closed
alvitawa opened this issue Oct 17, 2020 · 3 comments
Closed

Give a method a different name from it's signature #1242

alvitawa opened this issue Oct 17, 2020 · 3 comments

Comments

@alvitawa
Copy link

alvitawa commented Oct 17, 2020

I have been looking around the documentation but I have not found a way to specify a different name for a class method than the rust function signature.

According to the docs you can do this for a standard function like so:

#[pymodule]
fn rust2py(py: Python, m: &PyModule) -> PyResult<()> {

    #[pyfn(m, "sum_as_string")]
    fn sum_as_string_py(_py: Python, a:i64, b:i64) -> PyResult<String> {
        Ok(format!("{}", a + b))
    }

    Ok(())
}

(rust function is called 'sum_as_string_py', but in python you call 'sum_as_string'

I would love to be able to do something similar for a classes' methods:

#[pymethods]
impl Dataset {
    #[pyname = "add_feature"]
    fn add_feature_py(&mut self, matrix: &PyArray1<bool>) -> PyResult<()> {
        Ok(())
    }
}

This way you can give functions in the rust interface the same name as their python counterparts:

impl Dataset {
    fn add_feature(&mut self, matrix: Vec<bool>) -> { }
}
@kngwyu
Copy link
Member

kngwyu commented Oct 18, 2020

You can do

#[pymethods]
impl Dataset {
    #[name = "add_feature"]
    fn add_feature_py(&mut self, matrix: &PyArray1<bool>) -> PyResult<()> {
        Ok(())
    }
}

@kngwyu kngwyu closed this as completed Oct 18, 2020
@cmyr
Copy link
Contributor

cmyr commented Apr 28, 2021

Pardon the bump but just found this when I had the same question. Maybe it would be helpful if the available annotations were listed in the guide?

@davidhewitt
Copy link
Member

@cmyr no problem at all, I agree there's a documentation issue here. I've been trying to start solving this problem by making the attribute syntax more uniform: #1567

The idea being that the attribute will become #[pyo3(name = "...")], and we'll document all the options that the #[pyo3(...)] attribute will support.

If you have a moment to read through that PR, I'd welcome your opinion on the design proposal.

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

No branches or pull requests

4 participants