【问题标题】:Python type hinting, output type depends on input typePython 类型提示,输出类型取决于输入类型
【发布时间】:2021-10-07 00:50:20
【问题描述】:

考虑以下函数

import typing
def make_list(el : typing.Any):
    return [el, el]

如何提示它返回

typing.List[type(el)]

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:

    这就是TypeVar 的用途:

    from typing import TypeVar, List
    
    T = TypeVar('T')
    
    def make_list(el: T) -> List[T]:
        return [el, el]
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2023-04-04
      • 2016-07-18
      • 2020-10-14
      • 2019-02-25
      • 2018-02-23
      • 1970-01-01
      • 2022-01-11
      • 2015-08-04
      相关资源
      最近更新 更多