Overriding a global
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Dec 14 07:53:22 EST 2011
On Wed, 14 Dec 2011 13:05:19 +0100, Jean-Michel Pichavant wrote:
> Bad ideas :
>
> i = 5
>
> def spam():
> for i,v in enumerate([1,2,3,4]):
> for i,v in enumerate(['a','b', 'c']):
> print i, v
> print i,v # bad surprise
The bad surprise happens because you are using the same name twice in
*one* namespace, the local scope. This example has nothing to do with
local/global name clashes: the existence of global i is irrelevant.
Python's scoping rules work correctly, and global i is not affected by
the local i.
Programming languages use multiple namespaces so that you don't need to
make your variable names globally unique. There are languages that don't
distinguish between local and global. Python is not one of them. The
programmer should feel free to use local names without worrying too much
if they accidentally use a global name.
Having said that, re-using names isn't *entirely* risk free, because if
you use a global name locally, and then try to *also* access the global
name, you will fail. This is called shadowing, and the problem with
shadowing is when you do it by accident. (Newbies are particularly prone
to this, especially when they call variables "str", "list", etc.) But it
is the "by accident" part that is dangerous: there is nothing wrong with
shadowing globals or builtins when you do it by design.
> good ideas :
>
> # global
> nameThatWillNotBeUsedlocally = 'foo'
Oh please. Names can be too long as well as too short.
> def spam():
> for qtyIndex, quantity in enumerate([5,6,3,1]):
> for fruitIndex, fruit in enumerate(['orange', 'banana']):
> print fruitIndex, fruit
> print qtyIndex, quantity
More sensible naming conventions are to be encouraged, but verbose names
just for the sake of verbosity is not. spam() is a five line function; if
the programmer can't keep track of the meaning of loop variables i and j
over five lines, perhaps they should consider a change of career and get
a job more suited to their intellectual prowess. I hear McDonalds is
hiring.
If spam() were larger and more complex, then more expressive names would
be valuable. But in the simple example you give, it just adds noise.
--
Steven
More information about the Python-list
mailing list