Skip to content

Add attrs support #92

@sscherfke

Description

@sscherfke

It would be very nice to have attrs support, alongside support for dataclasses.

Attrs works quite similarly to dataclasses (dataclasses drew a lot of inspiration from attrs).

The major difference for serialization with orjson is, that the list of fields can be found in the __attrs_attrs__ attribute. As POC, I wrote a small patch:

--- a/src/typeref.rs
+++ b/src/typeref.rs
@@ -84,7 +84,7 @@
         DST_STR = PyUnicode_InternFromString("dst\0".as_ptr() as *const c_char);
         DICT_STR = PyUnicode_InternFromString("__dict__\0".as_ptr() as *const c_char);
         DATACLASS_FIELDS_STR =
-            PyUnicode_InternFromString("__dataclass_fields__\0".as_ptr() as *const c_char);
+            PyUnicode_InternFromString("__attrs_attrs__\0".as_ptr() as *const c_char);
         ARRAY_STRUCT_STR =
             pyo3::ffi::PyUnicode_InternFromString("__array_struct__\0".as_ptr() as *const c_char);
         VALUE_STR = pyo3::ffi::PyUnicode_InternFromString("value\0".as_ptr() as *const c_char);

I compiled orjson and tested it:

>>> from attr import dataclass
>>> import orjson
>>>
>>> @dataclass
... class Data:
...     x: int
...     y: int
...
>>> orjson.dumps(Data(1, 2))
b'{"x":1,"y":2}'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions