2
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?

smac89
  • 39,374
  • 15
  • 132
  • 179
geckos
  • 5,687
  • 1
  • 41
  • 53
  • try from ast import ast – frab Jan 20 '21 at 00:41
  • Same problem, in fact this is due list generator having it's own scope https://bugs.python.org/msg215625, I find out an *ugly* solution – geckos Jan 20 '21 at 00:45
  • Does this answer your question? [Possible bug in pdb module in Python 3 when using list generators](https://stackoverflow.com/questions/17290314/possible-bug-in-pdb-module-in-python-3-when-using-list-generators) – smac89 Jan 20 '21 at 01:56

2 Answers2

1

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]
smac89
  • 39,374
  • 15
  • 132
  • 179
0

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

geckos
  • 5,687
  • 1
  • 41
  • 53
  • 1
    Another solution is to create a global variable that refers to `ast` and then use that global variable. See my [answer](https://stackoverflow.com/a/65801962/2089675) – smac89 Jan 20 '21 at 01:39