4

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)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Thiago Padilha
  • 4,590
  • 5
  • 44
  • 69

1 Answers1

5

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

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • the Helper class doesn't provide any __init__, so when I construct the Helper instance (helper = Helper()), what will happen? Does Helper() just return a instance with one class attribute? – Alcott Sep 10 '11 at 08:40
  • @Alcott: Yes, the class attribute defaults to `None` and then you change it to an instance attribute by `helper.val = ...`. That's the simplest definition possible for solving this problem, I think. – AndiDog Sep 10 '11 at 22:18