Make succeeding non-default init-parameters keyword-only in dataclasses instead of raising

Currently in “dataclasses”, if non-defaulted fields are defined after defaulted-fields (usually subclasses adding required fields) that are initialised via argument (ie init=True), a TypeError is raised.

We can support the idiom of subclassing dataclasses with required fields by forcing all arguments after defaulted arguments to be keyword-only in the __init__ definition.

This is almost completely backwards-compatible: the only code that will break is any code relying on a TypeError to be raised when non-defaulted fields are defined upon data-class construction, which is very unlikely as class declaration tends to not be try-catched. However, the PEP states explicitly that a TypeError will be raised, so this will need to be changed and noted:

TypeError will be raised if a field without a default value follows a field with a default value. This is true either when this occurs in a single class, or as a result of class inheritance.

Related links:

1 Like

I just learnt that PEPs don’t need to be updated to reflect changes (makes sense, they’re a proposal, not a spec). My comment in the original post doesn’t stand,

Is there any news on this proposal?
I can’t wait to use it…

Some people were interested, but there was no discussion on the python-ideas mailing list. It seems like none of the Python devs were particularly interested in looking in to this.

If you want the functionality in your own project, add this code: Support non-defaulted after defaulted fields in dataclasses · GitHub