我需要一种类型组合的简写,其中一种类型作为参数提供。
例:
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/