Overriding statically typed methods
When overriding a statically typed method, mypy checks that theoverride has a compatible signature:
- class Base:
- def f(self, x: int) -> None:
- ...
- class Derived1(Base):
- def f(self, x: str) -> None: # Error: type of 'x' incompatible
- ...
- class Derived2(Base):
- def f(self, x: int, y: int) -> None: # Error: too many arguments
- ...
- class Derived3(Base):
- def f(self, x: int) -> None: # OK
- ...
- class Derived4(Base):
- def f(self, x: float) -> None: # OK: mypy treats int as a subtype of float
- ...
- class Derived5(Base):
- def f(self, x: int, y: int = 0) -> None: # OK: accepts more than the base
- ... # class method
Note
You can also vary return types covariantly in overriding. Forexample, you could override the return type Iterable[int]
with asubtype such as List[int]
. Similarly, you can vary argument typescontravariantly – subclasses can have more general argument types.
You can also override a statically typed method with a dynamicallytyped one. This allows dynamically typed code to override methodsdefined in library classes without worrying about their typesignatures.
As always, relying on dynamically typed code can be unsafe. There is noruntime enforcement that the method override returns a value that iscompatible with the original return type, since annotations have noeffect at runtime:
- class Base:
- def inc(self, x: int) -> int:
- return x + 1
- class Derived(Base):
- def inc(self, x): # Override, dynamically typed
- return 'hello' # Incompatible with 'Base', but no mypy error