Let's say I have these classes:
class GenericCopyable:
def copy(self) -> GenericCopyable:
... # whatever is required to copy this
class CopyableFoo(GenericCopyable):
... # uses the parent implementation of "copy"
def bar(self): …
def some_code(victim: CopyableFoo):
v = victim.copy()
v.bar() ### I know that this works because "v" is a CopyableFoo, but mypy doesn't
The problem is that I need the return type of CopyableFoo.copy()
to be CopyableFoo
, not GenericCopyable
.
Is that possible?
Edited: The above is sample code to illustrate the problem. Modifying some_code
or CopyableFoo
in some way is certainly possible in this example; in my "real" program that'd be substantially more difficult.
You could do this.
from typing import TypeVar
# We define T as a TypeVar bound to the base class GenericCopyable
T = TypeVar('T', bound='GenericCopyable')
class GenericCopyable:
# we return the type T of the type of self
# Basically returning an instance of the calling
# type's class
def copy(self: T) -> T:
return type(self)()
class CopyableFoo(GenericCopyable):
pass
foo = CopyableFoo()
bar = foo.copy()
print(bar)
This looks a little clumsy because typically we don't need to annotate self
, since it's implicitly a type of the class it's bound to. However, mypy seems to be ok with it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments