Search code examples
pythonpython-typingpyright

How to convert between 2 type aliases in python?


I am trying to do the following in python:

import typing

TypeA = str

TypeB = typing.Union[typing.List[str], typing.List[int], int, str]

TypeC = typing.Dict[str, TypeB]

def funcA(arg1: TypeC):
    var1: typing.List[TypeA] = arg1["random_key"] # static typechecker i.e. pyright is not allowing this

How to make the typechecker i.e. pyright allow this assignment?


Solution

  • You can always use the typing.cast function to say "trust me, I know what I'm doing."

    var1: typing.List[TypeA] = cast(typing.List[TypeA], .....)
    

    And by the way, if you're using ≥3.9, you can just use list rather than typing.List.