Reputation: 1
This is my code:
from typing import Type, TypeVar
T = TypeVar("T")
class NewMethodsMixin:
def new_method(self) -> str:
"""This is a new method added by a mixin."""
print("added by mixin")
def class_decorator(cls: Type[T]):
class Decorated(NewMethodsMixin, cls):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
cls.__init__(self, *args, **kwargs)
return Decorated
@class_decorator
class MyClass:
def old_method(self) -> str:
print("original method")
my_instance = MyClass()
my_instance.old_method() # 'original method'
my_instance.new_method() # 'added by mixin'
This is how it looks in the IDE:
I wish to get type hints for old_method
.
And if I use another approch:
...
def class_decorator(cls: Type[T]) -> Type[T]:
...
This is how it looks in the IDE:
Now I get the type hint for old_method, but lose the type hint for new_method.
If I use the Union:
...
def class_decorator(cls: Type[T]) -> Type[T] | Type[NewMethodsMixin]:
...
This is how it looks in the IDE:
Apparently, pylance or other type hints can handle the decorated class correctly, but if I inherit the new class, this will cause a failure.
For some reasons I prefer to use decorators instead of using class inheritance as my users may not be able to handle the issue of multiple inheritance. Is there any solution here?
Upvotes: 0
Views: 45