shadowing built-in names (was Re: newbie help ?)

Alex Martelli aleax at aleax.it
Fri May 16 12:44:11 EDT 2003


John Hunter wrote:
   ...
>     >> file=open("codes.txt",'r+') #open the file
>     >> 
>     >> Danger.  'file' is a built-in name; don't use it as a variable
>     >> name.
> 
>     Fredrik> who cares?  Python doesn't, so why should you?
> 
> python also doesn't care if I use 1 space for indentation or obfuscate
> my code, but most human readers would.  Pointing out style conventions
> is fair game.  Even if not everyone adheres to them, I'd guess most
> would advise a newbie not to clobber built-in functions with variable
> names, unless they had specific reason to do so.

Seconded.  The problem with 'clobbering' (actually just 'shadowing')
built-in names, particularly ones of types but more generally ones of
functions too to some extent, is that it leads to 'newbie bugs' when
combined with advice taken from books, from the net, or from more
knowledgeable friends who do not, for any reason, scrutinize most
carefully the whole environment in which the code they advise could
be dropped.

For example, most newbies just love to use builtin type names to name
one specific variable of that type, so for example they happily code:

    list = [1, 2, 4, 8]

Then a few lines later they have a tuple or an iterator and want to
make a list out of it, so they learn from a book or the net or a
friend that all they need to code for the purpose is:

    foo = list(bar)

Alas, this won't work because of that previous 'clobbering' (or
rather 'shadowing'); the poor newbie will get an error message
saying something like

    'list' object is not callable

and will be totally befuddled, sometimes wasting _hours_ trying
to find out WHY the book (&c) recommends he call 'list' ... while
Python insists (they think) that 'list' is not callable.  Let's
not even get into the horrors that await code that tries to e.g.
SUBCLASS list when the built-in name has been shadowed this way;-).

Personally, I'd LOVE it if pychecker could warn about such 'reuse'
of built-in names.  Lacking that, it's quite nice that _posters_
warn other posters about it (and other dubious usages that Python
does support BUT may be error-prone and best avoided).


Alex





More information about the Python-list mailing list