user3920334
user3920334

Reputation: 33

Using Property Setter In __init__

How do I use a Property setter in __init__ without pylint complaining that the attribute has been defined outside __init__?

For example, the following code only produces one exception which is caught in the try clause at the bottom.

class CircleNotUsingSetterInInit(object):

    def __init__(self, radius):
        # Notice underscore in 'self.radius
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        self._radius = radius


class CircleUsingSetterInInit(object):

    def __init__(self, radius):
        # Notice lack of underscore in 'self.radius'
        self.radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        # From pylint:
        # Attribute '_radius' defined outside __init__ (attribute-defined-outside-init)
        self._radius = radius


CircleNotUsingSetterInInit(5)
CircleNotUsingSetterInInit(-1)
CircleUsingSetterInInit(5)
try:
    CircleUsingSetterInInit(-1)
except ValueError:
    print("caught exception")

I'm using Python 2.7.10.

Upvotes: 3

Views: 2243

Answers (1)

WorldSEnder
WorldSEnder

Reputation: 5054

The warning is completely safe to ignore in this case. Pylint just doesn't "see" that, it's rather complex to notice without doing syntax parsing.

You can add a comment for pylint to disable this warning locally like this:

class CircleUsingSetterInInit(object):

    # ....

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        # pylint: disable=W0201
        self._radius = radius

W0201 is the code for attribute-defined-outside-init, which is the warning you receive according to the docs. You should always add such disable comments as close to the source as possible, so that pylint works normally for the rest of the file.

Upvotes: 5

Related Questions