Python checks the enclosing scope if it doesn't find the name in the
current scope, *but* any assignment to a name (e.g. x=...; for x in
...; def x...) marks that name as belonging to the current
function/class scope.

In Python 3 there's the `nonlocal` statement, which does exactly what you want.

In Python 2, you'll need a mutable object. Consider these two options:

- quick hack: use a list:

def main():
    select = [0]

    @window.event
    def on_key_press(symbol, mods):
        if symbol == key.DOWN:
            select[0] += 1

- less of a hack: use an object

class State(object):
    def __init__(self):
        self.select = 0

def main():
    state = State()

    @window.event
    def on_key_press(symbol, mods):
        if symbol == key.DOWN:
            state.select += 1


On Mon, Feb 24, 2014 at 9:22 AM, Henré Botha <[email protected]> wrote:
> More importantly: I don't want the variable select to exist globally. It
> should only be defined within main(). Is there no way to pull this off?
>
>
> On Monday, February 24, 2014 1:42:18 AM UTC+2, swiftcoder wrote:
>>
>> On Sun, Feb 23, 2014 at 4:24 PM, Henré Botha <[email protected]> wrote:
>>>
>>> Hi folks, noobie here. Just started playing with pyglet two nights ago.
>>> Adoring it.
>>>
>>> I'm struggling a little with event handlers, and how/where to use them in
>>> actual code (as opposed to didactic examples).
>>>
>>> The problem I am experiencing is inside a function definition:
>>> initialising a variable before the event handler bit, and then referencing
>>> said variable inside the event handler, causes an UnboundLocalError
>>> exception ("local variable 'select' referenced before assignment").
>>>
>>> Why doesn't this work? C-C-C-CODE EXAMPLE: http://pastebin.com/5VYYp8ay
>>>
>>> Any help appreciated. :)
>>
>>
>> You need to place a 'global settings' statement inside you event handler,
>> to inform Python that you want to assign to the variable in the outer scope,
>> rather than creating a new variable in the inner scope.
>>
>> --
>> Tristam MacDonald
>> Software Development Engineer, Amazon.com
>> http://swiftcoder.wordpress.com/
>
> --
> You received this message because you are subscribed to the Google Groups
> "pyglet-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/pyglet-users.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to