python 静态检查_python中的静态类型检查

python 静态检查

Python 3.5 introduced Type Hints, a new feature that allows developers to use static type checking in python.

Python 3.5引入了Type Hints ,这是一项新功能,允许开发人员在python中使用静态类型检查。

Python中的类型检查 (Type checking in Python)

Python is a duck typed programming language. Duck typing in computer programming is an application of the duck test:

Python是一种鸭子式编程语言。 鸭子在计算机编程中的打字是鸭子测试的一种应用:

If it walks like a duck and it quacks like a duck, then it must be a duck.

如果它走路像鸭子,嘎嘎叫鸭子,那它一定是鸭子。

Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.

鸭子类型是与动态类型相关的概念,其中对象的类型或类比其定义的方法重要。 使用鸭子类型时,根本不会检查类型。 而是,检查给定方法或属性的存在。

In the following gist you can see an example that demonstrates how any object may be used in any context, up until it is used in a way that it is not supported:

在下面的要点中,您可以看到一个示例,该示例演示如何在任何上下文中使用任何对象,直到以不支持该对象的方式使用该对象:

Running the code above would result in the following output:

运行上面的代码将导致以下输出:

Duck flying
Sparrow flying
AttributeError: 'Whale' object has no attribute 'fly'

Duck and Sparrow are Flying animals because they know how to fly. Whale isn’t because it doesn’t :)

鸭子和麻雀是会飞的动物,因为他们会飞。 鲸不是因为它不是:)

Python中的静态类型检查 (Static type checking in Python)

Since Python 3.5 we can use the Type Hints to check the types in our python code. Now, we can write something similar like this:

从Python 3.5开始,我们可以使用Type Hints来检查python代码中的类型。 现在,我们可以编写类似以下内容:

In the example above we have defined a function that takes a string type parameter and returns a string value. Then, if we call the greeting function we must pass a string value as parameter. We can assume that the returned value of the function will also be a string.

在上面的示例中,我们定义了一个函数,该函数采用字符串类型参数并返回字符串值。 然后,如果调用greeting函数,则必须传递一个字符串值作为参数。 我们可以假定函数的返回值也将是一个字符串。

As its name suggests, the Type Hints are just that, hints, so we can write this code and run it without errors:

顾名思义,类型提示就是提示,因此我们可以编写以下代码并运行它而不会出现错误:

So, how we can check these hints? We must use a static type checker for this purpose. mypy is an optional static type checker for Python that aims to combine the benefits of duck typing and static typing. We can install mypy by running this command:

那么,我们如何检查这些提示? 为此,我们必须使用静态类型检查器。 mypy是Python的可选静态类型检查器,旨在结合鸭子类型和静态类型的优点。 我们可以通过运行以下命令来安装mypy:

$ python -m pip install mypy

Once installed, we can check the last example:

安装完成后,我们可以检查最后一个示例:

$ mypy sample.py
sample.py:4: error: Argument 1 to "greeting" has incompatible type "int"; expected "str"
Found 1 error in 1 file (checked 1 source file)

As we can see an error is found because we are passing an integer value to the greeting function, which expected a string.

如我们所见,发现错误是因为我们将整数值传递给了期望的字符串的greeting函数。

We can integrate this tool in our favorite editor and check these errors while coding. In Visual Studio Code, we can integrate it by installing the python extension and adding the "python.linting.mypyEnabled": true line to the .vscode/settings.json project file:

我们可以将此工具集成到我们最喜欢的编辑器中,并在编码时检查这些错误。 在Visual Studio Code中,我们可以通过安装python扩展并将"python.linting.mypyEnabled": true行添加到.vscode/settings.json项目文件中来进行.vscode/settings.json

类型基础 (Type basics)

The most basic thing that we can do with the Type Hints is to assign types to variables using the built-in types:

我们可以使用类型提示执行的最基本的操作是使用内置类型将类型分配给变量:

Also, we can use the type hints for our functions, declaring the argument types but also the returned type:

另外,我们可以为函数使用类型提示,既声明参数类型又声明返回的类型:

Type hints can also be used with classes:

类型提示也可以与类一起使用:

声明我们自己的类型 (Declaring our own types)

While we can use the built-in types in our projects, we can also declare our own.

虽然我们可以在项目中使用内置类型,但也可以声明自己的类型。

With type aliases we can declare a type assigning an existing type to an alias. For example, we could declare a Point type reusing the Tuple[float, float] type:

使用类型别名,我们可以声明将现有类型分配给别名的类型。 例如,我们可以声明一个Point类型,重用Tuple[float, float]类型:

The typing module also includes the NewType helper function that we can use to create distinct types. This function accepts two parameters: the name of the new type and the underlying type to use. In the following gist we refactored the last example in order to use the NewType helper:

typing模块还包括NewType辅助函数,我们可以使用该函数来创建不同的类型。 该函数接受两个参数:新类型的名称和要使用的基础类型。 在下面的要点中,我们重构了最后一个示例,以便使用NewType帮助器:

There are some differences between using aliases or types defined with the NewType helper. The use of a type alias declares two types to be equivalent to one another. Doing Point = Tuple[float, float] will make the static type checker treat Point as being exactly equivalent to Tuple[float, float]. This is useful when you want to simplify complex type signatures. In contrast, NewType declares one type to be a subtype of another. Doing Point= NewType('Point', Tuple[float, float]) will make the static type checker treat Point as a subclass of Tuple[float, float], which means a value of type Tuple[float, float] cannot be used in places where a value of type Point is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

使用别名或通过NewType帮助器定义的类型之间存在一些差异。 使用类型别名可以声明两种类型彼此等效 。 执行Point = Tuple[float, float]将使静态类型检查器将Point视为与Tuple[float, float] 完全等效 。 当您要简化复杂的类型签名时,这很有用。 相反, NewType将一种类型声明为另一种类型的子类型 。 做Point= NewType('Point', Tuple[float, float])将使静态类型检查器将Point视为Tuple[float, float]子类 ,这意味着不能使用Tuple[float, float]类型的值在需要Point类型的值的地方。 当您希望以最小的运行时成本来防止逻辑错误时,这很有用。

加起来 (Summing up)

Type Hints is a powerful feature that give us support to do type checking in our projects. This can help us to avoid code mistakes and it’s also useful to better understand the intent of the code.

类型提示是一项强大的功能,可为我们提供在项目中进行类型检查的支持。 这可以帮助我们避免代码错误,并且有助于更好地理解代码的意图。

翻译自: https://medium.com/trabe/static-type-checking-in-python-58a46cf94f8a

python 静态检查

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值