I have a list serving as an instance variable in a python class. Direct assignments to this list is fine but appending to the list will change it globally (i.e., across all instances of that class). Here's a simple example:
class foo(object):
def __init__(self, x = []):
if not isinstance(x, list):
raise TypeError('x must be a list')
else:
self.x = x
f1 = foo()
f2 = foo()
f1.x = [1,2]
print 'f1.x', f1.x,' f2.x = ',f2.x
f3 = foo()
f4 = foo()
f3.x.append(2)
print 'f3.x = ',f3.x,' f4.x = ',f4.x
The output is as follows:
f1.x [1, 2] f2.x = []
f3.x = [2] f4.x = [2]
How to avoid global changes in x when appending?