In my project my Mypy is haunting me over some inheritance, and I can't find a reason why in some cases it does not complain about the error:
note: In class "Cat":
Incompatible types in assignment (expression has type "Dict[str, Any]", base class "Animal" defined the type as "None")
and does not for the Dog
, code example:
class Animal:
attributes = None
def __init__(self):
if attributes is None:
raise NotImplementedExcepton
class Cat(Animal):
attributes = {
'fur': 'black',
'sound': 'meow',
}
class Dog(Animal):
attributes = {
'fur': 'brown',
'sound': 'woof',
}
attributes
can be None
as seen in Animal
, so you define it as Optional
. Then you also define what type of attributes
might be.
from typing import Dict, Optional
class Animal:
attributes: Optional[Dict[str, str]] = None
def __init__(self):
if self.attributes is None:
raise Exception
class Cat(Animal):
attributes = {
'fur': 'black',
'sound': 'meow',
}
This won't raise any mypy errors.