mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Add note for union types with missing attribute

Open Prabhat-Thapa45 opened this issue 7 months ago • 5 comments

This pull request fixes an issue #17036

If some attribute is not defined for a single union item (often None), this helps new users to narrow down by providing hint. For example, the following code:

class A:
    def foo(self) -> int: pass

def f(x: Union[A, None]) -> int:
    return x.foo()

previously (on the master branch) generated this error message:

main.py:8: error: Item "B" of "A | B" has no attribute "x" [union-attr]

With this PR, the message remains, but we add a suggestion for how to fix the error:

main.py:8: error: Item "B" of "A | B" has no attribute "x"  [union-attr]
main.py:8: note: You can use 'if hasattr( a, 'x'):' to guard against missing attribute error

Prabhat-Thapa45 avatar Jul 24 '24 07:07 Prabhat-Thapa45