Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

all variables are undefined in python debugger

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

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

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...