I have an existing class that changes an important type upon a certain method call. It looks something like this:
class RememberLast:
def __init__(self, last):
self._last = last
def set(self, new_last):
self._last = new_last
def get(self):
return self._last
remember = RememberLast(5)
type(remember.get()) # int
remember.set('wow')
type(remember.get()) # str
remember.set(4.5)
type(remember.get()) # float
Ideally the type of remember
would change from RememberLast[int]
to RememberLast[str]
and then to RememberLast[float]
. Is there a way to represent this situation with type hints?
Returning self
with a different type hint in set()
isn't ideal because there are existing callers. For these existing callers that don't use the return value, the type would stay as RememberLast[int]
even though the type was "destroyed" and isn't correct anymore.
The existing class I'm referring to is twisted.internet.defer.Deferred
, which allows chaining callbacks. The type of the last return value becomes the parameter for the next callback. So the type of a Deferred
can be thought of as the type of the last callback added to it.