Create the type LiteralType as Literal's equivalent of Union's UnionType

If you want to write a function that takes in a Union, you can do this:

from types import UnionType

def use_union(union: UnionType):
    ...

use_union(Union[int, str])

But there isn’t a way to do this with Literal. I propose that we create the type LiteralType that can be used like this:

from types import LiteralType

def use_literal(literal: LiteralType):
    ...

use_literal(Literal[1])
1 Like

Related: PEP 747: TypeExpr: Type Hint for a Type Expression.

3 Likes

I guess TypeExprs are what I actually wanted, thanks!

1 Like

As a workaround for now though, why doesn’t this work:

LiteralType Workaround

When this is how UnionType is defined in types.py:

UnionType definition

?

Because these types involve special casing. That UnionType works at all is already borderline case and I am unsure works consistently across type checkers. I would be kind of surprised if it did work if you tried pytype, pyre, pyright, and mypy each.

At moment the type hint for something like Union/Literal is under specified and that’s what type form pep is working clarifying.

1 Like

For static type checkers, it doesn’t matter what is in types.py; they only look at the stubs in typeshed. The type.__or__ method is annotated as returning UnionType, so type checkers support that type, but Literal is a special form and too heavily special-cased for type checkers to know anything about the actual runtime type.

2 Likes