类型注释稍后定义的类(前向参考) [英] Type annotating a class that is defined later (Forward Reference)

查看:16
本文介绍了类型注释稍后定义的类(前向参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于风格原因,我试图在 Foo 类之前保留 myDict 的定义.这将导致 NameError 因为 Foo 尚未定义.

For style reasons I'm trying to keep definition of myDict before class Foo. This will cause a NameError because Foo is not yet defined.

from typing import Dict

myDict: Dict[str, Foo] = {}

class Foo:
    pass

将 myDict 移动到 Foo 下方显然可以解决这个问题,但是有什么办法可以让 myDict 及其注释保持在顶部吗?

Moving myDict below Foo obviously fixes this, but is there any way I can keep myDict and its annotation up top?

推荐答案

可以引用如下:

from typing import Dict

myDict: Dict[str, 'Foo'] = {}

class Foo:
    pass

参见 https://www.python.org/dev/peps/pep-0484/#forward-references 了解更多信息.

See https://www.python.org/dev/peps/pep-0484/#forward-references for more information.

这篇关于类型注释稍后定义的类(前向参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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