Reputation: 338
I need a shorthand for a combination of types where one type is provided as an argument.
Example:
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"
Upvotes: 1
Views: 818
Reputation: 64058
Your code example basically works almost as-is. You just need to make T
a 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)
This particular technique is known as generic type aliases.
Upvotes: 1