返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Python

Using Python 3's New Feature Type Annotations to Improve Code Readability

Look at the code first def add(x: int, y: int) - int: return x + y Those who haven't used type annotations (Type Annotations) might find it a bit confusing at first glance. In fact, the code above is the same as the following. def add(x, y): return x + y Introduction to Type Annotations We know that Python is a dynamic language; variables and function parameters are not distinguished by type. The Python interpreter will at run

曦远 (DealiAxy)约 8 分钟
目录4 个章节

Look at the Code First

def add(x: int, y: int) -> int:
    return x + y

Those who haven't used type annotations (Type Annotations) might find it a bit confusing at first glance. In fact, the code above is the same as the following.

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

Introduction to Type Annotations

We know that Python is a dynamic language; variables and function parameters are not distinguished by type. The Python interpreter dynamically determines the types of variables and parameters at runtime. The advantage of this is that writing code is very fast and flexible, but the downside is also obvious: it's hard to maintain. After writing the code for a while, looking at it again can be difficult to understand, because the types of those variables, parameters, and function return values have all been forgotten. And when you're reading someone else's code, you also can't tell the types of variables or parameters at a glance; you often have to figure them out yourself, which creates a significant obstacle to learning.

So Python 3 has this new feature that lets you add annotations for the types of parameters, function return values, and variables. However, this is merely a comment and has no effect whatsoever on the running of the code. The actual types of variables are still determined by the Python interpreter. All you're doing is improving the readability of the code, nothing more.

Look at the Code

def add(x: int, y: int) -> int:
    return x + y


def area_calculation(radius: float) -> float:
    # 变量类型注解需要 py3.6 以上版本
    # Var Type Annotations need python 3.6 and later
    pi: float = 3.1415926
    return radius * radius * pi


if __name__ == '__main__':
    print(add(1, 2))
    print(add.__annotations__)
    print(area_calculation(2))
    print(area_calculation.__annotations__)

Run result:

3
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
12.5663704
{'radius': <class 'float'>, 'return': <class 'float'>}

Here we called the function's __annotations__ attribute, through which you can see the annotations for parameter and return value types.

Testing the Correctness of Annotations

As mentioned earlier, these annotations only serve as comments and do not affect code execution, so even if you write the type annotations incorrectly, the program will still run according to the correct types at runtime. Then, Python provides a tool that makes it convenient for us to test the correctness of type annotations in the code, mypy

First, install:

pip install mypy

To test:

mypy filename.py

If there are no errors, there is no output; if there are errors, there will be corresponding output, such as

$ mypy demo.py
demo.py:14: error: Incompatible return value type (got "float", expected "int")

_EOF_

Using Python 3's New Feature Type Annotations to Improve Code Readability

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

手写核心价值观编码工具-Python实现

前言 今天是五一劳动节,祝各位无产阶级劳动者节日快乐! 然后来整活分享一些有趣的东西~ 这个小工具是我大学时做着玩的,对于各位接班人来说,12个词的核心价值观这东西,大家都非常熟悉了,这工具可以实现将一段话编码为核心价值观实现加密,同时也能将密文解密出来。 为啥要做这个呢,隔太久不太记得了,~~好像是因为游戏里喷队友老是被屏蔽,灵机一动,要是换成和谐的文字不就不会被屏蔽了吗(误~~ 实现原理 简单

2022-05-01 · Python · 约 1 分钟

我用Qt和Python开发了一个视频合并工具

想合并视频,但是却找不到比较好用的工具,很多都要收费,我想着「这破功能还得收费?」,于是决定自己搞一个,一开始用Python做了一个,效果还不错,完美完成了我的视频合并任务,不过没有图形界面,想分享给朋友一起用也没办法,于是昨天用Qt写了个图形界面套上去,中间还是遇到一些问题的,通过这篇文章记录一下。 软件的界面就是这样啦,用Qt Designer随便拖出来的,和VS拖控件也差不了多少。 用起来挺

2021-12-18 · Python · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…