search
HomeBackend DevelopmentPython TutorialHow to use variable type annotation in Python

一、概述

1、描述

变量类型注解是用来对变量和函数的参数返回值类型做注解,让调用方减少类型方面的错误,也可以提高代码的可读性和易用性。

但是,变量类型注解语法传入的类型表述能力有限,不能说明复杂的类型组成情况,因此引用了typing模块,来实现复杂的类型表达。

2、常用的数据类型

Type Description
int 整型 integer
float 浮点数字
bool 布尔(int 的子类)
str 字符 (unicode)
bytes 8 位字符
object 任意对象(公共基类)
List[str] 字符组成的列表
Tuple[int, int] 两个int对象的元组
Tuple[int, ...] 任意数量的 int 对象的元组
Dict[str, int] 键是 str 值是 int 的字典
Iterable[int] 包含 int 的可迭代对象
Sequence[bool] 布尔值序列(只读)
Mapping[str, int] 从 str 键到 int 值的映射(只读)
Any 具有任意类型的动态类型值
Union 联合类型
Optional 参数可以为空或已经声明的类型
Mapping 映射,是 collections.abc.Mapping 的泛型
MutableMapping Mapping 对象的子类,可变
Generator 生成器类型, Generator[YieldType、SendType、ReturnType]
NoReturn 函数没有返回结果
Set 集合 set 的泛型, 推荐用于注解返回类型
AbstractSet collections.abc.Set 的泛型,推荐用于注解参数
Sequence collections.abc.Sequence 的泛型,list、tuple 等的泛化类型
TypeVar 自定义兼容特定类型的变量
Generic 自定义泛型类型
NewType 声明一些具有特殊含义的类型
Callable 可调用类型, Callable[[参数类型], 返回类型]
NoReturn 没法返回值

3、mypy模块

mypy是Python的可选静态类型检查器

安装mypy模块 pip3 install mypy

使用mypy进行静态类型检查 mypy 执行 python 文件

二、使用

1、基本使用

from typing import List, Set, Dict, Tuple
#对于简单的 Python 内置类型,只需使用类型的名称
x1: int = 1
x2: float = 1.0
x3: bool = True
x4: str = "test"
x5: bytes = b"test"
 
# 对于 collections ,类型名称用大写字母表示,并且
# collections 内类型的名称在方括号中
x6: List[int] = [1]
x7: Set[int] = {6, 7}
#对于映射,需要键和值的类型
x8: Dict[str, float] = {'field': 2.0}
#对于固定大小的元祖,指定所有元素的类型
x9: Tuple[int, str, float] = (3, "yes", 7.5)
#对于可变大小的元祖,使用一种类型和省略号
x10: Tuple[int, ...] = (1, 2, 3)
 
'''在终端执行检查
(venv) D:\python>mypy .\01.py
Success: no issues found in 1 source file
'''

2、函数参数返回值添加类型标注

1. 指定多个参数的方式

'''
定义一个函数   参数 num int类型
返回值 字符串类型
使用mypy检测
'''
def num_fun(num: int) -> str:
    return str(num)
 
num_fun(100)
print(num_fun(100))
 
# 指定多个参数的方式
def plus(num1: int, num2: int) -> int:
    return num1 + num2
 
# 在类型注释后为参数添加默认值,默认值需要添加在末尾
'''
声明函数参数时,所有带有默认值的参数必须放在非默认参数的后面。
这是因为 Python 解释器需要确定参数传递的顺序,
如果默认参数放在非默认参数前面,解释器就无法确定哪个参数是哪个
'''
def func1(num1: int, my_float: float = 3.5)-> float:
    return num1 + my_float
print(func1(10,20))
f = func1
print(f(10))

2. Callable

Callable 是一个抽象类,用于描述可调用对象的基本行为,例如函数、方法和类。当你声明一个函数变量并将其分配给一个变量时,这个变量只是一个普通的 Python 对象,并不是一个可调用对象,因此它没有默认值

