Paul Berry (stereotype441) wrote,
Paul Berry
stereotype441

Python: assigning to variables in containing scopes

I want to be able to do this in Python:
def call_three_times(f):
    f()
    f()
    f()

def foo():
    call_count = 0
    def bar():
        call_count += 1
    call_three_times(bar)
    assert call_count == 3

if __name__ == '__main__':
    foo()

That doesn't work because "call_count += 1" causes Python to interpret every reference to call_count inside bar() as a local variable inside bar(). So you get an UnboundLocalError.

But I don't want to introduce a new local variable inside bar(). I just want to assign to the local variable in the scope of the containing function foo(). Python doesn't let you do this using the normal assignment syntax. So I need a workaround. Here is the best I've come up with:
def call_three_times(f):
    f()
    f()
    f()

def foo():
    call_count = [0]
    def bar():
        call_count[0] += 1
    call_three_times(bar)
    assert call_count[0] == 3

if __name__ == '__main__':
    foo()

But that seems kind of lame. Is there a canonical way to accomplish this sort of thing in Python?
Subscribe
  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 9 comments