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

How to create a typing combination where one of the types is provided as an argument?

我需要一个 shorthand 类型组合,其中一种类型作为参数提供。

示例:

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"

您的代码示例基本上可以按原样运行。您只需要将 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