python参数检查类型

1.什么是类型检查? (1. What is Type Checking?)

Type Checking is the programming language feature that specifies how the variables are created and their types are identified by the language compiler or interpreter.

类型检查是一种编程语言功能,它指定语言编译器或解释器如何创建变量以及如何标识变量的类型。

2.类型检查有哪些不同类型? (2. What are the different types of Type Checking?)

A programming language can be classified into the following based on type checking.

可以根据类型检查将编程语言分为以下几种。

  1. Statically Typed Languages – C, Java, C++, etc.

    静态类型语言 -C,Java,C ++等
  2. Dynamically Typed Languages – JavaScript, Python, Ruby, etc.

    动态类型语言 – JavaScript,Python,Ruby等

2.1)什么是静态类型检查? (2.1) What is Static Type Checking?)

The type of a variable is known at the compile-time. The type of a variable is fixed and we can’t change it at a later point of time.

变量的类型在编译时是已知的。 变量的类型是固定的,我们以后不能更改它。

Let’s look at the variable declaration in Java.

让我们看一下Java中的变量声明。

String str = "Hello";

If we try to change the type of the variable or assign a value of incompatible type, the compiler will throw an error.

如果我们尝试更改变量的类型或分配不兼容类型的值,则编译器将引发错误。

str = 10; // Type mismatch: cannot convert from int to String 

int str = 10; // Duplicate local variable str

2.2)什么是动态类型检查? (2.2) What is Dynamic Type Checking?)

The type of the variable is determined at the runtime. We don’t specify the type of the variable in the code. The code behaves differently based on the type of the object at runtime.

变量的类型在运行时确定。 我们没有在代码中指定变量的类型。 代码在运行时根据对象类型的不同而有所不同。

Let’s look at an example of a function definition in Python.

让我们看一下Python中的函数定义示例。

def add(x, y):
    return x + y


print(add(10, 5))
print(add('A', 'B'))

If the function arguments are integers, the sum is returned. If they are string, they are concatenated and returned.

如果函数参数为整数,则返回总和。 如果它们是字符串,则将它们串联并返回。

If we pass any other custom object, we might get a different response or an error is raised if the ‘+’ operator is not supported by them.

如果传递任何其他自定义对象,则可能会得到不同的响应,或者如果它们不支持'+'运算符,则会引发错误。

2.3)静态类型化语言与动态类型化语言 (2.3) Statically Typed Languages vs Dynamically Typed Languages)

  1. The benefit of statically typed language is that many errors related to incompatible types are caught at the compile-time. The same is not true with the dynamically typed languages. It might take a long time before you get the error related to the incompatible type.

    静态类型语言的好处是在编译时会捕获许多与不兼容类型有关的错误。 对于动态类型的语言,情况并非如此。 您可能需要很长时间才能收到与不兼容类型相关的错误。
  2. The benefit of dynamically typed language is the shorter development time. But, this benefit fades away when the project code size grows. It’s really hard to debug a program throwing error because of the wrong type as it will occur only once in a while based on the user input or the data received from another source.

    动态类型语言的好处是开发时间更短。 但是,随着项目代码大小的增加,这种好处就会消失。 由于类型错误,调试程序引发的错误真的很困难,因为基于用户输入或从其他来源接收到的数据,它只会偶尔出现一次。

3.用Python打字 (3. Duck Typing in Python)

Duck typing is a concept of dynamically typed programming languages. The type of object is less important than the functions it defines.

鸭子打字是动态打字的编程语言的概念。 对象的类型不如其定义的功能重要。

Let’s look at this with an example of a custom object and the add() function we have defined.

让我们用一个自定义对象和我们定义的add()函数的示例来看看。

def add(x, y):
    return x + y

class Data:

    def __init__(self, i):
        self.id = i

d1 = Data(10)
d2 = Data(5)

print(add(d1, d2))

This code will produce the following runtime error:

此代码将产生以下运行时错误:

Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/type_checking.py", line 12, in <module>
    print(add(d1, d2))
  File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/type_checking.py", line 2, in add
    return x + y
TypeError: unsupported operand type(s) for +: 'Data' and 'Data'

If we want our object to support the addition operator, all we have to do is define __add__() function for it.

如果我们希望我们的对象支持加法运算符,我们要做的就是为其定义__add __()函数。

def __add__(self, other):
    return self.id + other.id

Now, the print statement will print 15 and there will be no error produced by the code.

现在,print语句将打印15,并且代码不会产生任何错误。

So, in essence, the type of the object doesn’t matter at all. As long as the required functions are defined to support an operation, there won’t be any issues because of the object type.

因此,从本质上讲,对象的类型根本不重要。 只要定义了所需的功能以支持操作,就不会因为对象类型而出现任何问题。

4.在Python中键入提示 (4. Type Hints in Python)

Python 3.5 added type hints support using the typing module. As the name suggests, it’s a way for the developers to hint the expected type of the function arguments and return types.

Python 3.5使用类型模块添加了类型提示支持。 顾名思义,这是开发人员暗示函数参数和返回类型的预期类型的​​一种方式。

Let’s say we have a function to perform some operations on two numbers.

假设我们有一个函数可以对两个数字执行一些运算。

def calculate(x, y, op='sum'):
    if op == 'divide':
        return x // y
    if op == 'difference':
        return x - y
    if op == 'multiply':
        return x * y
    # default is sum
    return x + y

Even though it’s intended for numbers only, it will work for string arguments too.

即使仅用于数字,它也适用于字符串参数。

print(calculate(10, 3, 'divide'))  # 3
print(calculate(10, 5))  # 15
print(calculate('A', 'B'))  # AB

Let’s see how to add type hints for the given function.

让我们看看如何为给定函数添加类型提示。

