PyStr

Derive Macro PyStr 

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

Derive macro generating a __str__() fn/Python method.

It returns the string that contains get and set fields as default, in the order of declaration.

If the filed is marked by #[pyderive(str=true)] attribute, the field is included in the string that __str__() returns; if #[pyderive(str=false)], it isn’t.

  • It should place #[derive(PyStr)] before #[pyclass].
  • It requires IntoPyObject trait for fields.
  • recursively calls str() like a dataclass.

§Example

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

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

Python::attach(|py| -> PyResult<()> {
    let a = Py::new(py, PyClass {
        string: "s".to_string(),
        integer: 1,
        float: 1.0,
        tuple: ("s".to_string(), 1, 1.0),
        option: None,
        excluded: "excluded".to_string(),
    })?;

    py_run!(py, a, r#"assert str(a) == "PyClass(string='s', integer=1, float=1.0, tuple=('s', 1, 1.0), option=None)""#);

    Ok(())
});