cpython::py_class_method! [] [src]

macro_rules! py_class_method {
    ($f: ident) => { ... };
    ($f: ident ( $( $pname:ident : $ptype:ty ),* ) ) => { ... };
}

Creates a Python class method descriptor that invokes a Rust function.

There are two forms of this macro: 1) py_class_method!(f) f is the name of a rust function with the signature fn(Python, &PyType, &PyTuple, Option<&PyDict>) -> PyResult<R> for some R that implements ToPyObject.

2) py_class_method!(f(parameter_list)) This form automatically converts the arguments into the Rust types specified in the parameter list, and then calls f(Python, &PyType, Parameters). See py_argparse!() for details on argument parsing.

Returns a type that implements typebuilder::TypeMember by producing an class method descriptor.

Example

#![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use] extern crate cpython;
use cpython::{Python, PythonObject, PyResult, ObjectProtocol, PyType,
              PyRustTypeBuilder, NoArgs};

fn method(py: Python, cls: &PyType) -> PyResult<i32> {
    Ok(42)
}

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let my_type = PyRustTypeBuilder::<i32>::new(py, "MyType")
      .add("method", py_class_method!(method()))
      .finish().unwrap();
    let result = my_type.as_object().call_method(py, "method", NoArgs, None).unwrap();
    assert_eq!(42, result.extract::<i32>(py).unwrap());
}