-1

When running threads using the threading and Queue libraries, I am creating an object in the threads run() function. Let's say that the class initiates like so:

class Test():
    def __init__(self, dictionary={}):
        self.dict = dictionary

When I try to access the dictionary in different threads, it seems like Python is only creating one instance of the dictionary. Here is the Thread class. I started two of these:

class ThreadTest(threading.Thread):
    def run(self):
        while True:
            // interact with Queue items
            obj = Test()
            print "%s - %s" % (self.name, id(obj.dict))
            queue.task_done()

And the output:

Thread-1 - 19219616
Thread-2 - 19219616

This is really confusing because the Test class is created twice, but it is sharing the same dictionary.

Is there a way to create a new instance of dictionary in this case?

timp
  • 13
  • 3
  • 1
    This has been answered time and again, and yes, you can overcome it by not using a mutable default argument. – g.d.d.c Feb 28 '13 at 18:40
  • Okay. I didn't realize the issue was caused by the default argument. Thanks! – timp Feb 28 '13 at 18:45

1 Answers1

2

Default arguments are only evaluated once, when the def line is encountered. Therefore, your default argument dictionary={} is shared between all instances.

Use dictionary=None instead, and

if dictionary is None:
    self.dict = {}
else:
    self.dict = dictionary

to create a new instance each time.

nneonneo
  • 171,345
  • 36
  • 312
  • 383