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)
相关推荐
站大爷IP1 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780517 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i7 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05067 小时前
【ESP32-CAM】HELLO WORLD
python
Doris_20238 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20238 小时前
Python 模式匹配match case
前端·后端·python
这里有鱼汤8 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩9 小时前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp
测试老哥9 小时前
Selenium 使用指南
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
百锦再9 小时前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame