Run-time behaviour of `TypeAliasType

I want to focus on a sub-problem that’s not related to Annotated nor pydantic: reusing type aliases for runtime type checks using isinstance. That the following works:

from typing import TypeAlias

SubUnion: TypeAlias = int | str
WholeUnion: TypeAlias = SubUnion | float

x: WholeUnion = 'x'
if isinstance(x, SubUnion):
    pass

but this doesn’t

type SubUnion = int | str
type WholeUnion = SubUnion | float

x: WholeUnion = 'x'
if isinstance(x, SubUnion):
    pass

is a usability problem.

As I mentioned in my earlier post, we have 100+ of these unions in our code base and they have a lot of members. It’s a very common pattern when programming with discriminated unions, which is very common in APIs and databases.

If we’d have to duplicate all union type aliases so we have e.g. both WholeUnion and WholeUnionAsTuple we’d be better of sticking with TypeAlias, which is a problem if it gets removed (at which point I don’t know what the Python solution to this problem is.)

1 Like