我有以下字典代表一个人,该人可能是许多变体之一。这里只是一些:
person = {"name": "Johnny"}
person = {"name": "Johnny", "age": 25}
person = {"name": "Johnny", "age": 25, "active": True}
我正在提取某些键,并使用它们来打印语句。问题出现在类型提示中,当我在脚本上运行mypy时,出现错误提示Incompatible types in assignment (expression has type "object", variable has type "Optional[str]")
:
name: Optional[str] = person.get("name") # mypy error here
age: Optional[int] = person.get("age") # mypy error here
if name and age:
print(f"In 5 years, {name} will be {age + 5} years old")
要解决这个问题,mypy_extensions.TypedDict
类型似乎很有希望,但是看来我不能缺少或多余的钥匙:
from mypy_extensions import TypedDict
PersonDict = TypedDict("PersonDict", {"name": str, "age": int})
# ERROR: Key 'age' missing for TypedDict "PersonDict"
person: PersonDict = {"name": "Johnny"}
# ERROR: Extra key 'active' for TypedDict "PersonDict"
person: PersonDict = {"name": "Johnny", "age": 25, "active": True}
即使字典中的键是动态的,是否仍要为字典中的特定键定义类型?
答案 0 :(得分:1)
在您的TypedDict中添加total=False
将允许丢失键:
PersonDict = TypedDict("PersonDict", {"name": str, "age": int}, total=False)
https://mypy.readthedocs.io/en/latest/more_types.html#totality
似乎不允许在模式中没有其他键。