def calculate1(x: int, y: int, op: str = 'sum') -> int:
    # same code as above

The function argument type hints are provided with a colon (:) and the return type using -> sign.

函数参数类型提示带有冒号(:),返回类型使用->符号。

But, this doesn’t enforce the function argument and return types. The code will still work for other types of arguments.

但是,这不会强制执行函数参数和返回类型。 该代码仍可用于其他类型的参数。

But, third party tools such as type checkers, IDEs, linters, etc. can parse this to warn us for the possibility of the wrong types of arguments. For example, if we pass string arguments to this function, the PyCharm IDE will produce a warning message as “Expected type ‘int’, got ‘str’ instead“.

但是,第三方工具(例如类型检查器,IDE,lint等)可以对此进行解析,以警告我们参数类型错误的可能性。 例如,如果我们将字符串参数传递给此函数,则PyCharm IDE会生成警告消息“ 期望类型为'int',而取值为'str'而不是 ”。

4.1)类型提示的优点 (4.1) Advantages of Type Hints)

  • The type hints also documents the code for the function expected argument types and the return type.

    类型提示还记录了函数预期参数类型和返回类型的代码。
  • It helps API users in making sure that the correct type of arguments are being passed to a function.

    它可以帮助API用户确保将正确类型的参数传递给函数。
  • Helps improving IDE, type checkers, and Linters in warning users when an incompatible type of argument is being passed to a function.

    当将不兼容类型的参数传递给函数时,有助于改进IDE,类型检查器和Linter,以警告用户。

4.2)类型提示的缺点 (4.2) Disadvantages of Type Hints)

  • There is no runtime benefit for type hints. It doesn’t enforce the types or raises any warning or errors if a different type of argument is passed.

    类型提示没有运行时的好处。 如果传递了不同类型的参数,它不会强制类型,也不会引发任何警告或错误。
  • The type hints are more like documentation. If the function is changed and the developer misses to change the type hints accordingly, it will give a wrong message to the developer using the function. Maintaining type hints are time-consuming and requires developers’ effort.

    类型提示更像文档。 如果功能被更改,并且开发人员错过了相应地更改类型提示的操作,则会向使用该功能的开发人员显示错误消息。 维护类型提示非常耗时,需要开发人员的努力。
  • It slows down the program speed a little bit.

    它会稍微降低程序速度。
  • The type hints were introduced in Python 3.5, so it’s fairly new and won’t work with older Python versions.

    类型提示是在Python 3.5中引入的,因此它是一个相当新的特性,不适用于旧版本的Python。

4.3)__annotations__属性 (4.3) __annotations__ attribute)

Python functions have __annotations__ attribute, which contains the information about the type hints.

Python函数具有__annotations__属性,其中包含有关类型提示的信息。

def calculate(x, y, op='sum'):
    pass

def calculate1(x: int, y: int, op: str = 'sum') -> int:
    pass

print(calculate.__annotations__)  # {}

print(calculate1.__annotations__) 
# {'x': <class 'int'>, 'y': <class 'int'>, 'op': <class 'str'>, 'return': <class 'int'>}

5. Python运行时类型检查 (5. Python Runtime Type Checking)

We can use type() function to get the type of a variable at runtime.

我们可以使用type()函数在运行时获取变量的类型。

>>> x = 10
>>> type(x)
<class 'int'>
>>> 
>>> s1 = 'Hello'
>>> type(s1)
<class 'str'>
>>>

We can also use isinstance() function to check if a variable is of a certain type or not. This function returns a boolean value and accepts two arguments.

我们还可以使用isinstance()函数来检查变量是否属于某种类型。 该函数返回一个布尔值并接受两个参数。

>>> x = 10
>>> isinstance(x, int)
True
>>> isinstance(x, str)
False
>>>
>>> o = object()
>>> isinstance(o, (int, str, object))
True

6. Python静态类型检查 (6. Python Static Type Checking)

Python is a dynamically typed language. But, we can use mypy module for static type checking. Note that this will work only when we have added type hints to a function.

Python是一种动态类型的语言。 但是,我们可以使用mypy模块进行静态类型检查。 请注意,这仅在我们向函数中添加了类型提示时才有效。

The mypy module will check the code and raise errors if we are calling the function with incompatible data type arguments. We can install mypy module using the PIP command.

如果我们使用不兼容的数据类型参数调用函数,则mypy模块将检查代码并引发错误。 我们可以使用PIP命令安装mypy模块。

pip install mypy

Let’s say we have a Python script type_checking.py with the below content.

假设我们有一个包含以下内容的Python脚本type_checking.py

def calculate(x, y, op='sum'):
    pass


def calculate1(x: int, y: int, op: str = 'sum') -> int:
    pass


calculate('a', 'b')
calculate1('a', 'b')

Now, we can run mypy from the command line to test this file for function argument types.

现在,我们可以从命令行运行mypy来测试该文件的函数参数类型。

$ mypy type_checking.py
type_checking.py:10: error: Argument 1 to "calculate1" has incompatible type "str"; expected "int"
type_checking.py:10: error: Argument 2 to "calculate1" has incompatible type "str"; expected "int"
Found 2 errors in 1 file (checked 1 source file)
$

7.结论 (7. Conclusion)

In this tutorial, we learned about the statically-typed and dynamically-typed languages. We also learned that for the large codebase, statically-typed code is more beneficial. We learned about the type hints in Python and how to use mypy module as a static type checker.

在本教程中,我们学习了静态类型和动态类型的语言。 我们还了解到,对于大型代码库,静态类型的代码更为有益。 我们了解了Python中的类型提示以及如何将mypy模块用作静态类型检查器。

8.参考 (8. References)

翻译自: https://www.journaldev.com/33542/python-type-checking

python参数检查类型

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