Check that attribute exists in each union item [union-attr]
If you access the attribute of a value with a union type, mypy checksthat the attribute is defined for every type in thatunion. Otherwise the operation can fail at runtime. This also appliesto optional types.
Example:
- from typing import Union
- class Cat:
- def sleep(self) -> None: ...
- def miaow(self) -> None: ...
- class Dog:
- def sleep(self) -> None: ...
- def follow_me(self) -> None: ...
- def func(animal: Union[Cat, Dog]) -> None:
- # OK: 'sleep' is defined for both Cat and Dog
- animal.sleep()
- # Error: Item "Cat" of "Union[Cat, Dog]" has no attribute "follow_me" [union-attr]
- animal.follow_me()
You can often work around these errors by using assert isinstance(obj, ClassName)
or assert obj is not None
to tell mypy that you know that the type is more specificthan what mypy thinks.