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:
- Python bug: bpo-36077 (includes my PR for the change implementation)
- Stack Overflow question: Class inheritance in Python 3.7 dataclasses