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
目录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踩坑:类与类对象类型参数传递与使用
前言 对初学者来说,Python确实简单好用,毕竟动态类型语言,不用定义就可以拿来用,类型之间随意转换简直不要太方便,因此Python用来写写小脚本,爬虫程序什么的,没什么问题。 不过,一旦用来开发稍微大型一点的项目,例如搭建一个Web应用,就会遇到一些问题,一般缺乏经验的人都会陷入某些坑中。= =... 坑 先说坑,函数参数类型是一坑,类与类的对象这又是一坑。 虽然之前用其他静态类型语言(例如C
2022-05-27 · Python · 约 1 分钟
Python-本地时间和UTC时间转换
代码 import time import datetime def utc2local(utc_st): UTC时间转本地时间(+8: 00) now_stamp = time.time() local_time = datetime.datetime.fromtimestamp(now_stamp) utc_time = datetime.datetime.ut
2021-12-18 · Python · 约 1 分钟
配置pip国内镜像加快python第三方库安装速度~
现在这网络对于开发者来说有点不太友好,下载什么东西都慢慢,pip install慢,git clone也慢,难受…… 不过还好有各种代替的国内镜像源可以加速 临时配置 在使用pip的时候加参数-i https://pypi.tuna.tsinghua.edu.cn/simple 例如:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple d
2022-11-12 · Python · 约 1 分钟
手写核心价值观编码工具-Python实现
前言 今天是五一劳动节,祝各位无产阶级劳动者节日快乐! 然后来整活分享一些有趣的东西~ 这个小工具是我大学时做着玩的,对于各位接班人来说,12个词的核心价值观这东西,大家都非常熟悉了,这工具可以实现将一段话编码为核心价值观实现加密,同时也能将密文解密出来。 为啥要做这个呢,隔太久不太记得了,~~好像是因为游戏里喷队友老是被屏蔽,灵机一动,要是换成和谐的文字不就不会被屏蔽了吗(误~~ 实现原理 简单
2022-05-01 · Python · 约 1 分钟
讨论
共 0 条加载评论中…