While I was going through code in twisted framework tutorials about 'writing servers', I came through following lines of code which made me confused.

class Chat(LineReceiver):
    def __init__(self,users):
        self.users = users

class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances
    def buildProtocol(self, addr):
        return Chat(self.users)

Anyone please explain how self.users in ChatFactory class gets updated whenever self.users in Chat class is updated.

1 Answers

2
Jean-Paul Calderone On Best Solutions

In:

f = ChatFactory()
p = f.buildProtocol(some_address)

the expressions f.users and p.users refer to the same dictionary. This is because ChatFactory.buildProtocol passes self.users to the Chat initializer and the Chat initializer saves a reference to it.

Since it is the same dictionary, there is nothing that causes one to get updated when the other is updated because "one" and "the other" are actually the same thing.