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)
相关推荐
田姐姐tmner1 天前
Python 全面语法指南
开发语言·python
white-persist1 天前
【攻防世界】reverse | simple-check-100 详细题解 WP
c语言·开发语言·汇编·数据结构·c++·python·算法
王大傻09281 天前
Series的属性简介
python·pandas
A0_張張1 天前
记录一个PDF盖章工具(PyQt5 + PyMuPDF)
开发语言·python·qt·pdf
Faker66363aaa1 天前
Arive-Dantu叶片识别系统:基于cascade-mask-rcnn_regnetx-400MF_fpn_ms-3x_coco模型实现_1
python
想你依然心痛1 天前
AI赋能编程语言挑战赛:从Python到Rust,我用AI大模型重塑开发效率
人工智能·python·rust
quikai19811 天前
python练习项目
python
周杰伦_Jay1 天前
【Python开发面试题及答案】核心考点+原理解析+实战场景
开发语言·python
HyperAI超神经1 天前
【vLLM 学习】vLLM TPU 分析
开发语言·人工智能·python·学习·大语言模型·vllm·gpu编程
爱笑的眼睛111 天前
FastAPI 请求验证:超越 Pydantic 基础,构建企业级验证体系
java·人工智能·python·ai