Skip to content

Commit

Permalink
Use a full path for #[new] method which is also #[classmethod].
Browse files Browse the repository at this point in the history
lifthrasiir committed May 29, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent d930bc1 commit c2d4e8a
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pyo3-macros-backend/src/method.rs
Original file line number Diff line number Diff line change
@@ -506,7 +506,9 @@ impl<'a> FnSpec<'a> {
let (arg_convert, args) = impl_arg_params(self, cls, &py, false)?;
let call = match &self.tp {
FnType::FnNew => quote! { #rust_name(#(#args),*) },
FnType::FnNewClass => quote! { #rust_name(PyType::from_type_ptr(#py, subtype), #(#args),*) },
FnType::FnNewClass => {
quote! { #rust_name(_pyo3::types::PyType::from_type_ptr(#py, subtype), #(#args),*) }
}
x => panic!("Only `FnNew` or `FnNewClass` may use the `TpNew` calling convention. Got: {:?}", x),
};
quote! {
23 changes: 23 additions & 0 deletions tests/test_no_imports.rs
Original file line number Diff line number Diff line change
@@ -121,3 +121,26 @@ fn test_basic() {
pyo3::py_run!(py, *d, "b += a; assert (b.v, b.s) == (19, 'foobar!')");
});
}

#[pyo3::pyclass]
struct NewClassMethod {
#[pyo3(get)]
cls: pyo3::PyObject,
}

#[pyo3::pymethods]
impl NewClassMethod {
#[new]
#[classmethod]
fn new(cls: &pyo3::types::PyType) -> Self {
Self { cls: cls.into() }
}
}

#[test]
fn test_new_class_method() {
pyo3::Python::with_gil(|py| {
let cls = py.get_type::<NewClassMethod>();
pyo3::py_run!(py, cls, "assert cls().cls is cls");
});
}

0 comments on commit c2d4e8a

Please sign in to comment.