python - 获取与静态类型检查器一起使用的 TypedDict 值类型的函数

标签 python dictionary mypy python-typing

我正在寻找一个 Python (3.8+) 函数:

  • 输入:TypedDict的键值
  • 输出:
    • 返回值(简单)
    • 是否有适当的类型提示(我被卡住的地方)

这里有一个代码示例来帮助解释:

from typing import Any, Literal, TypedDict

class Foo(TypedDict):
    bar: int
    baz: str
    spam: Any

foo = Foo(bar=0, baz="hi", spam=1.0)

def get_type(key: Literal["bar", "baz"]):  # How to type hint the return here?
    """Function that get TypedDict's value when passed a key."""
    val = foo[key]
    # This works via intelligent indexing
    # SEE: https://mypy.readthedocs.io/en/stable/literal_types.html#intelligent-indexing
    reveal_type(val)  # mypy: Revealed type is 'Union[builtins.int, builtins.str]'
    return val

fetched_type = get_type("bar")
reveal_type(fetched_type)  # mypy: Revealed type is 'Any'
# I would like this to have output: 'int'

如果你不知道,我使用的静态类型检查器是 mypy

我在 get_type 上面的函数用 intelligent indexing 完成一半,但我不确定如何键入提示 get_type 的返回。

我应该为 get_type 的返回添加什么类型的提示?


研究

这两个问题

使用 TypeVar 提供答案。有什么方法可以将 TypeVarTypedDict 一起使用吗?

最佳答案

如果我对你的问题的理解正确,你可以使用 @overload 来获取 get_type:

from typing import Any, Literal, TypedDict, Union, overload

class Foo(TypedDict):
    bar: int
    baz: str
    spam: Any

foo = Foo(bar=0, baz="hi", spam=1.0)


@overload
def get_type(key: Literal["bar"]) -> int: ...

@overload
def get_type(key: Literal["baz"]) -> str: ...
    

def get_type(key: Literal["bar", "baz"]) -> Union[int, str]:
    """Function that get TypedDict's value when passed a key."""
    val = foo[key]
    reveal_type(val)  # mypy: Revealed type is 'Union[builtins.int, builtins.str]'
    return val

fetched_type = get_type("bar")
reveal_type(fetched_type)  # mypy: Revealed type is 'builtins.int'

关于python - 获取与静态类型检查器一起使用的 TypedDict 值类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65299047/

相关文章:

python - 把一行拆分成一个字典,里面有多层键值对

c++ - 使用 Qt 解析 JSON 数组

pycharm - mypy Reveal_type 的单元测试

python - TensorFlow:如果 tf.train.batch 已经并行出队示例,并行排队示例是否会加快批量创建速度?

python - 如何检查所有给定点(空间中)是否位于同一条线上?

python - 我通过 python BeautifulSoup 获得了结果集,但我不知道如何获取其中的 NavigableString

python - 是什么让用户定义的类不可散列?

java - 使用 AppEngine 访问本地 map 数据

python - mypy 对 Callable 的类型检查认为成员变量是一个方法

python - mypy Error TypeVar with Value Restriction and Union of Unions/Optional 无法传递通用容器类型