'How can I inherit from dynamically created classes whilst maintaining type safety in Python?
The situation
I have a function that I'm using to dynamically create classes, some of which I inherit from.
def createType(extends: type[T]) -> type[T]:
def constructor(self, s: str) -> None:
self.s = s
def stringify(self) -> str:
return self.s
def thing(self) -> None:
print("Hello")
return type( # type: ignore
f"MyType{extends.__name__}",
(extends,),
{
'__init__': constructor,
'__str__': stringify,
'thing': thing,
}
)
TypeA = createType(object)
class TypeB(TypeA):
...
The problem
When I create the derived class, I get an error in mypy.
class TypeB(TypeA):
# ^^^^^ Invalid base class "TypeA"
As well as this, I can't get intellisense predictions on instances of TypeA or TypeB.
b = TypeB()
b.thing() # Not suggested
How can I cleanly fix the mypy errors and get intellisense predictions for my code?
What I've tried
1.
I've tried using typevars for the return values of the createType function. This doesn't solve either issue
2.
I've tried creating a mock interface type, then using an if TYPE_CHECKING check to redefine it.
class MyInterface:
def __init__(self, s: str) -> None:
...
def thing(self) -> None:
...
if not TYPE_CHECKING:
TypeA = createType(Thing)
else:
TypeA = MyInterface
While this allows me to get type hints for the added methods, it doesn't work for the original type, and it means that I'm adding a bunch of extra duplicate code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
