除非我弄错了,在Python中创建一个函数是这样的:

def my_func(param1, param2):
    # stuff

但是,实际上并没有给出这些参数的类型。而且,如果我没记错的话,Python是一种强类型语言,因此,Python似乎不应该让你传入与函数创建者期望的不同类型的参数。然而,Python如何知道函数的用户正在传递正确的类型呢?假设函数实际使用了形参,如果它是错误的类型,程序会死吗?必须指定类型吗?


当前回答

无论您是否指定类型提示,都将在运行时失败。

However, you can provide type hints for both function arguments and its return type. For example, def foo(bar: str) -> List[float] hints that bar is expected to be a string and the function returns a list of float values. This will result in a type check error when the method is invoked if the types don't match (before the use of the parameter in the function, or of the return type). This IMOHO is much more helpful in catching such errors vs an error about a missing field or method somewhere in the method call. I recommend reading the official Python documentation Typing - Support for type hints.

此外,如果使用类型提示,则可以使用静态类型检查器来验证代码的正确性。python中内置的一个这样的工具是myypy(官方文档)。关于静态类型检查的文章的这一部分很好地介绍了如何使用它。

其他回答

我在其他答案中没有看到这个,所以我把这个加到锅里。

正如其他人所说,Python不会对函数或方法参数强制执行类型。假设您知道自己在做什么,如果您确实需要知道传入的内容的类型,您将检查它并决定自己要做什么。

完成此任务的主要工具之一是isinstance()函数。

例如,如果我编写了一个希望获得原始二进制文本数据的方法,而不是普通的utf-8编码字符串,那么我可以在进入时检查参数的类型,并根据所找到的参数进行调整,或者引发一个异常来拒绝。

def process(data):
    if not isinstance(data, bytes) and not isinstance(data, bytearray):
        raise TypeError('Invalid type: data must be a byte string or bytearray, not %r' % type(data))
    # Do more stuff

Python还提供了各种深入对象的工具。如果您足够勇敢,甚至可以使用importlib动态地为任意类创建自己的对象。我这样做是为了从JSON数据重新创建对象。这样的事情在像c++这样的静态语言中是一场噩梦。

如果有人想指定变量类型,我已经实现了一个包装器。

import functools
    
def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for i in range(len(args)):
            v = args[i]
            v_name = list(func.__annotations__.keys())[i]
            v_type = list(func.__annotations__.values())[i]
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        v = result
        v_name = 'return'
        v_type = func.__annotations__['return']
        error_msg = 'Variable `' + str(v_name) + '` should be type ('
        error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
        if not isinstance(v, v_type):
                raise TypeError(error_msg)
        return result

    return check

使用它作为:

@type_check
def test(name : str) -> float:
    return 3.0

@type_check
def test2(name : str) -> str:
    return 3.0

>> test('asd')
>> 3.0

>> test(42)
>> TypeError: Variable `name` should be type (<class 'str'>) but instead is type (<class 'int'>)

>> test2('asd')
>> TypeError: Variable `return` should be type (<class 'str'>) but instead is type (<class 'float'>)

EDIT

如果没有声明任何参数的(或返回值的)类型,上面的代码就不能工作。下面的编辑可以提供帮助,另一方面,它只对kwarg有效,不检查args。

def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for name, value in kwargs.items():
            v = value
            v_name = name
            if name not in func.__annotations__:
                continue
                
            v_type = func.__annotations__[name]

            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ') '
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        if 'return' in func.__annotations__:
            v = result
            v_name = 'return'
            v_type = func.__annotations__['return']
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                    raise TypeError(error_msg)
        return result

    return check

在这个页面上,有一个臭名昭著的例外值得提及。

当str函数调用__str__类方法时,它会巧妙地检查其类型:

>>> class A(object):
...     def __str__(self):
...         return 'a','b'
...
>>> a = A()
>>> print a.__str__()
('a', 'b')
>>> print str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type tuple)

就好像Guido提示我们,如果程序遇到意外类型,应该引发哪个异常。

无论您是否指定类型提示,都将在运行时失败。

However, you can provide type hints for both function arguments and its return type. For example, def foo(bar: str) -> List[float] hints that bar is expected to be a string and the function returns a list of float values. This will result in a type check error when the method is invoked if the types don't match (before the use of the parameter in the function, or of the return type). This IMOHO is much more helpful in catching such errors vs an error about a missing field or method somewhere in the method call. I recommend reading the official Python documentation Typing - Support for type hints.

此外,如果使用类型提示,则可以使用静态类型检查器来验证代码的正确性。python中内置的一个这样的工具是myypy(官方文档)。关于静态类型检查的文章的这一部分很好地介绍了如何使用它。

Python并不关心你将什么传递给它的函数。当您调用my_func(a,b)时,param1和param2变量将保存a和b的值。Python不知道您正在使用正确的类型调用函数,并期望程序员处理这一点。如果函数将使用不同类型的参数调用,您可以使用try/except块包装访问它们的代码,并以您想要的任何方式计算参数。