0

Using a for loop I am trying to append dictionaries to an object attribute:

do = direct_objects[0].point_logs
for direct_object in direct_objects: #Contains two objects
            print ( do is direct_object.point_logs) #Gives true both times
            do = direct_object.point_logs
            print(direct_object.id) #objects are different instances
            dates = generate_dates_interval('2017-01-01', '2017-04-01', 14) #Generates dates with an interval of 14 days for the given period

            for i in range(0, len(dates)-1):

                point_logs, interval_logs, cum_logs = get_point_logs(direct_object, dates[i],
                                                                     dates[i+1]) # gets logs for given period

                if point_logs is not None:
                    direct_object.point_logs.append(point_logs)
                if interval_logs is not None:
                    direct_object.interval_logs.append(interval_logs)
                if cum_logs is not None:
                    direct_object.cum_logs.append(cum_logs)

I want to loop through the dates and append all the logs to an instance of DirectObject's point_logs. However what I get is that, instead of being two seperate lists, the direct_object.point_logs becomes a a big list of all the point logs for both direct objects.

class DirectObject(object):
    def __init__(self, id, created_date, deleted_date, name, type, point_logs = [], interval_logs = [], cum_logs= [],
                 services = None):
        self.id = id
        self.created_date = created_date
        self.deleted_date = deleted_date
        self.name = name
        self.type = type
        self.point_logs = point_logs
        self.interval_logs = interval_logs
        self.cum_logs = cum_logs
        self.services = services

    def __str__(self):
        return str(self.name) + " id: " + str(self.id) + " type: " + str(self.type)
    def __repr__(self):
        return str(self.name) + " id: " + str(self.id) + " type: " + str(self.type)

Why is this happening?

k88
  • 1,858
  • 2
  • 12
  • 33

1 Answers1

1

Since everything is an object in Python, the empty list you use as the default argument is too an object. More importantly, it is the same object! Like writing a = b = [] You have to try other recipes, such as the one here.

What is the pythonic way to avoid default parameters that are empty lists?

Community
  • 1
  • 1
Elan
  • 443
  • 5
  • 14