0

I'm trying to create a simple model base

class Model:

    _fields = {}

    def __init__(self, **props):
        import pdb; pdb.set_trace()
        for key, value in props.items():
            if key in self._fields:
                setattr(self, key, value)

    def __setattr__(self, name, value):
        if name not in self._fields:
            return
        setattr(self, name, value)

However, when I set a value that is in my _fields list, it ends up in an infinite loop (setattr calling __setattr__). I can't figure out how I can set a value like this.

Rohit
  • 3,018
  • 2
  • 29
  • 58

1 Answers1

0

To paraphrase the doc on __setattr__, if __setattr__ needs to set an attribute you can avoid recursion by calling the base class's __setattr__ method:

object.__setattr__(self, name, value)

# Or ...
super().__setattr__(self, name, value)
luther
  • 5,195
  • 1
  • 14
  • 24
  • Ah, so if this is inherited, I have to create a `__setattr__` in each subclass? I can't just utilize it in the child? – Rohit Aug 27 '19 at 02:56
  • @Rohit: `__setattr__` gets inherited like any other method. I'm not sure I understand your question. The point of this is that your `__setattr__` must call a *different* `__setattr__` in order to not be recursive. – luther Aug 27 '19 at 04:55