Table of Contents
一、概述
1、描述
2、常用的数据类型
3、mypy模块
二、使用
1、基本使用
2、函数参数返回值添加类型标注
3、混合类型检查改进
4、类型别名更改
Home Backend Development Python Tutorial How to use variable type annotation in Python

How to use variable type annotation in Python

Apr 29, 2023 pm 07:52 PM
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
'''
Copy after login

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))
Copy after login

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
'''
Copy after login

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;
Copy after login

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"))
Copy after login

在这个例子中,函数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;
Copy after login

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,"类型名称更改"))
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

See all articles