以字符串形式给出的 Python 类型提示? [英] Python type hint given as a string?

查看:29
本文介绍了以字符串形式给出的 Python 类型提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这种形式的函数:

I have a function of this form:

def foo(o: "hello") -> dict:
    # pass

我知道-> dict"意味着 foo 返回一个字典.我不明白的是你好"部分.为什么此类型提示以字符串形式给出?什么是你好"?

I understand that the "-> dict" means that foo returns a dictionary. What I don't understand is the "hello" part. Why is this type hint given as a string? What is "hello"?

可能相关 - 这是一个自动生成的文件.

Possibly relevant - this is an autogenerated file.

推荐答案

有时需要在创建对象之前设置类型注释,例如:

type annotations sometimes need to be set before the object has been created, for example:

class Node:
    def next() -> Node:
        pass

这段代码实际上失败了,因为Node被引用为Node.next的注解,而Node类仍在创建中.这与以下失败的原因相同:

This piece of code actually fails, because Node is referenced as an annotation of Node.next while the class Node is still being created. This is the same reason why the following fails:

class T:
    t = T()

为了解决这个问题,您可以使用字符串代替

To get around this, you can use a string instead

class Node:
    def next() -> 'Node':
        pass

所以类型检查器稍后只会评估 Node (a 前向引用).

so the typechecker will only evaluate Node later (a forward reference).

这实际上是决定是python 3.7中的一个设计缺陷您可以使用 from __future__ import annotations 并且第一个示例将起作用.

This was actually decided to be a design flaw so in python 3.7 you can use from __future__ import annotations and the first example will work.

这篇关于以字符串形式给出的 Python 类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