astroid icon indicating copy to clipboard operation
astroid copied to clipboard

Notice `is not None` and similar checks and prevent `BadUnaryOperationMessage`

Open gpshead opened this issue 5 years ago • 1 comments

Steps to reproduce

Run pylint on this file:

"""Demonstrate invalid-unary-operand-type deficiency."""

class Klass:
    """Demonstration."""

    def __init__(self, param=None):
        self._param = param

    def method(self):
        """Returns -param or None."""
        if self._param is not None:
            return -self._param
        return None

Current behavior

example.py:12:19: E1130: bad operand type for unary -: NoneType (invalid-unary-operand-type)

Expected behavior

The invalid-unary-operand-type message should've been supressed because the code block it is coming from is guarded by an is not None check on the attribute in question. astroid has enough information to infer that within this file.

(confirming that... change the default value from the constructor parameter from None to any number and the error disappears)

I suppose you can argue that anything could have been changed to another type at any time by threads or some intervening call that somehow twiddles with this instances state, but the natural intent of code like this is that it hasn't which seems like the ideal thing for a best effort inference engine like astroid to infer.

Versions

pylint 2.5.2 astroid 2.4.1

gpshead avatar May 20 '20 01:05 gpshead

This appears to be a dup of https://github.com/PyCQA/pylint/issues/1472

yilei avatar Sep 14 '22 17:09 yilei