Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__getattr__ going recursive in python

I have the declared a class in following way

class A:
    def __init__(self, list_1, list_2):
        self.list1 = list_1
        self.list2 = list_2

    def __getattr__(self, item):
        if item in self.list1: return "It is in list 1"
        elif item in self.list2: return "It is in list 2"
        else: return "It is in neither list 1 nor list 2"

Here when I am adding __setattr__ self.list1 goes recursive, since __getattr__ get called after every self.list1 and this recursion is unstoppable. Can you please help me out with it. I need to implement like this.

Thanks

like image 487
Paritosh Singh Avatar asked Jun 21 '12 19:06

Paritosh Singh


1 Answers

First of all, this is a totally bizarre usage of __getattr__, but I'll assume that you know that.

Basically, the problem is that __setattr__ is always called every time you do something like self.foo = bar, so if you use that within __setattr__ you'll end up with the recursion that you got. What you need to do is insert the value that you're trying to set directly into __dict__ self.__dict__['foo'] = bar.

If you're using new style classes (i.e. A is a descendant of object), then you could also do super(A, self).__setattr__(item, value) or even just object.__setattr__(self, item, value)

like image 112
Nathan Binkert Avatar answered Sep 23 '22 08:09

Nathan Binkert