[Type Hint] Is there a way to reuse variables in types for Literal?

Example

from typing import Literal


name_list = ["Tom", "Jerry"]

name1: Literal["Tom", "Jerry"] = "Tom"   # ✅  But💧<name_list> not reuse 

:question:Is there a way to reuse variables in types for Literal ???

:point_down:eg:

name2: Literal[ *name_list ] = "Tom"   # ❌ "I initially thought of this method, but it is incorrect."

The opposite kind of works:

from typing import Literal, TypeAlias, get_args



Name: TypeAlias = Literal["Tom", "Jerry"]

name_list: list[Name] = list(get_args(Name))  # has to be annotated because type checker cannot infer type

name1: Name = "Tom"
2 Likes

Thank you very much!!! This is what I wanted. :+1:

1 Like