代码之家  ›  专栏  ›  技术社区  ›  Intrastellar Explorer

用于获取与静态类型检查器一起使用的TypedAct值类型的函数

  •  0
  • Intrastellar Explorer  · 技术社区  · 5 年前

    • 输入:a键 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 获取类型 .

    获取类型


    研究

    这两个问题

    使用 TypeVar . 有什么方法可以使用它吗 类型变量 具有 打字机 ?

    0 回复  |  直到 5 年前
        1
  •  1
  •   alex_noname    5 年前

    如果我正确理解你的问题,你可以使用 @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'
    
    
    推荐文章