0

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?

user3076813
  • 499
  • 2
  • 6
  • 13
  • 1
    Side-note: Typically, you wouldn't type check, you'd just do `self.x = list(x)` to convert any iterable to a `list`, with the `list` constructor implicitly raising an exception for non-iterables, instead of insisting on one, and only one, specific type. This way, users who have a `tuple` can pass it in without converting to `list` explicitly, `list` arguments are shallow copied so mutations in the caller don't affect the instance and vice-versa (which would accidentally solve your problem), etc. – ShadowRanger Oct 14 '16 at 16:42
  • @ShadowRanger very good advice – jamylak Oct 15 '16 at 03:24

0 Answers0