Unclear docs for dataclasses.field

Docs say (3.13.2):

hash: This can be a bool or None. If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged.

One possible reason to set hash=False but compare=True ...

Should clarify [edit, this is wrong: that False is equivalent to None, and say, “set hash=None but compare=True”], unless False and None somehow behave differently here.

False means do not include this field in the hash. None means use the value of compare to decide if this field is used in the hash, so they’re different. False should be called out explicitly, I think.

I think we can create an issue on GitHub and change the docs so that we also explicitly mention how False affects the hash generation (something like:

If true […], If false, this field is excluded in the generated __hash__ method. If None […]

1 Like

Thanks for the clarification, makes more sense now. Could read, then: “If true, … . If false, … . If None, …”

I’ve created Clarify the meaning `dataclasses.field(..., hash=False)` · Issue #130130 · python/cpython · GitHub to track the changes (the issue number is quite nice by the way)

2 Likes