Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My expected code:

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading