Allow use of `Required` and `NotRequired` to make an existing typed dict total or optional
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 1.8k
- Forks
- 302
- Ø Merge
- 23 Std.
- Gemergte PRs (30 T.)
- 8
Beschreibung
I think the ability of indicating that a typed dict requires all keys or that all are optional would be very useful.
For example to allow defining default values for a particular dict or to return a dict that has been completely assigned from a function
A simple example
class A(TypedDict):
a: int
b: int
ADefault = {'a': 1, 'b': 42}
def optionalA(v: NotRequired[A]) -> A:
return ADefault | v
optionalA({'a': 11}) # ok since all keys of NotRequired[A] are optional
class X(TypedDict, total=False):
x: str
y: str
XDefault: X = {"x": "xv", "y": "yv"}
def withXDefault(v: X) -> Required[X]:
return XDefault | v
withXDefault({"x": "foo"})["y"] # ok since all keys of Required[X] are required
This idea is inspired by the analogous types in typescript Required and Partial that are in general very convenient.
I think it makes sense having the same behaviour of the typescript counterparts:
NotRequired[X]is a no op, since X is defined astotal=False. Same forRequired[A].Required/NotRequiredwould include all keys of the typed dict and all its superclasses. This differs from howtotalworks. Example:class TD1(TypedDict): a: int class TD2(TypedDict, total=False): b: int TDR = Required[TD2] # b becomes required TDNR = NotRequired[TD2] # a becomes not requiredRequired/NotRequiredused inline in the TypedDict are not taken into consideration, so the end result is the same independently of how the typed dict is defined
Beitragsleitfaden
Für dieses Repository ist kein Beitragsleitfaden indexiert
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der Überprüfung der vorgeschlagenen Semantik von TypedDict, Required und NotRequired sowie der Beispiele im Issue, einschließlich Vererbung und Inline-Annotationen. Definiere das Verhalten und identifiziere die relevante typing specification und die Konformitätstests; abgeschlossen bedeutet, dass die angeforderten Transformationen konsistent spezifiziert und validiert sind.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- developer-experience
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100