Skip to content

Commit

Permalink
WIP: PyFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
sebpuetz committed Sep 6, 2020
1 parent 64b06ea commit fd37b21
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
5 changes: 2 additions & 3 deletions pyo3-derive-backend/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ pub fn add_fn_to_module(
Ok(quote! {
fn #function_wrapper_ident<'a>(
args: impl Into<pyo3::derive_utils::WrapPyFunctionArguments<'a>>
) -> pyo3::PyResult<pyo3::PyObject> {
) -> pyo3::PyResult<&'a pyo3::types::PyFunction> {
let arg = args.into();
let (py, maybe_module) = arg.into_py_and_maybe_module();
#wrapper
Expand All @@ -231,8 +231,7 @@ pub fn add_fn_to_module(
};

let function = unsafe {
pyo3::PyObject::from_owned_ptr(
py,
py.from_owned_ptr::<pyo3::types::PyFunction>(
pyo3::ffi::PyCFunction_NewEx(
Box::into_raw(Box::new(_def.as_method_def())),
mod_ptr,
Expand Down
8 changes: 8 additions & 0 deletions src/types/function.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use crate::ffi;
use crate::prelude::*;

/// Represents a builtin Python function object.
#[repr(transparent)]
pub struct PyFunction(PyAny);

pyobject_native_var_type!(PyFunction, ffi::PyCFunction_Type, ffi::PyCFunction_Check);
2 changes: 2 additions & 0 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub use self::datetime::{
};
pub use self::dict::{IntoPyDict, PyDict};
pub use self::floatob::PyFloat;
pub use self::function::PyFunction;
pub use self::iterator::PyIterator;
pub use self::list::PyList;
pub use self::module::PyModule;
Expand Down Expand Up @@ -225,6 +226,7 @@ mod complex;
mod datetime;
mod dict;
mod floatob;
mod function;
mod iterator;
mod list;
mod module;
Expand Down
9 changes: 4 additions & 5 deletions src/types/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use crate::ffi;
use crate::instance::PyNativeType;
use crate::pyclass::PyClass;
use crate::type_object::PyTypeObject;
use crate::types::PyTuple;
use crate::types::{PyAny, PyDict, PyList};
use crate::types::{PyFunction, PyTuple};
use crate::{AsPyPointer, IntoPy, Py, PyObject, Python};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
Expand Down Expand Up @@ -275,12 +275,11 @@ impl PyModule {
/// ```
pub fn add_function<'a>(
&'a self,
wrapper: &impl Fn(&'a Self) -> PyResult<PyObject>,
wrapper: &impl Fn(&'a Self) -> PyResult<&'a PyFunction>,
) -> PyResult<()> {
let py = self.py();
let function = wrapper(self)?;
let name = function.getattr(py, "__name__")?;
let name = name.extract(py)?;
let name = function.getattr("__name__")?;
let name = name.extract()?;
self.add(name, function)
}
}

0 comments on commit fd37b21

Please sign in to comment.