-
The goal is, a Python function returns a new class, that is a subclass of some arbitrary base. The returned object should be typed as such. pylance can handle this case, however in mypy I historically have to use the get_dynamic_class_hook, which actually refers to the code in question I'm trying to write without a plugin. Example: import typing
from typing import Any
from typing import Type
class MyBaseClass:
some_attr = 'attribute'
if typing.TYPE_CHECKING:
def __init__(self, **kw: Any):
...
def make_a_base_class() -> Type[MyBaseClass]:
return type("MyClass", (MyBaseClass,), {})
# this works:
# MyBase = MyBaseClass
# this doesn't
MyBase = make_a_base_class()
class MyConcreteClass(MyBase):
pass
mc = MyConcreteClass()
if typing.TYPE_CHECKING:
reveal_type(MyBase) Output in pyright is correct:
mypy won't accept the base (but does know what it is!):
is this a bug in mypy? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 13 replies
-
This should arguably generate an error in pyright/pylance as well. The statement |
Beta Was this translation helpful? Give feedback.
This should arguably generate an error in pyright/pylance as well. The statement
MyBase = make_a_base_class()
looks similar to a type alias declaration, but it's not really a legal type alias because it uses a call expression. Therefore it should be treated as a normal variable assignment. A variable shouldn't be allowed as a base class in a class declaration.