4

Sorry for the terrible title. I had to figure out the terminology and an trying to put all relevant points there.

Consider the following simple interaction in Python:

Python 3.6.9 (default, Jul 21 2019, 14:33:59) 
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python.el: native completion setup loaded
>>> s1 = [ i for i in range(10)]
>>> [i for i in range(len(s1)) if s1[i]%2 == 0]
[0, 2, 4, 6, 8]

The last statement creates (and prints) indexes of the even elements in the original array s1.

But the equivalent does not work in pdb:

(Pdb) !s1 = [ i for i in range(10)]
(Pdb) s1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(Pdb) ![i for i in range(len(s1)) if s1[i]%2 == 0]
*** NameError: name 's1' is not defined

Why is s1 in scope in python interpreter but not in debugger? I am trying to identify elements in the array that meet certain criteria. What is the python way to do this in debugger?

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
  • 2
    Tried your code in the pdb and it works perfectly. What python version do you use? – Oleksandr Hiliazov May 06 '20 at 15:58
  • Can you please explain why are you using `!` to `!s1` in Pdb? – thisshri May 06 '20 at 15:58
  • 1
    This should work without any problem. Which OS and which Python version you are using? – Tarun Lalwani May 06 '20 at 17:31
  • Hmm. My question included copy-paste of my interaction but today I am not able to reproduce. I have already discounted the possibility that this was due to my using `cygwin python` or using it in `emacs` as both of them are now working. Must be some usage error on my part. – Miserable Variable May 08 '20 at 00:02
  • 1
    @thisshri I habitually use `!` in python because any string entered `pdb>` prompt is first executed as a debugger command. For example if you have a variable named `step` then entering the command `step = 5` would not assign to the variable but rather step to the next line of code. Search for `!` at https://docs.python.org/3.8/library/pdb.html – Miserable Variable May 08 '20 at 00:03

1 Answers1

4

Like others have mentioned, your code should work. However, I ran into a similar issue some time ago when I tried to use a variable in a list comprehension like you and I found Antimony's response here very useful:

"In Python 3, you have to use the interact command in pdb before you can access any non-global variables due to a change in the way comprehensions are implemented."

List comprehension scope error from Python debugger

imochoa
  • 736
  • 4
  • 8
  • This is most definitely what happened. I had almost exact same code to start a debugger withing a function and actually the code I executed in the debugger was copied from source. I did not even know of `interact`, thank you. It's a pity I didn't see this before the bounty expired but I'll take care of that. – Miserable Variable May 15 '20 at 02:36