python - PDB: Variable can be printed but is undefined -


it looks strange. variable name classes printed undefined when trying execute filter(...) contruction.

here code:

def start(self, tag, attrib):     classes = attrib[self._class_attr] if self._class_attr in attrib else none      if tag == self._tag_p:         p = self._doc.add_paragraph('')          self._cur_p = p          if classes not none:             alignments = [self._left_align, self._center_align, self._right_align]             import pdb; pdb.set_trace()             alignments = filter(lambda x: partial(x.is_in, classes), alignments)             if len(alignments) > 0:                 p.alignment = alignments[0].get()              assert len(alignments) < 2 

pdb stops on it's break. when try execute filter():

(pdb) print filter(lambda x: partial(x.is_in, classes), alignments) *** nameerror: global name 'classes' not defined 

but:

(pdb) print classes center title (pdb) classes u'center title' 

why filter(...) instruction not executed normally?

let's reproduce in short code:

from functools import partial  def f():     classes = 'my_classes'      def my_bool(obj, _):         return true      if classes not none:         import pdb; pdb.set_trace() # point         alignments = filter(lambda x: my_bool(x, classes), ['1', '2', '3'])         import pdb; pdb.set_trace() # point b         pass  f()  ...  (pdb) filter(lambda x: my_bool(x, classes), ['1', '2', '3']) *** nameerror: global name 'my_bool' not defined 

however, command c (continue) of pdb in point a not generate exception.

pdb eval loop. eval loop takes write prompt line line , eval(...)s it. means doesn't bind closure-scoped variables in defined functions (lambdas). eval (which function) has own scope , doesn't participate in closure evaluating in.

you can see equivalent problem example code:

def f():     x = 1     return eval('lambda: x')  >>> f()() traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "<string>", line 1, in <lambda> nameerror: name 'x' not defined 

an (unfortunate) workaround define lambdas up-front , use them in pdb expression.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -