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.

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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: __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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.