问题描述
在Python 3.9中,我们可以按照here所述以小写的内置方式使用类型提示(无需从typing
模块导入类型签名):
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello",name)
我非常喜欢这个主意,我想知道是否可以使用这种类型提示,但是在以前的python版本中,例如Python 3.7,我们编写了这样的类型提示:
from typing import List
def greet_all(names: List[str]) -> None:
for name in names:
print("Hello",name)
解决方法
只需从annotations
导入__future__
,您就应该做好了。
from __future__ import annotations
import sys
!$sys.executable -V #this is valid in iPython/Jupyter Notebook
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello",name)
greet_all(['Adam','Eve'])
Python 3.7.6
Hello Adam
Hello Eve