Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


The 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.


Python 3 release date: 3 December 2008

C++11 release date: 12 August 2011


True, but in C++ the problem never existed.


This 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]




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: