Python: Is there any issue with using __getattribute__ within a class?

161 Views Asked by At

I have created a class for managing subscriptions to a messaging service. The class instantiates three separate clients for reasons related to the configuration for each subscription, also three per instance of the class. To reduce the instantiation of the three clients to one for loop, I've used __getattribute__ and __setattr__. I've read other threads about these methods, and I'm not sure if using them as I have could lead to issues. Here is a very simplified example:

class BaseClient(object):

    def __init__(self, name):
        self.name = name
        
    def connect(self):
        return 'client logged on'
        
    def do_other_things(self):
        return 'other things done'
        
    

class MsgServiceListener(object):
    
    def __init__(self):
        
        self.client1 = None
        self.client2 = None
        self.client3 = None
        self.clientNames = ['client1', 'client2', 'client3']
        
    def createAndSubscribe(self):
        for client in self.clientNames:
            if not self.__getattribute__(client):
                self.__setattr__(client, BaseClient(client))
                self.__getattribute__(client).connect()
                self.__getattribute__(client).do_other_things()

Is there anything wrong with the way I've harnessed the underscore methods?

1

There are 1 best solutions below

0
AKX On BEST ANSWER

Instead of using the dunder methods __setattr__/__getattr__ (or __getattribute__), you should use getattr(self, client) and setattr(self, client, value)...

but better yet, you should just use a dict if you need to map names to objects.

class MsgServiceListener:
    def __init__(self):
        self.clients = {}
        self.clientNames = ["client1", "client2", "client3"]

    def createAndSubscribe(self):
        for client in self.clientNames:
            self.clients[client] = c = BaseClient(client)
            c.connect()
            c.do_other_things()