This is a weird situation I've been scratching my head about for an hour or so. I can't explain this error, can you? If v1
is None, the if v1 is not None:
block doesn't get run, but v2 is already defined in the method definition, with default of None. Why is it when I pass v1 with a value, it works, but when using the default None, it makes the v2 unbound? If I change it so that the if v1 is not None:
block is outside the method()
it works, but not if it is inside. I don't understand this behavior. Thanks for any clarification you can give me.
>>> def test(v1=None, v2=None):
... def method():
... if v1 is not None:
... v2 = 1
... print v1
... print v2
... method()
...
>>> test()
None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in test
File "<stdin>", line 6, in method
UnboundLocalError: local variable 'v2' referenced before assignment
>>> test('test1', 'test2')
test1
1
>>>
>>> def test(v1=None, v2=None):
... if v1 is not None:
... v2 = 1
... def method():
... print v1
... print v2
... method()
...
>>> test()
>>> def test(v1=None, v2=None):
... if v1 is not None:
... v2 = 1
... def method():
... print v1
... print v2
... method()
...
>>> test()
None
None
>>> test('test1', 'test2')
test1
1
>>>