如何创建其中一种类型作为参数提供的类型组合?

时间:2019-09-08 10:34:52

标签: python python-3.x python-typing

我需要一种类型组合的简写,其中一种类型作为参数提供。

示例:

class CustomType:
  pass

# Shorthand
  OptionalCustomType = Union[Optional[T], CustomType]

# Usage
  def fun(x: OptionalCustomType[str]) -> str:
    # Type of x should be equivalent to Union[None, CustomType, str]
    if x is None:
      return "None"
    if x is CustomType:
      return "Custom Type"
    return "Some string"

1 个答案:

答案 0 :(得分:1)

您的代码示例基本上按原样工作。您只需要将T设置为typevar:

from typing import Optional, Union, TypeVar

class CustomType:
    pass

T = TypeVar('T')
OptionalCustomType = Union[Optional[T], CustomType]

# This type-checks without an issue
def fun(x: OptionalCustomType[str]) -> str:
    # Type of x should be equivalent to Union[None, CustomType, str]
    if x is None:
        return "None"
    if x is CustomType:
        return "Custom Type"
    return "Some string"

y: OptionalCustomType[int]

# In mypy, you'll get the following output:
# Revealed type is 'Union[builtins.int, None, test.CustomType]'
reveal_type(y)

这项特殊技术被称为generic type aliases