3

I am now trying to create a descriptor class for model fields which saves it's modification history.

I can determine the fact when some method is called on field value by just overriding getattr:

def __getattr__(self, attr):
    print(attr)
    return super().__getattr__(attr)

And I can see arguments of overrided methods:

def __add__(self, other):
    print(self, other)
    return super().__add__(other)

The problem is that += operator is just a syntactic sugar for:

foo = foo + other

So I can not handle += as single method call, it triggers __add__ and then __set__. Am I able to determine that value was not totally replaced with new one, but was added/multiplied/divided etc.?

Pavel Shishmarev
  • 1,335
  • 9
  • 24

1 Answers1

1

Use __iadd__

For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
RafalS
  • 5,834
  • 1
  • 20
  • 25