I am having some sort of issue with list aliasing or variable assignment in Python 2.7. I will show you a minimal example. There are two different results with and without the assertion, and I don't know why/how the assertion affects this.
Somehow it is overwriting an attribute when I append something to the object_list shown below:
class Object1(object):
def __init__(self):
self.object_list = []
def add_thing(self, thing):
# this next line makes all the difference
assert thing.name not in [thing.name for thing in self.object_list], 'agent id already exists, use another one'
self.object_list.append(thing)
class Thing(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
Here is a minimal example:
With the assertion
mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')
mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)
print mfd.object_list
>> [blah, blah]
Without the assertion
mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')
mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)
print mfd.object_list
>> [blah, blew]
Can someone please explain to me how the assertion above is affecting this? Thank you.
[thing.name for thing in self.object_list]... now hasthing= self.object_list[-1]... instead just do[other.name for other in self.object_list]new_thing not in self