名称未在类型注释中定义
Name not defined in type annotation
我目前正在努力创建一个 python 线性代数模块,用于娱乐和练习该语言。我最近尝试向模块添加类型注释,例如:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: Vector) -> Vector:
# More implementation details....
然而,当我尝试导入它时,它吐出 NameError: Name 'Vector' is not defined
。我承认这个问题已经以 here 的形式得到了回答,但它似乎并没有完全为我的情况提供答案。
我想知道的:
- 我在这个文件中按字面定义了 class。为什么说名称未定义?
- 如何定义
Vector
以使其可用于注释(作为 type
)?
您有前向声明;函数(绑定为方法)是在 在 之前创建的, class 是,因此名称 Vector
尚不存在。只有当所有 class 主体都已执行后,才能 Python 创建 class
对象并将名称 Vector
绑定到它。
只需使用带有名称的字符串即可:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: 'Vector') -> 'Vector':
# More implementation details....
这不会影响您 IDE 对声明的看法;一旦加载了整个模块,就会查找字符串,并在当前上下文中解析为有效的 Python 表达式。由于 class Vector
在整个模块加载后就存在,因此字符串 'Vector'
可以正确转换为 class 对象。
另见 specification on forward references:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
[...]
The string literal should contain a valid Python expression [...] and it should evaluate without errors once the module has been fully loaded.
从 Python 3.7 开始,您可以通过在模块。在 Python 3.10 及更高版本 this has become the default behaviour. See PEP 563 -- Postponed Evaluation of Annotations 中。请注意,在 outside 注释中,您可能仍需要使用前向引用语法(字符串文字),例如在类型别名中(就 Python 而言,这是一个常规变量赋值)。
如果您使用的是 Python 3.7 及更高版本。看看Postponed evaluation of annotations
从Python3.7开始允许,只需添加:
from __future__ import annotations
还要注意
It will become the default in Python 3.10.
我目前正在努力创建一个 python 线性代数模块,用于娱乐和练习该语言。我最近尝试向模块添加类型注释,例如:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: Vector) -> Vector:
# More implementation details....
然而,当我尝试导入它时,它吐出 NameError: Name 'Vector' is not defined
。我承认这个问题已经以 here 的形式得到了回答,但它似乎并没有完全为我的情况提供答案。
我想知道的:
- 我在这个文件中按字面定义了 class。为什么说名称未定义?
- 如何定义
Vector
以使其可用于注释(作为type
)?
您有前向声明;函数(绑定为方法)是在 在 之前创建的, class 是,因此名称 Vector
尚不存在。只有当所有 class 主体都已执行后,才能 Python 创建 class
对象并将名称 Vector
绑定到它。
只需使用带有名称的字符串即可:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: 'Vector') -> 'Vector':
# More implementation details....
这不会影响您 IDE 对声明的看法;一旦加载了整个模块,就会查找字符串,并在当前上下文中解析为有效的 Python 表达式。由于 class Vector
在整个模块加载后就存在,因此字符串 'Vector'
可以正确转换为 class 对象。
另见 specification on forward references:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
[...]
The string literal should contain a valid Python expression [...] and it should evaluate without errors once the module has been fully loaded.
从 Python 3.7 开始,您可以通过在模块。在 Python 3.10 及更高版本 this has become the default behaviour. See PEP 563 -- Postponed Evaluation of Annotations 中。请注意,在 outside 注释中,您可能仍需要使用前向引用语法(字符串文字),例如在类型别名中(就 Python 而言,这是一个常规变量赋值)。
如果您使用的是 Python 3.7 及更高版本。看看Postponed evaluation of annotations
从Python3.7开始允许,只需添加:
from __future__ import annotations
还要注意
It will become the default in Python 3.10.