繁体   English   中英

TypeScript 与 Python 输入默认 arguments 和自动完成

[英]TypeScript vs. Python typing default arguments and autocompletion

在 TypeScript 中,我曾经有以下内容,它将用作类型推断:

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

上面的示例应该在键入时为您提供选项和自动完成,并在您键入不在选项列表中的选项时出错。

当我探索 Python 时,我发现了typing模块。 但是我尝试的方法没有用,我找不到我希望找到的东西。

我的预期代码:

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

我的预期结果应该与 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")

一切都有效,除了最后一行让mypy合理地抱怨:

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

请注意,在 Python 中,解释器不关心类型注释,并将毫无问题地执行最后一个 function 调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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