Python3.7 中的函数输入参数是否可以有静态类型声明?

Is it possible to have static type declarations for function input arguments in Python3.7?

这是我在 leetcode.com 的 Python3 代码框架中看到的语法。注意函数输入参数的类型声明(或者至少我认为它们是类型声明,以前从未见过)。 nums 必须是 intList,并且 s 必须是 int

class Solution:
    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        pass

如果我 运行 在 leetcode.com 的环境中运行该功能,它会无错退出。但是,如果我 运行 在我自己的 Python 3.7.3 环境中使用相同的代码,我会得到一个 NameError。

def findTargetSumWays(self, nums: List[int], S: int) -> int: NameError: name 'List' is not defined

怎么了? leetcode.com 上的语法是真实的 Python 吗?

是的,这是真正的语法,我相信是从 3.7 开始正式使用的。

此静态类型中使用的 List 是从 typing 模块导入的。

您可以在 PEP-484: Type Hints or in the typing module docs 中阅读更多相关信息。