#pyo3 #derive #special #automatic #repr

pyo3_special_method_derive

Automatically derive Python dunder methods for your Rust code

15 releases

new 0.4.3 Apr 10, 2025
0.4.2 Jul 20, 2024
0.3.1 Jul 19, 2024
0.3.0 Jun 25, 2024
0.1.3 Jun 17, 2024

#995 in Rust patterns

Download history 223/week @ 2024-12-21 894/week @ 2024-12-28 1005/week @ 2025-01-04 1992/week @ 2025-01-11 462/week @ 2025-01-18 448/week @ 2025-01-25 1097/week @ 2025-02-01 96/week @ 2025-02-08 1041/week @ 2025-02-15 1085/week @ 2025-02-22 888/week @ 2025-03-01 5/week @ 2025-03-08 46/week @ 2025-03-15 4/week @ 2025-03-22 106/week @ 2025-04-05

156 downloads per month

MIT license

19KB
326 lines

Derive macros to make Rust objects more friendly 🤗.

Please see these docs for the PyDisplay and PyDebug traits which power Str and Repr.

This crate automatically derives the following functions for structs and enums:

  • __str__

  • __repr__

  • __dir__

  • __getattr__

  • __dict__

  • Skip exposure of variants or fields per derive macro with the #[skip(...)] attribute (eg. #[skip(Dir, Str)])

  • Struct fields which are not pub are skipped automatically

When you have custom Rust structs which need to implement PyDisplay and PyDebug, you should use the AutoDisplay and AutoDebug traits. This will have the same output as Str and Repr respectively.

This crate exports 2 traits (PyDisplay`` and PyDebug`) which should be implemented for every type for which its field or variant is not skipped.

It also exports a macro to use the Debug and Display traits to generate a PyDebug and PyDisplay implementation.

In addition, the AutoDisplay and AutoDebug macros enable usage of arbitrary Rust, non-pyclass structs.


pyo3-special-method-derive

This crate enables you to automatically derive Python dunder methods for your Rust crate using PyO3.

Key features

  • The following methods may be automatically derived on structs and enums:
    • __str__
    • __repr__
    • __dir__
    • __getattr__
    • __dict__
  • Support for structs and enums (only unit and complex enums due to a PyO3 limitation)
  • Support for skipping variants or fields per derive macro with the #[skip(...)] attribute
  • Automatically skip struct fields which are not pub

Example

#[pyclass]
#[derive(Dir, Str, Repr)]
struct Person {
    pub name: String,
    occupation: String,
    #[pyo3_smd(skip)]
    pub phone_num: String,
}

PyO3 feature note

To use pyo3-special-method-derive, you should enable the multiple-pymethods feature on PyO3:

pyo3 = { version = "0.22", features = ["multiple-pymethods"] }

Dependencies

~3.5MB
~81K SLoC