python / python/cpython

Add `alias` as a `field()` parameter for dataclasses

Offen
#101,192 8 Kommentare 26 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@ericvsmith arbeitet bereits daran.

Seit 20.1.2023.

stdlib type-feature
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Feature or enhancement

Add an alias parameter to dataclasses.field() which behaves like alias in attrs.field() (see here and search for "alias"). It has the effect that it changes the corresponding argument name in the synthesized __init__.

Pitch

Since attrs 22.2.0, attrs.field has an alias parameter that does the following:

from attrs import define, field

@define
class C:
    _name: tuple[str, str] = field(alias="name")

    @property
    def full_name(self) -> str:
        return " ".join(self._name)

c = C(name=("John", "Smith"))  # `name` not `_name`
print(c.full_name)

The typical use-case for this is private instance variables as in the above example. But there could be other use-cases as well, like

@define
class C:
    viewport: tuple[int, int] = field(alias="vp")

C(vp=(2, 4))  # constructor uses shorthand

Besides being a useful feature in and of itself, another reason to add this to the standard library is that it would bring dataclasses in line with dataclass_transform which already supports the alias parameter in field(): https://peps.python.org/pep-0681/#field-specifier-parameters . It is currently a bit strange that dataclass_transform has a feature that dataclasses.dataclass doesn't actually have.

Previous discussion

https://discuss.python.org/t/add-alias-as-a-field-parameter-for-dataclasses/22988/1

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.