返回文章列表文章索引阅读全文
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+FFMPEG实现视频分割与合并

前言 日常中偶尔会遇到需要简单剪辑处理视频的场景,以前我可能会拿出PR来剪辑一下,(别跟我说国产那些软件,剪辑完视频强制加上广告片头片尾恶心的一批),但是PR毕竟太重量级,剪个简单的视频都要花不少时间,直到我发现了FFmpeg…… 这个FFmpeg真的是神器,免费开源功能强大,好像很多软件都是基于这个开发的,它本身提供了命令行接口就已经能满足我们日常的简单视频处理需求,我用来简单处理视频分割、合并

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

关于Python的异常处理

前言 异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。 Python 中(至少)有两种错误:语法错误和异常( syntax errors 和 exceptions )。下面稍微介

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

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

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

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

讨论

共 0 条

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

加载评论中…