3 ms·
But Python 2.7 has this problem: def f(): x = 0 def add(amount): x += amount # UnboundLocalError: local variable 'x' reference
by amelius 10y ago
But Python 2.7 has this problem:
def f():
x = 0
def add(amount):
x += amount # UnboundLocalError: local variable 'x' referenced before assignment
add(10)
add(20)
add(30)
return x
print f()
In C++, this problem doesn't exist.
- dmix 10y agoThe question is the cost of supporting it (assuming this is a problem needing fixing) as it has far reaching implications in all of the added complexity to all the abstractions layered on top of it. I'm not making a good/bad argument that one is better than the other. The two languages have widely different usecases and rationale in the language design. But I'm not convinced C++ is (or can become) very Pythonic given the complexity it must support at all the basic levels.
- deleted 10y ago[deleted]
- js2 10y agoThis is fixed in Python 3 with the nonlocal keyword. In Python 2, the idiomatic work-around is to have x be list of one item: def f(): x = [0] def add(amt): x[0] += amt add(10) return x[0]
- Veedrac 10y agoPython 3 release date: 3 December 2008 C++11 release date: 12 August 2011
- amelius 10y agoTrue, but in C++ the problem never existed.