Skip to content

Commit

Permalink
hygiene: fix #[pymethods(crate = "...")]
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jan 27, 2023
1 parent 98b1297 commit 5667a09
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions newsfragments/2923.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `#[pymethods(crate = "...")]` option being ignored.
15 changes: 12 additions & 3 deletions pyo3-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,13 @@ pub fn pyclass(attr: TokenStream, input: TokenStream) -> TokenStream {
/// [10]: https://pyo3.rs/latest/class.html#method-arguments
/// [11]: https://pyo3.rs/latest/class.html#object-properties-using-pyo3get-set
#[proc_macro_attribute]
pub fn pymethods(_: TokenStream, input: TokenStream) -> TokenStream {
pub fn pymethods(attr: TokenStream, input: TokenStream) -> TokenStream {
let methods_type = if cfg!(feature = "multiple-pymethods") {
PyClassMethodsType::Inventory
} else {
PyClassMethodsType::Specialization
};
pymethods_impl(input, methods_type)
pymethods_impl(attr, input, methods_type)
}

/// A proc macro used to expose Rust functions to Python.
Expand Down Expand Up @@ -191,8 +191,17 @@ fn pyclass_enum_impl(
.into()
}

fn pymethods_impl(input: TokenStream, methods_type: PyClassMethodsType) -> TokenStream {
fn pymethods_impl(
attr: TokenStream,
input: TokenStream,
methods_type: PyClassMethodsType,
) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemImpl);
// Apply all options as a #[pyo3] attribute on the ItemImpl
// e.g. #[pymethods(crate = "crate")] impl Foo { }
// -> #[pyo3(crate = "crate")] impl Foo { }
let attr: TokenStream2 = attr.into();
ast.attrs.push(syn::parse_quote!( #[pyo3(#attr)] ));
let expanded = build_py_methods(&mut ast, methods_type).unwrap_or_compile_error();

quote!(
Expand Down
8 changes: 8 additions & 0 deletions src/test_hygiene/pymethods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -807,3 +807,11 @@ impl Dummy {
// PyGcProtocol
// Buffer protocol?
}

// Ensure that crate argument is also accepted inline

#[crate::pyclass(crate = "crate")]
struct Dummy2;

#[crate::pymethods(crate = "crate")]
impl Dummy2 {}

0 comments on commit 5667a09

Please sign in to comment.