This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author eric.smith
Recipients eric.smith
Date 2021-03-17.17:39:21
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1616002761.92.0.652624260802.issue43532@roundup.psfhosted.org>
In-reply-to
Content
The idea is that a keyword-only field becomes a keyword-only argument to __init__().

For the proposal and a discussion, see https://mail.python.org/archives/list/python-ideas@python.org/message/FI6KS4O67XDEIDYOFWCXMDLDOSCNSEYG/

The @dataclass decorator will get a new parameter, kw_only, which defaults to False. If kw_only=True, all fields in the dataclass will be by efault keyword-only. In addition, field() will have a new kw_only parameter. If true, the field will be keyword-only. If false, it will not be keyword-only. If unspecified, it will use the value of dataclass's kw_only parameter.

In addition, a module-level variable KW_ONLY will be added. If a field has this type, then all fields after it will default to kw_only=True. The field is otherwise completely ignored.

Examples:

@dataclasses.dataclass
class A:
    a: Any = field(kw_only=True) 

Will have __init__(self, *, a)

@dataclasses.dataclass(kw_only=True)
class B:
    a: Any
    b: Any 

Will have __init__(self, *, a, b)

@dataclasses.dataclass
class C:
    a: Any
    _: dataclasses.KW_ONLY
    b: Any
    c: Any

Will have __init__(self, a, *, b, c)

If any non-keyword-only parameters are present, they will be moved before all keyword-only parameters, only for the generated __init__. All other generated methods (__repr__, __lt__, etc.) will keep fields in the declared order, which is the case in versions 3.9 and earlier.

@dataclasses.dataclass
class D:
    a: Any
    b: Any = field(kw_only=True)
    c: Any

Will have __init__(self, a, c, *, b)

PR to follow.
History
Date User Action Args
2021-03-17 17:39:21eric.smithsetrecipients: + eric.smith
2021-03-17 17:39:21eric.smithsetmessageid: <1616002761.92.0.652624260802.issue43532@roundup.psfhosted.org>
2021-03-17 17:39:21eric.smithlinkissue43532 messages
2021-03-17 17:39:21eric.smithcreate