Betrachten Sie den folgenden Codeabschnitt:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
Der obige Kodex ist nur eine Möglichkeit zu demonstrieren, was ich zu erreichen versuche. Ich würde gerne machen namedtuple
mit Typhinweisen.
Kennen Sie einen eleganten Weg, um das gewünschte Ergebnis zu erzielen?
Die bevorzugte Syntax für ein typisiertes benanntes Tupel seit 3.6 ist
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
Bearbeiten
Erwägen Sie ab Python 3.7 die Verwendung von dataclasses
(Ihre IDE unterstützt sie möglicherweise noch nicht für die statische Typprüfung):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
Sie können verwenden typing.NamedTuple
Aus den Dokumenten
Typisierte Version von namedtuple
.
>>> import typing
>>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])
Dies ist nur in Python 3.5 und höher vorhanden
Nur um fair zu sein, NamedTuple
aus typing
:
>>> from typing import NamedTuple
>>> class Point(NamedTuple):
... x: int
... y: int = 1 # Set default value
...
>>> Point(3)
Point(x=3, y=1)
gleich klassisch namedtuple
:
>>> from collections import namedtuple
>>> p = namedtuple('Point', 'x,y', defaults=(1, ))
>>> p.__annotations__ = {'x': int, 'y': int}
>>> p(3)
Point(x=3, y=1)
So, NamedTuple
ist nur Syntaxzucker für namedtuple
Unten finden Sie eine Erstellung NamedTuple
Funktion aus dem Quellcode von python 3.10
. Wie wir sehen können, verwendet es collections.namedtuple
Konstruktor und fügt hinzu __annotations__
aus extrahierten Typen:
def _make_nmtuple(name, types, module, defaults = ()):
fields = [n for n, t in types]
types = {n: _type_check(t, f"field {n} annotation must be a type")
for n, t in types}
nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
return nm_tpl
Außerdem haben Sie ab py3.7 die Dataclass-Option: docs.python.org/3/library/dataclasses.html
– JohannesE
23. Juli 2018 um 9:37 Uhr