Puzzled by list-appending behavior
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu May 26 23:52:35 EDT 2011
On Fri, 27 May 2011 13:24:24 +1000, Chris Angelico wrote:
> On Fri, May 27, 2011 at 11:59 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> 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.
>
> But even for something that short, why do it? Why not call the parameter
> 'lst' or something? Shadowing with something completely different is
> seldom going to give major advantage, and has the potential to be quite
> confusing.
Because "lst" is not a real word. To native readers of languages derived
from Latin or Germany, such as English, it is quite a strange "word"
because it has no vowel. In addition, it looks like 1st (first).
We use naming conventions like my_list list_ lst alist etc. to avoid
shadowing the built-in list, not because they are good to use in and of
themselves. (E.g. we don't write "my_tree" because there's no "tree" to
shadow.) All of these are ugly to some extent, which is to say, they
cause some small, or not so small, additional cognitive load to the
reader. We don't use the name "list_" because we like trailing
underscores! We do it because it avoids the cost of shadowing a built-in.
But in a small function, there's no real cost to shadowing, so why
bother? Any hypothetical confusion caused is no greater than, and
probably less than, the increased difficulty in reading any of the
alternatives.
Either way, we're talking micro-optimizations in readability here. Don't
get hung up over the choice of a name. If you'd rather never shadow, I'm
fine with that too. I just think "never shadow" is unnecessarily strict.
Sometimes shadowing is harmless, and sometimes it's useful.
If you're writing a tutorial for beginners, shadowing a built-in without
explanation will cause confusion, but for production code, I think it
reasonable to assume the reader knows Python well enough not to stumble
over that choice.
--
Steven
More information about the Python-list
mailing list