简体   繁体   中英

Parametrized Union for python type annotations

I'd like to define a generic type like the following

MyType(OtherType) := Union[SomeClass, OtherType]

So that instead of typing the following to annotate x:

x: Union[SomeClass, int]

I'd only have to write

x: MyType[int]   # or MyType(int) for what it's worth

Do I have to subclass Type ? If so, how does one go about doing that?

If I understood correctly all you need is a TypeVar instance like

from typing import TypeVar, Union


class SomeClass:
    ...


OtherType = TypeVar('OtherType')
MyType = Union[SomeClass, OtherType]


def foo(x: MyType[int]) -> int:
    return x ** 2

with code like this placed in test.py module

$ mypy test.py

gives me

test.py:13: error: Unsupported operand types for ** ("SomeClass" and "int")
test.py:13: note: Left operand is of type "Union[SomeClass, int]"

and with fix in foo

def foo(x: MyType[int]) -> int:
    if isinstance(x, SomeClass):
        return 0
    return x ** 2

has no issues.

Notes

If we really need this type of alias I've called it something like

SomeClassOr = Union[SomeClass, OtherType]

since

SomeClassOr[int]

seems more readable to me than

MyClass[int]

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM