J
Jean-Michel Pichavant
Chris said:So... it's a bad idea for me to use 'i' many times in my code, with
the same name having different meanings in different places? In
languages with infinitely-nesting scopes (one of Python's great lacks,
imho), I've often had three different variables with the same names,
all perfectly valid, and all doing what they should. It's not just
loop indices - I used to have a piece of code in which 'res' was a
MySQL resource being processed in a loop, and I had three nested
loops. Each time I referenced 'res', it used the innermost available
resource, which was precisely what I wanted. If I'd arbitrarily had to
guarantee that all variable names were unique, I would have had
completely unnecessary fiddling around.
Python wouldn't let you do that with three nested 'res'es in one
function, but you can perfectly reasonably have a global and a local.
It makes perfect sense... which is a good reason for keeping it legal.
ChrisA
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
good ideas :
# global
nameThatWillNotBeUsedlocally = 'foo'
def spam():
for qtyIndex, quantity in enumerate([5,6,3,1]):
for fruitIndex, fruit in enumerate(['orange', 'banana']):
print fruitIndex, fruit
print qtyIndex, quantity
While a lot of people still use i,j,k,v to handler values and indexes, I
think it's a bad idea. I'm just stating an opinion from my personnal
python experience. I know some people can successfully use the hard way.
JM