带有默认值的参数可以放在任何位置,但是在声明函数参数时,所有带有默认值的参数必须放在非默认参数的后面。这是因为 Python 解释器需要确定参数传递的顺序,如果默认参数放在非默认参数前面,解释器就无法确定哪个参数是哪个。

from typing import  Callable
#定义变量  指向一个函数
def func2(num1:int, my_float=3.5) -> str:
    return f'返回结果{num1 + my_float}'
print(func2(10))
#Callable指向可调用(函数)值的方式
x: Callable[[int, float], str] = func2
print(x(10, 3.5))
 
'''
执行结果
返回结果13.5
返回结果13.5
'''

3. Iterator

#定义函数,产生整数的生成器,每次返回一个
from typing import Iterator
# 产生整数的生成器函数安全地返回只是一个 整数迭代器的函数
#,因此这就是我们对其进行注释的方式
def g(n: int) -> Iterator[int]:
    i = 0
    while i < n:
        yield i #下次迭代时,代码从 yield 的下一条语句(不是下一行)开始执行
        i += 1
 
print(g(10))
for i in g(10):
    print(i)
 
&#39;&#39;&#39;执行结果
<generator object g at 0x00000000014E88E0>
0
1
2
3
4
5
6
7
8
9
&#39;&#39;&#39;

3、混合类型检查改进

1.联合运算符

联合运算符使用 " | "  线来替代了旧版本中Union[] 方法,使得程序更简洁

#新版本
def get_name(user: str | dict) -> str:
    if isinstance(user, str):
        return user
    elif isinstance(user, dict):
        return user.get(&#39;name&#39;, &#39;&#39;)
print(get_name({&#39;name&#39;:&#39;Bob&#39;}))
print(get_name("Alice"))

在这个例子中,函数get_name接受一个参数user,它可以是一个字符串或一个字典。如果user是一个字符串,函数会直接返回这个字符串;如果user是一个字典,函数会尝试从字典中获取name字段的值,并返回它。

在这个例子中,我们使用联合运算符将str和dict类型组合起来,表示user可以是这两种类型之一。

#旧版本,Union方法来实现相同的功能
from typing import Union
def get_name2(user: Union[str, dict]) -> str:
    if isinstance(user, str):
        return user
    elif isinstance(user, dict):
        return user.get(&#39;name&#39;, &#39;&#39;)
 
print(get_name2({&#39;name&#39;:&#39;Bob&#39;}))
print(get_name2("Alice"))
&#39;&#39;&#39;执行结果
Bob
Alice
&#39;&#39;&#39;

4、类型别名更改

#旧版本
oldname = str
def oldFunc(param:oldname) -> oldname:
    return param + param
oldFunc(&#39;oldFunc:花非人陌&#39;)
 
 
#新版本,从3.10后开始支持
from typing import TypeAlias
 
newstr :TypeAlias = str    #定义类型别名
newint :TypeAlias = int
def func_test(num:newint, msg:newstr)->newstr:
    return str(num) + msg
print(func_test(100,"类型名称更改"))

The above is the detailed content of How to use variable type annotation in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

What is a lambda function?What is a lambda function?Apr 28, 2025 pm 04:28 PM

Article discusses lambda functions, their differences from regular functions, and their utility in programming scenarios. Not all languages support them.

What is a break, continue and pass in Python?What is a break, continue and pass in Python?Apr 28, 2025 pm 04:26 PM

Article discusses break, continue, and pass in Python, explaining their roles in controlling loop execution and program flow.

What is a pass in Python?What is a pass in Python?Apr 28, 2025 pm 04:25 PM

The article discusses the 'pass' statement in Python, a null operation used as a placeholder in code structures like functions and classes, allowing for future implementation without syntax errors.

Can we Pass a function as an argument in Python?Can we Pass a function as an argument in Python?Apr 28, 2025 pm 04:23 PM

Article discusses passing functions as arguments in Python, highlighting benefits like modularity and use cases such as sorting and decorators.

What is the difference between / and // in Python?What is the difference between / and // in Python?Apr 28, 2025 pm 04:21 PM

Article discusses / and // operators in Python: / for true division, // for floor division. Main issue is understanding their differences and use cases.Character count: 158

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.