简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM