Issue 35710: Make dataclasses.field() accept another name for __init__ field's name

Issue35710

Created on 2019-01-10 17:11 by remi.lapeyre, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg333409 - (view) Author: Rémi Lapeyre (remi.lapeyre) * Date: 2019-01-10 17:11
When creating a class, I sometimes wish to get this behavior:


    def MyClass:
        def __init__(self, param):
            self._param = param

        def __repr__(self):
            return f"MyClass(param={self._param})"


Unless I'm making a mistaking, this behavior is not currently possible with dataclasses.

I propose to change:

    field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)

to: 

    field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None, target=None)

with target being used as the init parameter name for this field and in the repr.

If this is accepted, I can post the patch to make this change.
msg333586 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2019-01-14 06:25
"target" seems too general for the OP's use case.  "private=False" would be more focused.  General renaming occasionally has uses but is mostly an anti-pattern.  

Some thought also needs to be given to downstream effects of renaming (what shows up in help(), impact of renaming on type annotations, introspection challenges, what asdict() should do, whether the overall implementation would be made more complex, is the attribute now out of reach for __post_init__(), is this even within the scope of what dataclasses set out to do, etc).
History
Date User Action Args
2022-04-11 14:59:10adminsetgithub: 79891
2019-01-17 13:37:57theophilesetnosy: + theophile
2019-01-14 06:25:48rhettingersetnosy: + rhettinger
messages: + msg333586
2019-01-10 20:42:54eric.smithsetassignee: eric.smith

type: enhancement
nosy: + eric.smith

2019-01-10 17:11:11remi.lapeyrecreate