[英]Variable "foo_class" is not valid as type, but why?
I have something similar to this:我有类似的东西:
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)())
Running mypy
throws these two errors (added as comments ^) at line class FooBar(foo_class):
运行
mypy
会在class FooBar(foo_class):
行抛出这两个错误(添加为注释 ^ class FooBar(foo_class):
The code seems to work just fine:代码似乎工作得很好:
$ python this.py
<__main__.make_a_foobar_class.<locals>.FooBar object at 0x10a422be0>
What am I doing wrong?我究竟做错了什么?
Mypy, and the PEP 484 ecosystem in general, does not support creating classes with dynamic base types. Mypy 和一般的 PEP 484 生态系统不支持创建具有动态基类型的类。
This is likely because supporting such a feature is not worth the additional complexity: the type checker would need to implement additional logic/additional passes since it can no longer cleanly determine what exactly the parent type is by just examining the set of variable names that are currently in scope, and can also no longer accurately type check code using the new dynamic class in the general case.这可能是因为支持这样的功能不值得增加额外的复杂性:类型检查器需要实现额外的逻辑/额外的传递,因为它不能再通过检查一组变量名来明确地确定父类型是什么当前在范围内,并且在一般情况下也无法再使用新的动态类准确键入检查代码。
In any case, I would recommend either redesigning your code to avoid doing this, perhaps by using composition over inheritance or something.在任何情况下,我都会建议重新设计您的代码以避免这样做,也许通过使用组合而不是继承或其他方式。
Alternatively, you can suppress the errors mypy is generating by adding a # type: ignore
annotation.或者,您可以通过添加
# type: ignore
注释来抑制 mypy 生成的错误。 This annotation will filter out all errors associated with that particular line once type checking is done.一旦类型检查完成,此注释将过滤掉与该特定行相关的所有错误。
For example:例如:
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.