Pygtk: free variable referenced before assignment in the scope

A very strange mistake that I don’t even see. Inside the updater function, I have a built-in helper function for ... w / something help:

def attach_row(ws,r1,r2): es = [] for i,w in enumerate(ws): eb = gtk.EventBox() a = gtk.Alignment(xalign=0.0,yalign=0.5) a.add(w) eb.add(a) eb.set_style(self.rowStyle.copy()) es.append(eb) self.table.attach(eb, i, i+1, r1, r2, xoptions=gtk.EXPAND|gtk.FILL, yoptions=gtk.SHRINK) def ene(_,ev): for eb in es: eb.set_state(gtk.STATE_PRELIGHT) def lne(_,ev): for eb in es: eb.set_state(gtk.STATE_NORMAL) for eb in es: eb.connect('enter-notify-event', ene) eb.connect('leave-notify-event', lne) 

This works for a while, but if the update () function works too much, I end up with:

  for eb in es: NameError: free variable 'es' referenced before assignment in enclosing scope 

What causes this? es is definitely assigned before these functions are called. Is that not so? Is there some bizarre thing when, for some reason, ene () for a previously created string is called while a new one is being created and the closed one over es overwritten?

+6
closures python programming-languages semantics gtk
source share
2 answers

Quite mysteriously - it seems that the closure disappears from under the internal functions. I wonder if this is due to the way pygtk performs such callback functions (I am not familiar with its internal components). To try to figure this out - what happens if you also add ene and lne to the global list at the end of attach_row , just to make sure that they are somewhere "normal" so that closing them survives - does the problem persist in this case?

If this is the case, then I should recognize this problem as MYSTERIOUS mysterious and agree with the previous answer, suggesting as a workaround the use of calling calls that more clearly define their state (I would suggest two related methods one instance of the class, since they share their state, but two instances of the same class with __call__ get the state for installation, and the list of event boxes in its __init__ also reasonable - the presence of two separate IMHO classes is a little exaggeration ;-).

+4
source share

You do not have enough points to leave this as a comment (just registered) ...

  • No 'es' globally or in a higher area?
  • is attach_row also not a nested function?
  • Does a NameError exception point to a loop string in ene or lne functions?

One possible, but workaround, is to create ene and lne classes, which are created and can be called as functions using the __call __ () method.

0
source share

All Articles