Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm facing a very strange issue on Python 3.6. In the middle of my code, I call import pdb; pdb.set_trace() to debug some code.

And then I'm not able to debug properly, for instance:

(Pdb) abc = 3
(Pdb) [abc for _ in range(2)]
*** NameError: name 'abc' is not defined
(Pdb) [abc, abc]
[3, 3]

It seems like whenever I use list comprehensions, there is an issue of variable not defined. However, if I call the debugger right after I open Python, I do not observe this behavior, everything runs fine.

Any ideas why I'm having this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
746 views
Welcome To Ask or Share your Answers For Others

1 Answer

This happens because list comprehensions are (mostly) evaluated in a nested scope, and nested scopes created in pdb can't access the local variables of the scope being inspected. They can access globals, though, and when you launch pdb immediately after opening Python, you're running it in a global scope, so the abc you create is global.

This also happens with list comprehensions in exec and in class statements. Unfortunately, there isn't really a better workaround than "don't use list comprehensions there".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...