'x' is not defined when using list comprehensions in ipdb

Viewed 492
ipdb> import ast
ipdb> [t.unparse() if isinstance(t, ast.AST) else t for t in tree]
*** NameError: name 'ast' is not defined

I was trying this code, but for some reason it clams that ast is not defined, even after importing. How to circumvent this?

2 Answers

It gets better

See this answer

Instead of doing it with globals, you could just make your ipdb session interactive by typing interact at the start of your session.

Now you can continue just the way you were and everything should work.

Better solution

Pull the module into the global scope

ipdb>  import ast
ipdb>  global ast # <-- This
ipdb>  [t.unparse() if isinstance(t, ast.AST) else t for t in tree]

Previous answer

You could also just create a global variable that refers to AST

ipdb>  import ast
ipdb>  AST=ast.AST
ipdb>  [t.unparse() if isinstance(t, AST) else t for t in tree]

Okay I find out a way, but it's annoying.

First, this happens because list comprehension has it's own scope, so they don't work inside (i)pdb. For more info see this: https://bugs.python.org/msg215625

The solution is to use map + lambda to emulate list comprehension, I could get the same result by

!list(map((lambda t: t if type(t) is str else t.unparse()), tree))

The ! is needed because list is a keyword in pdb

Related