Python 函数参数类型检查

Python 函数参数类型检查

  • tags: Python, lint, type-checking, mypy
  • create: 2024.09.01 12:40
  • author: ChrisZZ imzhuo@foxmail.com

1. 问题描述

test.py 中编写了代码:

定义函数:

py 复制代码
def hello(capitalize: bool=False):
    if capitalize:
        print(f'Hello, World')
    else:
        print(f'hello, world')

调用函数:

py 复制代码
hello(True)

运行得到:

Hello, World

某天,重构了函数, 得到:

py 复制代码
def hello(name: str, capitalize: bool=False):
    if capitalize:
        print(f'Hello, {name}.upper()')
    else:
        print(f'hello, {name}')

忘记修改调用代码; 程序执行没有报错,不过并不符合预期:

hello, True

预期的是程序报错, 而不是把 True 这一 bool 类型的参数当作 str 类型处理。

解决办法

使用 mypy 做类型检查

安装:

py 复制代码
pip install mypy

检查:

py 复制代码
mypy test.py

报错内容:

bash 复制代码
test.py:15: error: Argument 1 to "hello" has incompatible type "bool"; expected "str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

低版本 Python 不支持类型注解?

Python3 从 3.5 版本开始支持类型注解。当 Python3 < 3.5, 或者 Python 版本为 Python2, 不支持 <var>:<type> 的类型注解形式。

对于上述情况,如果能保证开发环境是 Python >= 3.5, 那么就可以使用 mypy 执行类型检查;把类型注解写到注释中, mypy 就会识别。 基于前一节的代码, 在注释用标明类型注解后如下:

py 复制代码
def hello(name, capitalize=False):
    # type: (str, bool) -> None
    if capitalize:
        print(f'Hello, {name}.upper()')
    else:
        print(f'hello, {name}')

hello(True)

运行:

bash 复制代码
mypy test.py

输出如下,符合预期

bash 复制代码
test.py:22: error: Argument 1 to "hello" has incompatible type "bool"; expected "str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)
相关推荐
Yuner20002 分钟前
Python机器学习:从零基础到深度实战
人工智能·python·机器学习
r i c k18 分钟前
办公小程序开发----提高工作效率
python·python程序开发
wha the fuck40418 分钟前
(渗透脚本)TCP创建连接脚本----解题----极客大挑战2019HTTP
python·网络协议·tcp/ip·网络安全·脚本书写
qq_3561969518 分钟前
day39模型的可视化和推理@浙大疏锦行
python
深蓝电商API25 分钟前
从 “能爬” 到 “稳爬”:Python 爬虫中级核心技术实战
开发语言·爬虫·python
czlczl2002092541 分钟前
如何添加“默认给Sql查询语句加上租户条件”的功能
数据库·python·sql
破烂pan41 分钟前
Python 长连接实现方式全景解析
python·websocket·sse
高洁0143 分钟前
一文了解图神经网络
人工智能·python·深度学习·机器学习·transformer
咸鱼加辣1 小时前
按“最近是否用过”删(LRU)
python
serve the people1 小时前
tensorflow 零基础吃透:创建 tf.sparse.SparseTensor 的核心方法
人工智能·python·tensorflow