Overriding a global
Jean-Michel Pichavant
jeanmichel at sequans.com
Wed Dec 14 08:35:14 EST 2011
Steven D'Aprano wrote:
> 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.
>
>
The next time I'll illustrate meaningful names, I'll write a 3000 lines
function, just to be sure no one states that my point does'nt apply to a
function named spam which only counts from 1 to 3.
And don't answer that the spam function above does not count from 1 to
3, I know it doesn't.
For anyone interested in the actual topic, a good reading is
http://tottinge.blogsome.com/meaningfulnames/#Mult_Meanings
JM
More information about the Python-list
mailing list