使用 python 强制函数参数类型

Force fuction args type with python

我想强制函数 arg 为 str ,所以我在函数 args

中使用了 :str
def func (a:str):
    print(a)
func(int(2))

此代码有效且没有失败,为什么?

def func (a:str):
    print(a)
func(int(2))

您使用的是类型提示,如PEP 484所述。简而言之,它只是指导方针,不具有任何强制性作用。您可以使用 isinstance 函数来检查参数是否符合您的要求,并且 raise TypeError 否则遵循以下方式:

def func(a):
    if not isinstance(a, str):
        raise TypeError
    print(a)

您还可以(与运行时检查一起或代替它)使用静态类型检查器,它将尝试利用这些注释(以及它可以从联合国推断出的内容) -注释代码)并检查它们是否全部匹配。默认情况下 Python(有意且有意地)包括添加类型提示的语法,但不会执行任何类型检查:这不被视为 python 语言本身的一部分(尽管 python 使用类型 annotations,如数据类)。

主要的类型检查器是 mypy and developed under the umbrella of the Python project, but there are various alternatives (I've not necessarily tested so YMMV) e.g. Facebook's pyre, google's pytype or microsoft's pyright,以及集成工具,例如 jetbrains 等 IDE 的内置类型检查。