ingolemo / python-lenses

A python lens library for manipulating deeply nested immutable structures
GNU General Public License v3.0
313 stars 19 forks source link

Using setters with frozen dataclasses #25

Closed rolandcrosby closed 4 years ago

rolandcrosby commented 4 years ago

One of the projects I work on makes extensive use of frozen dataclasses, and generally uses the dataclasses.replace function to construct new instances of dataclasses with specific fields updated. This seems like it would be a natural fit for the setters available in lenses, or an extension thereof. Is this something that has been done before, or do you have any advice about how to accomplish this?

ingolemo commented 4 years ago

You can define hooks that allow the library to work with your own custom classes (relevant docs). You want to add a method that looks something like this to all your frozen classes:

def _lens_setattr(self, name, value):
    return dataclasses.replace(self, **{name: value})

There's no convenient way to hook the existing library to get it to work with all dataclasses automatically. But supporting dataclasses by default is probably a good idea, so I'll look into doing that.

rolandcrosby commented 4 years ago

Awesome, thank you for the advice!

ingolemo commented 4 years ago

I've just pushed a commit (c94f57e) that should make the library support dataclasses natively (no hooks required). My simple test cases seem to work but if you (or anyone) are able to try it on a more heavy duty codebase I'd appreciate any feedback.