How to use __setattr__ correctly, avoiding infinite recursion

You must call the parent class __setattr__ method:

class MyTest(object):

    def __init__(self, x):
        self.x = x

    def __setattr__(self, name, value):
        if name=="device":
            print "device test"
        else:
            super(MyTest, self).__setattr__(name, value)
            # in python3+ you can omit the arguments to super:
            #super().__setattr__(name, value)

Regarding the best-practice, since you plan to use this via xml-rpc I think this is probably better done inside the _dispatch method.

A quick and dirty way is to simply do:

class My(object):
    def __init__(self):
        self.device = self

Leave a Comment