How to define a generic type that works as an alias in Python

Viewed 54

Not sure if the title is 100% right, but it's simpler to explain using the following example:

class MyObject1:
    ...

class MyObject2:
    ...

@dataclass
class DataClass:
    source1: MyType[MyObject1]
    source2: MyType[MyObject2]

In this case, I'm looking for MyType to be something like:

MyType[T] = AliasTo(Union[T, str, None])

I feel like it could possibly be implemented using Generic but I can't make my head around how to do it.

(I'm using Python 3.8)

2 Answers

I don't know of an easy way to make the type definition itself parameterisable without making it a class unto itself.

But perhaps this is close enough to what you want:

from typing import TypeVar


class MyClass:
    pass


# instead of defining a parameterisable type, why not define the types you need?
MyType = TypeVar('MyType', MyClass, str, None)


def fun(x: MyType):
    if isinstance(x, MyClass):
        print('MyClass', x)
    elif isinstance(x, str):
        print('str', x)
    elif x is None:
        print('None')
    else:
        print('Something unexpected was passed')


fun(MyClass())
fun('test')
fun(None)
fun(1)

Output:

MyClass <__main__.MyClass object at 0x0000028D566CEA10>
str test
None
Something unexpected was passed

And in editors that check for it (for example in my case PyCharm), you get a warning like "Expected type 'MyType', got 'int' instead" on the last line fun(1), specifically on the 1.

Note: from the comments you've made it clear this is not ideal for you, but I'll leave the answer up for others looking and deciding it does work for them.

Define a TypeVar and a class that inherits from Union

In my example you see me inheriting from tuple actually,
but it is just to show that b really has inferred type str

from typing import *;

T = TypeVar("T");
class TupleAlias(tuple[T, str, None]): ...

def f(u: TupleAlias[int]):
    a, b, c = u;
    return b.capitalize();
pass

(in the picture, you should see completions for str type)

enter image description here

Related