繁体   English   中英

变量“foo_class”作为类型无效,但为什么呢?

[英]Variable "foo_class" is not valid as type, but why?

我有类似的东西:

from typing import Type


class Foo:
    pass


def make_a_foobar_class(foo_class: Type[Foo]) -> Type[Foo]:

    class FooBar(foo_class):
        # this.py:10: error: Variable "foo_class" is not valid as a type
        # this.py:10: error: Invalid base class "foo_class"
        pass

    return FooBar


print(make_a_foobar_class(Foo)())

运行mypy会在class FooBar(foo_class):行抛出这两个错误(添加为注释 ^ class FooBar(foo_class):

代码似乎工作得很好:

$ python this.py
<__main__.make_a_foobar_class.<locals>.FooBar object at 0x10a422be0>

我究竟做错了什么?

Mypy 和一般的 PEP 484 生态系统不支持创建具有动态基类型的类。

这可能是因为支持这样的功能不值得增加额外的复杂性:类型检查器需要实现额外的逻辑/额外的传递,因为它不能再通过检查一组变量名来明确地确定父类型是什么当前在范围内,并且在一般情况下也无法再使用新的动态类准确键入检查代码。

在任何情况下,我都会建议重新设计您的代码以避免这样做,也许通过使用组合而不是继承或其他方式。

或者,您可以通过添加# type: ignore注释来抑制 mypy 生成的错误。 一旦类型检查完成,此注释将过滤掉与该特定行相关的所有错误。

例如:

from typing import Type

class Foo:
    pass

def make_a_foobar_class(foo_class: Type[Foo]) -> Type[Foo]:

    class FooBar(foo_class):  # type: ignore
        pass

    return FooBar

print(make_a_foobar_class(Foo)())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM