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)
相关推荐
后台开发者Ethan34 分钟前
LangGraph ReAct应用
python·langgraph
f***686043 分钟前
问题:Flask应用中的用户会话(Session)管理失效
后端·python·flask
爱吃面条的猿1 小时前
Python修改pip install 指定安装包的路径和默认镜像源
linux·python·pip
饭饭大王6661 小时前
Python 模块的概念与导入:从基础语法到高级技巧
java·服务器·python
Sunhen_Qiletian1 小时前
python语言应用实战--------网络爬虫篇 第二篇(selenium库)
爬虫·python·selenium
鄃鳕2 小时前
装饰器【Python】
开发语言·python·数码相机
m0_528489252 小时前
Pycharm修改系统缓存路径(包含config, system, plugins, logs, remote sources等)
ide·python·pycharm·c盘
Franklin3 小时前
AI Coding 基础实践03 - Trae AI在Pycharm中的使用02 - 读取不了项目的文件问题解决
ide·python·pycharm
胖墩会武术3 小时前
【OpenCV图像处理】深度学习:cv2.dnn() —— 图像分类、人脸检测、目标检测
图像处理·pytorch·python·opencv