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:

  1. from typing import Union
  2.  
  3. class Cat:
  4. def sleep(self) -> None: ...
  5. def miaow(self) -> None: ...
  6.  
  7. class Dog:
  8. def sleep(self) -> None: ...
  9. def follow_me(self) -> None: ...
  10.  
  11. def func(animal: Union[Cat, Dog]) -> None:
  12. # OK: 'sleep' is defined for both Cat and Dog
  13. animal.sleep()
  14. # Error: Item "Cat" of "Union[Cat, Dog]" has no attribute "follow_me" [union-attr]
  15. 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.