Long integers: to L or not to L?
Dimitris Garanatsios
dg96057 at teledomenet.gr
Wed Mar 12 07:28:13 EST 2003
Dimitris Garanatsios wrote:
> ...but if you ever call function h() you might get:
>
> Traceback (most recent call last):
> File "script1.py", line 14, in ?
> h()
> File "script1.py", line 11, in h
> i = h1()
> File "script1.py", line 4, in h1
> i = i + 1
> UnboundLocalError: local variable 'i' referenced before assignment
>
> This is because nested scopes in python is a new addition which is not
> supported in my version (2.2.1) unless a "from __future__ import ..." is
> used. So in this case the "i = 0" statement is not seen inside h1().
> Again, you may consult python's documentation for more details about new
> feature additions...
A correction on my remark: I saw that nested scopes was part of python
2.2.1 (sorry about my mistake...). So the error gets raised when you try
to assign a new value to variable i (an immutuable object: integer) in a
scope that it does not exist (although it can be "seen" in that scope).
So if you change h1 to
def h1():
j = i + 1
print 1, j
if j == 5:
return j
else:
j = h1()
return j
You won't get the above UnboundLocalError (assuming nested scopes are
supported in your version of python) but instead a
RuntimeError: maximum recursion depth exceeded
because j will never reach value 5 :-)
If you want to use nested scopes to change the value of an object that
is defined in an outter scope, use muttuable objects:
def h():
i = [0]
def h1():
i[0] = i[0] + 1
print 1, i[0]
if i[0] == 5:
return i[0]
else:
i[0] = h1()
return i[0] # this will never get executed
i[0] = h1()
print 2, i[0]
This might not be pretty, but it will happily run as expected :-)
Again, sorry for my mistake
Dimitris
More information about the Python-list
mailing list