【问题标题】:Variable "foo_class" is not valid as type, but why?变量“foo_class”作为类型无效,但为什么呢?
【发布时间】:2020-01-07 19:31:22
【问题描述】:

我有类似的东西:

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): 行抛出这两个错误(添加为cmets ^)

代码似乎运行良好:

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

我做错了什么?

【问题讨论】:

标签: python-3.x mypy python-typing


【解决方案1】:

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)())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多