How to make a protocol inherits base model functions

Viewed 20

I'm writing a library to extend some abilities of Django Models.

Everything works just fine, the problem is the model needs to be decorated with a specific decorator that I created and for mypy it is a completely different class now.

So I've tried to use Protocols to inherit the decorated model's functions, like so...

M = TypeVar('M', bound=models.Model, covariant=True)

class WatchedModel(Protocol[M]):
    @classmethod
    def watched_operation(
        cls, operation: str, target: TargetType, *args: Any, **kwargs: Any
    ) -> Any:
        ...

T = TypeVar('T', bound='models.Model')

def watched(watcher, watched_managers) -> Callable[[Type[T]], Type['WatchedModel[T]']]:
    def decorator(cls: Type[T]) -> Type['WatchedModel[T]']:
       ...
       # implementation doesn't matter

    return decorator

@watched(...)
class CreateModel(models.Model):
    def test_func(self):
        pass

Here you can see that an instance of CreateModel is in fact a WatchedModel of CreateModel on mypy.

This image shows on vscode that an instance of the decorated model is a generic protocol of that model

But I can't have predictions to Django models.Model functions nor the test_func that I declared.

This images shows on vscode that mypy can't infer Django nor explicitly declared model functions

0 Answers
Related