python typing库的常用操作

本文介绍了Python的typing库,用于增强代码的可读性和支持类型提示。通过使用mypy编译器进行静态类型检查,可以检测类型错误。文章展示了如何创建类型别名、定义NewType自定义数据类型,并通过示例说明了它们在实际代码中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typing库的常用操作


本篇文章是介绍typing库的基本操作,更深入,更高级的用法可以查看官方文档
https://docs.python.org/3/library/typing.html

使用意义

为了提高python代码的可读性,我们可以用typping做类型提示,提示变量的值。同时,在IDE中,添加类型提示可以更方便地使用联想功能,提高生产力。

添加mypy编译器

需要注意的是,类型提示并不是强制转化变量类型,只是为了提高代码可读性。如果想要增加类型检查的功能,可以使用mypy,它是Python 中的静态类型检查器。用以下指令安装:

# 安装方法
pip3 install mypy

# 使用方法
mypy 'py文件路径'

使用typping给类型起别名

from typing import List

# Vector is a list of float values
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

a = scale(scalar=2.0, vector=[1.0, 2.0, 3.0])
print(a)
[2.0, 4.0, 6.0]

在以上的例子中,我们定义了Vector这个类型,作为列表List的别名,同时提示了列表中的内容是float类型。

from typing import Dict
import re

ConcatDict=Dict[str,str]

def check_if_valid(contacts: ConcatDict) -> bool:
    for name,email in contacts.items():
        if(not isinstance(name,str)) or (not isinstance(email,str)): # 检查是否都是str类型
            return False
        if not re.match(r"[a-zA-Z0-9\._\+-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+$", email): # 检查email的格式
            return False
    return True

print(check_if_valid({'vijay': 'vijay@sample.com'}))
print(check_if_valid({'vijay': 'vijay@sample.com', 123: 'wrong@name.com'}))
example.py:15: error: Dict entry 1 has incompatible type "int": "str"; expected "str": "str"  [dict-item]
Found 1 error in 1 file (checked 1 source file)

在这个例子中,规定了新的类型ConcatDict,要求字典的键和值都为str类型。

可以看到报错出现在最后一行,因为字典中的键为123,所以报错。

使用NewType()创建自定义数据类型

利用NewType来创建自定义数据类型,其使用方法为Newtype(数据类型名字,数据类型)

from typing import NewType

StudentID=NewType('StudentID',int)
sutdent_id=StudentID(100)

def print_student_id(s_id:StudentID) -> None:
    print(f'当前学生ID为{s_id}')
    
print_student_id(sutdent_id)
print_student_id(100)
example.py:35: error: Argument 1 to "print_student_id" has incompatible type "int"; expected "StudentID"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

如上面这个例子,当我们创建StudentID这个类型时,将他作为int的子类,所以当我们传入int变量到自定义函数`print_student_id时,在mypy中编译则会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值