biqqles/dataclassy

Add `internals` parameter to `as_dict`/`as_tuple`

Opened this issue · 4 comments

Simple example

from dataclassy import dataclass, as_dict

@dataclass
class MyClass:
    _my_internal_tracking_field: str = "Parent Class"
   my_other_field: str

>>> my_instance = MyClass(my_other_field="test")
>>> my_instance.__repr__
<bound method __repr__ of MyClass(my_other_field='test')>
>>> as_dict(my_instance)
{'_my_internal_tracking_field': 'Parent Class', 'my_other_field': 'test'}

From the README, hide_internals is True by default but seems to only apply to:

__repr__ and excludes them from comparison and iteration

Is there any case where we would want to definitely want to expose internal fields in the dictionary representation?

I see internals=True by default here in functions.py, maybe it should pass the hide_internals option instead of setting True automatically.
https://github.com/biqqles/dataclassy/blob/master/dataclassy/functions.py#L65-L69

I don't mind making this change but just want to see if I am missing any use cases.

values also returns a dict (but not recursively) and accepts an internals parameter, which defaults to False. In your simple example, I think it's what you want.

as_dict is more for serialising an entire nested data structure to a "simpler" format that can be e.g. dumped to JSON. That doesn't mean it shouldn't have an internals argument though. That could be added (and for as_tuple as well).

I would rather have an extra argument than these functions to introspect the class because it gives the user more control (you could easily want some fields to not show up in the repr, but still be important to serialise).

Right - to use values I think I would have to build a custom recursing function to reproduce as_dict though, as the dataclasses I am working with are large nested dataclass "types".

It is the exact functionality you mention that I am primarily using them for in my project:

serialising an entire nested data structure to a "simpler" format that can be e.g. dumped to JSON

but using an internal variable to keep track of various subclasses of component dataclasses. I can share an example if this doesn't make sense of course.

So potentially the additional functionality would be to add an internals arg to as_dict to accomplish this?

Sorry, I misunderstood because of the simplicity of your example.

So potentially the additional functionality would be to add an internals arg to as_dict to accomplish this?

Yes, I would do exactly this.

No worries - I could have shared all of my current huge dataclasses but it's a lot to type out, was easier at first to share a simple example.

Thanks for the feedback! I'll see if I can fit time to make this change and submit a PR soon.