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

标签 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"

最佳答案

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

关于python - 如何创建其中一种类型作为参数提供的类型组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841139/

相关文章:

python - 在 seaborn 中使用语言环境

python - 在python中迭代和匹配大文件

python - 最短超串搜索的更有效算法

python - 如何更改 Keras 中 softmax 输出的温度

python - 事务回滚

python - 找不到匹配的表格

python - 使用 OS 命令连接 CSV 文件

python - 如何在类型提示系统中使用通用(高级)类型变量?

python - Python 中的 Union from Typing 模块有什么作用?

返回子类实例的基类上的工厂方法的 Python 3 类型提示