Q:

How to check if an attribute has default value defined in __init__

How can I check if an attribute of an object has been set by the user or not? Currently, I have a class
class foo:
    def __init__(self):
        self.bar = 'baz'

Later I would like to check if the user set the value of bar or not, i.e. with something like
my_foo = foo()
my_foo.bar = 'mybaz'

so I would like to know if the second line above has been called or not (to throw a warning if it has not). I have two solutions, but I don't like either of them:

Check if my_foo.bar is equal to the default value. But it could be that the user sets my_foo.bar to the same value and then I don't want to throw a warning.
Don't set the default value in __init__, but only when it is used. Then it can be checked with getattr() and set with setattr().

I'm sure there is an elegant pythonic way to do it that I haven't thought of.

A:

Use the @property decorator to construct getters and setters, and the make the setter tell you when a user changes the attribute, example below
class Foo:

    def __init__(self):
        self._x_was_modified = False
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x_was_modified = True
        self._x = value

foo = Foo()
print('x was modified by user: {}'.format(foo._x_was_modified))
foo.x = 42
print('x was modified by user: {}'.format(foo._x_was_modified))

This will output:
x was modified by user: False
x was modified by user: True

