Skip to content

Allow subclasses of a dataclass to define required fields when a parent has defined optional fields #133162

Closed as not planned
@felipe-m-morais

Description

@felipe-m-morais

Feature or enhancement

Proposal:

Although this is something that can be worked around by defining the optional fields as kw_only, that has the onus of forcing the instantiation of the parent classes to be more verbose. Instead, I propose to simply adjust the order of the fields: just like they are already reordered to move kw_only fields to the back, we need only move fields that define a default/default_factory to the front. The fix is so simple it could be done in the same function with minor changes:

# Current:
def _fields_in_init_order(fields):
    # Returns the fields as __init__ will output them.  It returns 2 tuples:
    # the first for normal args, and the second for keyword args.

    return (tuple(f for f in fields if f.init and not f.kw_only),
            tuple(f for f in fields if f.init and f.kw_only)
            )

# Proposed:
def _fields_in_init_order(fields):
    # Returns the fields as __init__ will output them.  It returns 2 tuples:
    # the first for normal args, and the second for keyword args.
    
    required_fields = []
    optional_fields = []
    kw_fields = []
    for f in fields:
        if not f.init:
            continue
        if f.kw_only:
            kw_fields.append(f)
        elif f.default is MISSING and f.default_factory is MISSING:
            required_fields.append(f)
        else:
            optional_fields.append(f)

    return tuple(required_fields + optional_fields), tuple(kw_fields)

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions