Puzzled by list-appending behavior
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 26 21:59:32 EDT 2011
On Thu, 26 May 2011 11:27:35 -0700, John Ladasky wrote:
> On May 25, 9:46 pm, Uncle Ben <bgr... at nycap.rr.com> wrote:
>
>> list = [1,2,3]
>
> Somewhat unrelated, but... is it a good idea to name your list "list"?
> Isn't that the name of Python's built-in list constructor method?
>
> Shadowing a built-in has contributed to more than one subtle bug in my
> code, and I've learned to avoid it.
Agreed. However, there are good reasons for sometimes shadowing built-
ins, and namespaces make it safe to do so if you are sufficiently careful.
E.g. I have a module stats.sum() which shadows the built-in, but only in
that module, which is exactly the behaviour I want.
(If you do "from stats import sum", then you're responsible for whatever
happens next.)
Or you might isolate the shadow to a function small enough that you can
be sure that it won't cause any problems, e.g.:
def get(list, object):
"""Append object to a copy of list and return it."""
return list + [object]
For one or two line functions, I think that's perfectly reasonable.
Anything more than that, I'd be getting nervous.
--
Steven
More information about the Python-list
mailing list