Typing kwargs when passed a TypedDict #9195
Replies: 1 comment 2 replies
-
Pyright's current behavior is correct, and it conforms to behavior mandated by the Python typing spec. The issue is that TypedDict classes are structural and are not "closed", which means that a dict value can be compatible with a TypedDict definition even if it has extra items that are not defined in that TypedDict. Static type checkers must therefore assume that extra items are present and their values are of type There is a draft PEP 728 that proposes to add the concept of "closed" TypedDicts to the type system. Pyright has provisional support for this PEP which can be enabled with the Here's how it would look if you were to use a closed TypedDict. Code sample in pyright playground from typing import TypeAlias, TypedDict
OptionalScalarType: TypeAlias = bool | float | int | str | None
class Person(TypedDict, closed=True):
name: str
age: int
def foo(**kwargs: OptionalScalarType) -> None:
print(kwargs)
person: Person = {"name": "John", "age": 30}
foo(**person) In the meantime, you have a few options:
|
Beta Was this translation helpful? Give feedback.
-
I'm aware that v1.1.380 brought some changes to TypedDict:
However I am having issues with pyright complaining about using it and I am unsure whether this is my understanding of the type system is lacking or if it is a bug.
The last line has the error
This doesn't complain on v1.1.379, but I don't understand why it does on v1.1.380+.
If this behaviour is intended, I'm in the situation where I am not in control of function
foo
so would like to know how I can do something likefoo(**person)
and not have the type checker complain.(problem in particular I'm facing is with the
.options
method on DataFramerReader/Writer in pyspark, I've pulled out some boilerplate into a dict and now pyright isn't happy about it)Beta Was this translation helpful? Give feedback.
All reactions