I have the following code:
>>> def f(v=1):
... def ff():
... print v
... v = 2
... ff()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in f
File "<stdin>", line 3, in ff
UnboundLocalError: local variable 'v' referenced before assignment
I do understand why this message occurs (Python variable scope question), but how can I work with v
variable in this case? global v
doesn't work in this case.
asked Jun 6, 2011 at 18:43
-
3Why not just pass v to the ff() function?Rich– Rich2011年06月06日 18:46:32 +00:00Commented Jun 6, 2011 at 18:46
-
@Rich for example there are can be multiple nested functionsrsk– rsk2011年06月06日 19:17:36 +00:00Commented Jun 6, 2011 at 19:17
2 Answers 2
In Python 3.x, you can use nonlocal
:
def f(v=1):
def ff():
nonlocal v
print(v)
v = 2
ff()
In Python 2.x, there is no easy solution. A hack is to make v
a list:
def f(v=None):
if v is None:
v = [1]
def ff():
print v[0]
v[0] = 2
ff()
answered Jun 6, 2011 at 18:44
Sign up to request clarification or add additional context in comments.
1 Comment
Note that the second falls to stackoverflow.com/questions/1132941/… (calling it a second time without providing
v
prints 2).You haven't passed v to the inner function ff. It creates its own scope when you declare it. This should work in python 2.x:
def f(v=1):
def ff(v=1):
print v
v = 2
ff(v)
But the assignment call to v = 2
would not be persistent in other calls to the function.
answered Jun 6, 2011 at 18:47
1 Comment
senderle
Perhaps
def ff(v=v)
would come closer to what the OP wants.lang-py