python 中from __future__ import annotations 作用
时间: 2023-07-30 19:11:51 浏览: 58
在 Python 3.7 及更早的版本中,类型提示需要使用字符串来表示类型。例如:
```python
def greeting(name: str) -> str:
return f"Hello, {name}!"
```
在 Python 3.7 中,可以通过使用 `typing` 模块来使用更加标准化的类型提示。例如:
```python
from typing import List
def double(numbers: List[int]) -> List[int]:
return [n * 2 for n in numbers]
```
然而,在 Python 3.7 中,类型提示还是使用字符串来表示函数返回值的类型。例如:
```python
def greeting(name: str) -> 'str':
return f"Hello, {name}!"
```
在 Python 3.10 中,可以使用 `from __future__ import annotations` 语句来启用 PEP 563 中引入的新语法。这个特性允许在函数声明中使用本地变量的类型注释,并且可以使用 `str` 等字符串来表示函数返回值的类型。例如:
```python
from __future__ import annotations
from typing import List
def double(numbers: List[int]) -> List[int]:
result: List[int] = []
for n in numbers:
result.append(n * 2)
return result
```
注意,使用 `from __future__ import annotations` 语句会启用一些新的语法特性,包括:允许在函数声明中使用本地变量的类型注释,以及允许使用字符串来表示函数返回值的类型。这些特性在 Python 3.10 中是默认开启的,因此这个语句在 Python 3.10 中不再需要使用。