Python 函数参数类型检查

Python 函数参数类型检查

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

1. 问题描述

test.py 中编写了代码:

定义函数:

def hello(capitalize: bool=False):
    if capitalize:
        print(f'Hello, World')
    else:
        print(f'hello, world')

调用函数:

hello(True)

运行得到:

Hello, World

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

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 做类型检查

安装:

pip install mypy

检查:

mypy test.py

报错内容:

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 就会识别。 基于前一节的代码, 在注释用标明类型注解后如下:

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

hello(True)

运行:

mypy test.py

输出如下,符合预期

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)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值