我希望制作一个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
提供答案。是否有某种方法可以将TypeVar
与TypedDict
一起使用
如果我正确理解了您的问题,您可以使用
@overload
表示get_type
:相关问题 更多 >
编程相关推荐