Helgi
Helgi

Reputation: 338

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

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

Answers (1)

Michael0x2a
Michael0x2a

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

Related Questions