【问题标题】:Scope of return type hints in Python [duplicate]Python中返回类型提示的范围[重复]
【发布时间】:2021-03-29 16:54:33
【问题描述】:

我有两个类,A 和 B,它们都有返回另一个实例的方法。当我不使用类型提示时,这种情况可以正常工作,但是,我无法合并类型提示,如下例所示:

class A:
    def return_B_with_out_annotation(self):
        return B()
    
    def return_B_with_annotation(self) -> B():
        return B()


class B:
    pass

执行上述代码(在 Python 3.8 中)会产生以下错误:

NameError: name 'B' is not defined

所以我的问题是,为什么A.return_B_with_out_annotation 方法是有效代码,而A.return_B_with_annotation 不是?

【问题讨论】:

标签: python scope annotations type-hinting


【解决方案1】:

对于 Python 3.7+

您需要添加以下导入以允许您对尚未定义的类使用类型提示

from __future__ import annotations

PEP 563 is where this behaviour is proposed

【讨论】:

    【解决方案2】:

    发生这种情况是因为 A 类中的方法 return_B_with_annotation 尚未意识到其范围之外的 B 类。 有两种方法可以克服这个问题。 一种是在A之前先创建B类,如下图

    class B:
        pass
    class A:
        def return_B_with_out_annotation(self):
            return B()
        
        def return_B_with_annotation(self) -> B():
            return B()
    

    否则你应该将注解从 future 模块导入到 python 作为

    未来导入注释

    你的代码将是

    from __future__ import annotations
    
    class A:
    def return_B_with_out_annotation(self):
        return B()
    
    def return_B_with_annotation(self) -> B():
        return B()
    
    
    class B:
    pass
    

    ^这个比较推荐。

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2020-11-09
      • 2013-08-22
      • 2021-06-21
      • 2020-11-21
      • 2015-11-23
      相关资源
      最近更新 更多