PyNew

Derive Macro PyNew 

Source
#[derive(PyNew)]
{
    // Attributes available to this derive:
    #[pyderive]
}
Expand description

Derive macro generating a __new__() Python method.

It has all fields as the arguments as default, in the order of declaration.

If the filed is marked by #[pyderive(new=false)] attribute, the field is excluded from the arguments of the __new__() method. Notes, new=true has no effect.

  • It should place #[derive(PyNew)] before #[pyclass].

See the Customize Implementation section of the crate doc for detail.

ยงExample

use pyo3::{prelude::*, py_run};
use pyderive::*;

// Place before `#[pyclass]`
#[derive(PyNew)]
#[pyclass(get_all)]
struct PyClass {
    string: String,
    integer: i64,
    float: f64,
    tuple: (String, i64, f64),
    option: Option<String>,
    #[pyderive(new=false)]
    excluded: String,
}

let test = "
a = PyClass('s', 1, 1.0, ('s', 1, 1.0), None)
assert a.string == 's'
assert a.integer == 1
assert a.float == 1.0
assert a.tuple == ('s', 1, 1.0)
assert a.option is None
assert a.excluded == ''
";

Python::attach(|py| {
    let PyClass = py.get_type::<PyClass>();

    py_run!(py, PyClass, test)
});