类型提示是 Python 3.5 引入的一项功能,用于在函数定义中添加类型注释。它可以提供静态类型检查和编辑器自动补全的功能,使得代码更加可读和易于理解。在python3.5之后,就新增了对函数参数和返回值的类型指定和检查,以及在新建变量时也可以指定类型。使用类型提示(Type Hints)来声明类型。
1、python数据类型:
https://blog.csdn.net/weixin_49520696/article/details/134172661
-
- python基本数据类型:int、float、bool、bytes
-
- Python 内置容器: dict、list、set 和 tuple
- 3.Python 泛型:(typing模块)
Python 的泛型用于指示某些数据结构或函数可以接受多种数据类型,例如使得一个函数的参数能够接收多种类型的数据或者使得一个类能够接收并存储不同种类的数据。泛型在 Python 中通常通过模块 typing 实现。泛型的使用有助于提高代码的可读性和健壮性,尤其是在大型项目和团队协作中。
Python 中的泛型是使用 typing 模块中的 TypeVar 和 Generic 进行实现的。TypeVar 用于定义泛型类型变量,而 Generic 用于定义泛型类或函数。
typing 模块中的泛型支持包括一系列的泛型类型和类型变量,例如 List、Dict、Tuple 等。开发者可以使用这些泛型类型来声明具有泛型参数的数据结构或函数签名。此外,Python 3.9 引入了更多强大的泛型支持,包括 Literal、TypedDict 等新的泛型类型。
需要注意的是,Python 中的泛型类型提示仅用于静态类型检查和文档说明,并不影响运行时的行为。Python 解释器不会强制执行类型提示,因此在运行时仍然可以传入任何类型的参数。
from typing import TypeVar, Generic
T = TypeVar('T')
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3])) # 1
print(first(["apple", "banana", "cherry"])) # apple
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
stack = Stack[int]()
stack.push(1)
stack.push(2)
print(stack.pop()) # 2
typing常用类型
int、long、float:整型、长整形、浮点型
bool、str:布尔型、字符串类型
List、 Tuple、 Dict、 Set:列表、元组、字典、集合
Iterable、Iterator:可迭代类型、迭代器类型
Generator:生成器类型
2、python类型提示
python对函数的参数和返回值进行指定类型和检查
https://blog.csdn.net/sgyuanshi/article/details/96192887
https://geek-docs.com/python/python-ask-answer/472_python_how_to_specify_multiple_return_types_using_typehints.html
类型提示是 Python 3.5 引入的一项功能,用于在函数定义中添加类型注释。它可以提供静态类型检查和编辑器自动补全的功能,使得代码更加可读和易于理解。在python3.5之后,就新增了对函数参数和返回值的类型指定和检查,以及在新建变量时也可以指定类型。使用类型提示(Type Hints)来声明类型。
1.指定参数类型
- 基本类型指定:
def add(x: int, y: int) -> int:
return x + y
- 容器类型
from typing import List, Tuple, Dict
def add(a: int, string: str, f: float,
b: bool) -> Tuple[List, Tuple, Dict, bool]:
list1 = list(range(a))
tup = (string, string, string)
d = {"a": f}
bl = b
return list1, tup, d, bl
print(add(5, "hhhh", 2.3, False))
([0, 1, 2, 3, 4], ('hhhh', 'hhhh', 'hhhh'), {'a': 2.3}, False)
在传入参数时通过"参数名:类型"的形式声明参数的类型;
返回结果通过"-> 结果类型"的形式声明结果的类型。
- 泛型
TypeVar允许创建泛型函数或类。Callable和Sequence等泛型类型的使用。
T = TypeVar('T') # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
A = Union[str, None] # Must be str or None
from typing import Sequence, TypeVar, Union
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
- Union类型注释
https://fastapi.tiangolo.com/python-types
Union 类型允许同时使用多个数据类型,其中任何一种类型的值都可以传递给函数。在注释中,我们使用 or 或 | 分隔多个数据类型。您可以声明变量是几种类型中的任意一种,例如int或str。
在 Python 3.6 及更高版本(包括 Python 3.10)中,您可以使用类型Unionfromtyping并在方括号内放入可能接受的类型。
在 Python 3.10 中还有一种新语法,您可以用竖线 ( |)分隔可能的类型。
#Python 3.6 及更高版本
from typing import Union
def process_item(item: Union[int, str]):
print(item)
# Python 3.10 中还有一种新语法,您可以用竖线 ( |)分隔可能的类型。
def process_item(item: int | str):
print(item)
- Optional 类型注释
Optional类型表示一个可选的数据类型,它可用于表示参数可以是一种数据类型或 None 值。我们使用 Optional[type] 表示该函数参数可以是 type 或 None 值。
使用Optional[str]而不是 只会str让编辑器帮助您检测错误,您可能会假设某个值始终是str,而实际上它也可能也是None。Optional[Something]实际上是 的简写Union[Something, None],它们是等效的。这也意味着在 Python 3.10 中,你可以使用Something | None:
#Python 3.6 及更高版本
from typing import Optional
def say_hi(name: Optional[str] = None):
if name is not None:
print(f"Hey {name}!")
else:
print("Hello World")
from typing import Union
def say_hi(name: Union[str, None] = None):
if name is not None:
print(f"Hey {name}!")
else:
print("Hello World")
#在 Python 3.10 中,你可以使用Something | None:
def say_hi(name: str | None = None):
if name is not None:
print(f"Hey {name}!")
else:
print("Hello World")
- 嵌套的容器类型
嵌套容器(Nested container)是指容器中又包含其他容器。 typing 模块为这种数据类型提供了更复杂的注释方式。
from typing import List, Tuple
def my_function(arg1: List[Tuple[int, str]]) -> List[str]:
"""
接受一个整型列表中包含元组(整型,字符串),返回由元组中包含的字符串组成的列表。
"""
return [x[1] for x in arg1]
from pydantic import BaseModel
class PetCls:
def __init__(self, *, name: str, species: str):
self.name = name
self.species = species
class PersonCls:
def __init__(self, *, name: str, age: float = None, pets: list[PetCls]):
self.name = name
self.age = age
self.pets = pets
class Pet(BaseModel):
name: str
species: str
class Config:
orm_mode = True
class Person(BaseModel):
name: str
age: float = None
pets: list[Pet]
class Config:
orm_mode = True
bones = PetCls(name='Bones', species='dog')
orion = PetCls(name='Orion', species='cat')
anna = PersonCls(name='Anna', age=20, pets=[bones, orion])
anna_model = Person.from_orm(anna)
print(anna_model)
#> name='Anna' age=20.0 pets=[Pet(name='Bones', species='dog'),
#> Pet(name='Orion', species='cat')]
- Any 类型
Any 是一种特殊的类型。静态类型检查器将所有类型视为与 Any 兼容,反之亦然, Any 也与所有类型相兼容。这意味着可对类型为 Any 的值执行任何操作或方法调用,并将其赋值给任何变量。
2、指定返回值类型
返回结果通过"-> 结果类型"的形式声明结果的类型。
如何指定多个返回类型
在 Python 中,单个函数可以返回多个不同类型的值。这种情况下,我们可以使用 typing 模块中的 Union 类来指定多个返回类型。
typing.Union 类接受一个或多个类型作为参数,并返回一个包含了这些类型的联合类型。下面是一个使用 Union 类指定多个返回类型的示例:
from typing import Union
def divide(x: int, y: int) -> Union[int, float]:
if y == 0:
return float('inf')
else:
return x / y
在这个示例中,函数 divide 接受两个参数 x 和 y 的类型都为 int,并且返回类型为 Union[int, float]。如果 y 的值为 0,函数返回 float(‘inf’),否则返回 x / y 的结果。
3、类型检查工具
在 Python 中,我们可以使用第三方工具进行类型检查,以保证代码的正确性。常用的类型检查工具有 mypy、pylint 和 pyright 等。
mypy 是最受欢迎的静态类型检查工具之一,它可以检查代码中的类型错误和不一致之处,并提供有关如何修复这些错误的建议。使用 mypy 可以使代码更加健壮和可维护。
from typing import Union
def divide(x: int, y: int) -> Union[int, float]:
if y == 0:
return float('inf')
else:
return x / y
result = divide(5, 2)
print(result)
在命令行中运行以下命令进行类型检查:
mypy test.py
3、Pydantic 模型(数据接口)
Pydantic 用在web数据接口上对数据格式类型进行检测。
FastAPI 站在以下巨人的肩膀之上:
Starlette 负责 web 部分。
Pydantic 负责数据部分。
pydantic库是一种常用的用于数据接口schema定义与检查的库。Pydantic 在运行时强制执行类型提示,并在数据无效时提供用户友好的错误信息。
Pydantic 模型:
Pydantic 是一个用来用来执行数据校验的 Python 库。
你可以将数据的"结构"声明为具有属性的类。每个属性都拥有类型。接着你用一些值来创建这个类的实例,这些值会被校验,并被转换为适当的类型(在需要的情况下),返回一个包含所有数据的对象。