Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Which fields to expose in dataclasses.fields()? #75

Closed
ericvsmith opened this issue Nov 22, 2017 · 3 comments
Closed

Which fields to expose in dataclasses.fields()? #75

ericvsmith opened this issue Nov 22, 2017 · 3 comments

Comments

@ericvsmith
Copy link
Owner

As pointed out in #17 (comment), there are now 3 kinds of fields: regular fields, InitVar fields, and ClassVar fields.

With the addition of InitVars (see #17), the internal __dataclass_fields__ class variable now needs to store the InitVar fields in order to correctly compute derived class __init__() params. I keep track of which type each field is with an undocumented Field._field_type member. I don't think I even keep track of the ClassVar fields, since I don't need them for anything.

The question comes up: which fields are returned by dataclasses.fields()? As I currently have it implemented, it returns just the regular fields, not the InitVar or ClassVar fields. If we decide it needs to return the latter two, I'll have to expose the _field_type by renaming it, and give it better values that can be more easily consumed.

I'm leaning toward only returning the regular fields. We can always expose the other field types in the future, maybe by a new param for fields() indicating which types to return, or by a new API like dataclasses.all_fields().

I see the main reason for fields() is for serializers and the like to see what data is in each instance, and for that they only need the regular fields. But maybe I'm not thinking big enough, and there's some use for InitVars in particular.

@ilevkivskyi
Copy link
Contributor

I think it should be only regular fields, since the main use case would be to actually access those fields on an instance. I think having to use hasattr() of try: ... except: ... defeats the purpose of fields().

@ericvsmith
Copy link
Owner Author

Well you could do if f.field_kind == 'regular': val=getattr(inst, f.name) [0], but yeah, it does seem like just regular fields are the ones of value.

[0] Or whatever a check for the kind of field would look like.

@ericvsmith
Copy link
Owner Author

I'm going to leave fields() as just returning regular fields. If needed, we can add another API in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants