我正在寻找一个 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
的返回添加什么类型的提示?
研究
这两个问题
- Factory function for mypy `TypedDict`
- How to statically get TypeVar parameters from a Generic for use in static type checking?
使用 TypeVar
提供答案。有什么方法可以将 TypeVar
与 TypedDict
一起使用吗?
最佳答案
如果我对你的问题的理解正确,你可以使用 @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/