[Tutor] Baffling problem with a list of objects sharing a property

Alan Gauld alan.gauld at yahoo.co.uk
Wed May 25 12:26:10 EDT 2016


On 25/05/16 17:05, Alex Hall wrote:

> Python for a while so eventually unsubscribed.

Welcome back Alex :-)

> Now I'm using Python for work, and have run into a problem that has me
> baffled. It's as though a bunch of class instances in a list are sharing a
> single property. 

They are. You've stiumbled on one of those Python peculiarities of
implementation that can be useful and annoying in equal measure.

> class Test(object):
>  def __init__(self, name, paths=[]):
>   self.name = name
>   self.paths = paths

When you give a function/method a default value that same object is used
for *every* invocation of the method where the default applies.
So that list you create is shared and if any instance adds anything
to it, it will appear in every other instance too! So unless you
want that behaviour its usually better to make default values
immutable or None, then in the code assign the actual value,
like:

def foo(v = None):
    if not v: v = []  # or whatever mutable value you need.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list