Home > front end >  Python Typing - Return generic protocol as self
Python Typing - Return generic protocol as self

Time:04-04

If I have a base class that takes a generic T bound to typing.Protocol, how do I annotate that this class will be assignable to the passed protocol?

For example:

from typing import TypeVar, Generic, Protocol, Optional

T = TypeVar("T", bound = Protocol)

class Test(Generic[T]):
    something: Optional[str] = None

    def return_protocol(self) -> T:
        ...
        return self.__class__() # typing error, cannot assign self to T

I would like an end API of something like this:

class ProtoThatWrapsTest(Protocol):
    something: str
    ...


class Derived(Test[ProtoThatWrapsTest]):
    ...

t = Test()
t.something # Optional[str]

d = Derived().return_protocol()
d.something # str

CodePudding user response:

It seems that it was as simple as adding type: ignore to return self.__class__().

  • Related