Skip to content

Commit

Permalink
Scope macro imports more tightly (#4088)
Browse files Browse the repository at this point in the history
  • Loading branch information
mejrs committed Apr 23, 2024
1 parent 5d2f5b5 commit f5fee94
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
11 changes: 6 additions & 5 deletions pyo3-macros-backend/src/module.rs
Expand Up @@ -382,10 +382,7 @@ fn module_initialization(options: PyModuleOptions, ident: &syn::Ident) -> TokenS
fn process_functions_in_module(options: &PyModuleOptions, func: &mut syn::ItemFn) -> Result<()> {
let ctx = &Ctx::new(&options.krate);
let Ctx { pyo3_path } = ctx;
let mut stmts: Vec<syn::Stmt> = vec![syn::parse_quote!(
#[allow(unknown_lints, unused_imports, redundant_imports)]
use #pyo3_path::{PyNativeType, types::PyModuleMethods};
)];
let mut stmts: Vec<syn::Stmt> = Vec::new();

for mut stmt in func.block.stmts.drain(..) {
if let syn::Stmt::Item(Item::Fn(func)) = &mut stmt {
Expand All @@ -395,7 +392,11 @@ fn process_functions_in_module(options: &PyModuleOptions, func: &mut syn::ItemFn
let name = &func.sig.ident;
let statements: Vec<syn::Stmt> = syn::parse_quote! {
#wrapped_function
#module_name.as_borrowed().add_function(#pyo3_path::wrap_pyfunction!(#name, #module_name.as_borrowed())?)?;
{
#[allow(unknown_lints, unused_imports, redundant_imports)]
use #pyo3_path::{PyNativeType, types::PyModuleMethods};
#module_name.as_borrowed().add_function(#pyo3_path::wrap_pyfunction!(#name, #module_name.as_borrowed())?)?;
}
};
stmts.extend(statements);
}
Expand Down
4 changes: 3 additions & 1 deletion pytests/src/enums.rs
@@ -1,5 +1,7 @@
use pyo3::{
pyclass, pyfunction, pymodule, types::PyModule, wrap_pyfunction_bound, Bound, PyResult,
pyclass, pyfunction, pymodule,
types::{PyModule, PyModuleMethods},
wrap_pyfunction_bound, Bound, PyResult,
};

#[pymodule]
Expand Down
5 changes: 4 additions & 1 deletion tests/test_no_imports.rs
Expand Up @@ -30,7 +30,10 @@ fn basic_module_bound(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyRes
42
}

m.add_function(pyo3::wrap_pyfunction_bound!(basic_function, m)?)?;
pyo3::types::PyModuleMethods::add_function(
m,
pyo3::wrap_pyfunction_bound!(basic_function, m)?,
)?;

Ok(())
}
Expand Down

0 comments on commit f5fee94

Please sign in to comment.