Search code examples
pythonclassdefault-valuekeyword-argument

How to prevent reassignment of variable to object of same class from keeping previous data?


When reassigning box with a new instance of Box, instead of self.things being assigned an empty dictionary, it contains the same data from the previous instance.

I'm using python 3.7.3

import random

class Box:
    def __init__(self, things = {}):
        self.things = things

    def __str__(self):
        return str(self.things)

    def put_thing_in_location(self, thing, location):
        self.things[location] = thing


for i in range(2):
    box = Box()
    print(box)
    box.put_thing_in_location(
        random.randrange(10000), 
        random.randrange(10000)
    )

Output:

$ python bugTest.py

{}

{652: 8968}

I expect that things of the new instance of Box be an empty dictionary if no arguments are passed to it. Instead it keeps things from the previous instance of Box.


Solution

  • The issue is that you are assigning the exact same dictionary as the default to your instances, thus sharing it across all instances. Change your constructor to

    def __init__(self, things=None):
        self.things = {} if things is None else things
    

    This ensures that each instance takes a fresh dictionary as the default if nothing is given.