python - 有没有办法在其以前的版本中使用 Python 3.9 类型提示?

标签 python type-hinting static-typing python-3.9

在 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

关于python - 有没有办法在其以前的版本中使用 Python 3.9 类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63939138/

相关文章:

python - 在python中通过ref/ptr发送?

python - 如何绘制带坐标的 png-osm-map

python - 如何内省(introspection) SOAP 数据类型?

python - 在 Python 中手动引发(抛出)异常

python - "TypeError: ' 在函数签名中输入 ' object is not subscriptable"

PHP7 : Methods with a scalar type declaration refuse to type juggle NULL values, 即使在弱/强制模式下

php - 类型提示闭包参数

php - this 在 C++、PHP 和其他语言中的用法

static-typing - 您知道动态类型语言中优雅解决方案的任何示例吗?

c# - C# 和 typescript 之间 JSON 的端到端类型安全