Skip to content
Advertisement

TypeScript vs. Python typing default arguments and autocompletion

In TypeScript I used to have the following and it will work as type inference:

function func(x: "#1" | "#2" | "#3" = "#2"): void {}

The above example should give you options and autocompletion when typing, and error when you type options that are not in the list of options.

When I was exploring Python I found the typing module. But what I tried didn’t work, and I couldn’t find what I’ve hopped to find.

My expected code:

def func(x: "#1" | "#2" | "#3" = "#2") -> None:
    pass

My expected result should be similar to the one in TypeScript.

Advertisement

Answer

from typing import Literal, TypeAlias


Valid: TypeAlias = Literal["#1", "#2", "#3"]


def func(x: Valid = "#2") -> None:
    print(x)


if __name__ == "__main__":
    func("#1")
    func("#2")
    func("#3")
    func("#4")

All valid, except the last line makes mypy rightfully complain:

error: Argument 1 to "func" has incompatible type "Literal['#4']"; expected "Literal['#1', '#2', '#3']"  [arg-type]

Note that in Python, the interpreter does not care about the type annotations and will execute that last function call without a problem.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement