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

frn*_*nhr 16 python-3.x mypy python-typing

我有类似的东西:

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)())
Run Code Online (Sandbox Code Playgroud)

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

该代码似乎工作得很好:

$ python this.py
<__main__.make_a_foobar_class.<locals>.FooBar object at 0x10a422be0>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Mic*_*x2a 14

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

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

无论如何,我建议要么重新设计代码以避免这样做,也许通过使用组合而不是继承或其他方式。

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

例如:

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)())
Run Code Online (Sandbox Code Playgroud)