method returns object reference

Tim jtim.arnold at gmail.com
Tue Jun 23 14:32:40 EDT 2015


I spent a while finding this problem which looks something like the old "mutable default argument" problem. http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments

I'm not crystal clear on the details, but once I found it, the fix was easy.
I'm posting here just because I thought it was interesting.

The situation is that I have a Worker() which has a Client(). 
The worker queries the client; client returns its self.response
worker manipulates that response. Now client's response has same changes.

The code below prints the following two lines, showing how the 'newkey' is now inside the Client response, even though it was set in the worker.  This must be bad practice!  In my real code, the response is no longer an instance variable, which fixed the problem. It never had any business being bound to the client anyway.

output:
[('text', 'first thing')]
[('text', 'second thing'), ('newkey', 'my new value')]
 

class Client(object):
    def __init__(self):
        self.response = dict()

    def query(self, text):
        self.response['text'] = text
        print self.response.items()
        return self.response


class Worker(object):
    def __init__(self):
        self.client = Client()

    def work(self, expression):
        data = self.client.query(expression)
        data['newkey'] = 'my new value'


if __name__ == '__main__':
    t = Worker()
    t.work('first thing')
    t.work('second thing')



More information about the Python-list mailing list