python - mypy:定义动态字典中特定键的类型

标签 python python-3.x mypy

我有以下字典,代表一个可能是多种变体之一的人。这里只是一些:

person = {"name": "Johnny"}
person = {"name": "Johnny", "age": 25}
person = {"name": "Johnny", "age": 25, "active": True}

我正在提取某些键并使用它们来打印语句。问题出现在类型提示中,我收到一条错误消息 Incompatible types in assignment (expression has type "object", variable has type "Optional[str]")当我在脚本上运行 mypy 时:

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 type 看起来很有希望,但看来我不能缺少或多余的键:

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}

是否有办法为字典中的特定键定义类型,即使该字典中的键是动态的?

最佳答案

total=False 添加到 TypedDict 将允许缺少键:

PersonDict = TypedDict("PersonDict", {"name": str, "age": int}, total=False)

https://mypy.readthedocs.io/en/latest/more_types.html#totality

允许不在架构中的附加键似乎是不可能的。

关于python - mypy:定义动态字典中特定键的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677431/

相关文章:

python-3.x - Mypy 迭代器和生成器有什么区别?

python - 在 Geopandas map 上绘制六角网格

python人脸识别慢

python - MyPy - 处理可能的 None 返回类型

python - 如何仅键入协议(protocol)方法的第一个位置参数并让其他参数不键入?

python - 如何将 subprocess.run 的输出保存到字符串中?

python - Numba 的 prange 给出了错误的结果

python - 为什么我得到 "' ResultSet' has no attribute 'findAll'“在 Python 中使用 BeautifulSoup?

python - 我们不能将一个以 0(零)开头的值赋给变量吗?示例 : a=0123. 这会引发错误 "invalid token"

Python-从字典列表创建动态嵌套字典