Python -类型提示 Type Hints

简介: Python -类型提示 Type Hints

为什么会有类型提示


  • Python是一种动态类型语言,这意味着我们在编写代码的时候更为自由,运行时不需要指定变量类型
  • 但是与此同时 IDE 无法像静态类型语言那样分析代码,及时给我们相应的提示,比如字符串的 split 方法

def split_str(s):

   strs = s.split(",")

由于不知道参数 s 是什么类型,所以当你敲  s.  的时候不会出现 split 的语法提示

 

解决上述问题,类型提示

Python 3.5、3.6 新增了两个特性 PEP 484 和 PEP 526

帮助 IDE 为我们提供更智能的提示

这些新特性不会影响语言本身,只是增加一点提示

 

类型提示分类


主要分两个

  • 变量提示:PEP 526 特性加的
  • 函数参数提示:PEP 484 特性加的

 

变量类型提示


没有使用类型提示

想说明变量的数据类型只能通过注释

# 'primes' is a list of integers
primes = []  # type: List[int]
# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str
class Starship:
    # 'stats' is a class variable
    stats = {}  # type: Dict[str, int]


使用了类型提示

from typing import List, ClassVar, Dict
# int 变量,默认值为 0
num: int = 0
# bool 变量,默认值为 True
bool_var: bool = True
# 字典变量,默认为空
dict_var: Dict = {}
# 列表变量,且列表元素为 int
primes: List[int] = []
class Starship:
    # 类变量,字典类型,键-字符串,值-整型
    stats: ClassVar[Dict[str, int]] = {}
    # 实例变量,标注了是一个整型
    num: int


这里会用到 typing 模块,后面会再展开详解

 

假设变量标注了类型,传错了会报错吗?

from typing import List
# int 变量,默认值为 0
num: int = 0
# bool 变量,默认值为 True
bool_var: bool = True
# 字典变量,默认为空
dict_var: Dict = {}
# 列表变量,且列表元素为 int
primes: List[int] = []
num = "123"
bool_var = 123
dict_var = []
primes = ["1", "2"]
print(num, bool_var, dict_var, primes)
# 输出结果
123 123 [] ['1', '2']


它并不会报错,但是会有 warning,是 IDE 的智能语法提示

image.png

所以,这个类型提示更像是一个规范约束,并不是一个语法限制

 

变量类型提示-元组打包

# 正常的元组打包
a = 1, 2, 3
# 加上类型提示的元组打包
t: Tuple[int, ...] = (1, 2, 3)
print(t)
t = 1, 2, 3
print(t)
# py3.8+ 才有的写法
t: Tuple[int, ...] = 1, 2, 3
print(t)
t = 1, 2, 3
print(t)
# 输出结果
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)
(1, 2, 3)


为什么要加 ...

image.png

不加的话,元组打包的时候,会有一个 warning 提示

 

变量类型提示-元组解包


# 正常元组解包
message = (1, 2, 3)
a, b, c = message
print(a, b, c)  # 输出 1 2 3
# 加上类型提示的元组解包
header: str
kind: int
body: Optional[List[str]]
# 不会 warning 的栗子
header, kind, body = ("str", 123, ["1", "2", "3"])
# 会提示 warning 的栗子
header, kind, body = (123, 123, ["1", "2", "3"])


Optional 会在后面讲 typing 的时候详解

 

在类里面使用

class BasicStarship:
    captain: str = 'Picard'               # 实例变量,有默认值
    damage: int                           # 实例变量,没有默认值
    stats: ClassVar[Dict[str, int]] = {}  # 类变量,有默认值


ClassVar

  • 是 typing 模块的一个特殊类
  • 它向静态类型检查器指示不应在类实例上设置此变量

 

函数参数类型提示


不仅提供了函数参数列表的类型提示,也提供了函数返回的类型提示


栗子一

# 参数 name 类型提示 str,而函数返回值类型提示也是 str
def greeting(name: str) -> str:
    return 'Hello ' + name


栗子二

def greeting(name: str, obj: Dict[str, List[int]]) -> None:
    print(name, obj)
相关文章
|
2月前
|
Python IDE 开发工具
Python类型注解(十)
Python类型注解(十)
35 0
Python类型注解(十)
|
2月前
|
Python
【python】—— 内置类型、运算符、表达式、关键字
【python】—— 内置类型、运算符、表达式、关键字
114 1
|
9天前
|
人工智能 开发者 Python
Python 中的断点类型详解
Python 中的断点类型详解
16 2
|
12天前
|
存储 Python
Python变量类型
Python变量类型
8 0
|
19天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
50 0
|
1月前
|
存储 Python
python基础篇: 详解 Python 字典类型内置方法
python基础篇: 详解 Python 字典类型内置方法
28 1
|
2月前
|
安全 Python
Python系列(16)—— string类型转float类型
Python系列(16)—— string类型转float类型
|
2月前
|
Python
Python系列(15)—— int类型转string类型
Python系列(15)—— int类型转string类型
|
2月前
|
存储 Java 程序员
[Python] 变量的类型
[Python] 变量的类型
28 0
|
2月前
|
Java C# 开发者
Python 中的类型注解有哪些
Python 中的类型注解有哪些
16 4