2

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
2
  • 3
    Why not just pass v to the ff() function? Commented Jun 6, 2011 at 18:46
  • @Rich for example there are can be multiple nested functions Commented Jun 6, 2011 at 19:17

2 Answers 2

6

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).
1

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

Perhaps def ff(v=v) would come closer to what the OP wants.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.