How do I access outer functions variables inside a closure(python 2.6)?

Question:

From wikipedia

I need to access outer functions variables in a similar manner as using the ‘nonlocal’ keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword)

Asked By: Thiago Padilha

||

Answers:

I always use helper objects in that case:

def outerFunction():
    class Helper:
        val = None
    helper = Helper()

    def innerFunction():
        helper.val = "some value"

This also comes in handy when you start a new thread that should write a value to the outer function scope. In that case, helper would be passed as an argument to innerFunction (the thread’s function).

Answered By: AndiDog