1

I'm trying to debug a code snippet includes list comprehension inside loop.

list_a = ['a', 'b', 'c']
list_b = ['a', 'b']
for x in list_a:
    print([i for i in list_b if i == x])

The code run okay when I run the entire script. However when I located a breakpoint before the for loop and try to run the for loop interactively I got the following error:

Traceback (most recent call last): File "/root/pycharm/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "", line 2, in File "", line 2, in NameError: name 'x' is not defined

I'm using pycharm for debugging.

itamar kanter
  • 1,170
  • 3
  • 10
  • 25
  • what ide are you using ? I've been using Pycharm and didn't get your error – kederrac Aug 01 '19 at 09:17
  • Pycharm too, I get the error only when I directly run the for loop (i.e copy paste it in debug mode to the console prompt) – itamar kanter Aug 01 '19 at 10:25
  • I think it's similar to https://stackoverflow.com/questions/17290314/possible-bug-in-pdb-module-in-python-3-when-using-list-generators or https://github.com/inducer/pudb/issues/103 – itamar kanter Aug 04 '19 at 08:11

2 Answers2

0

best way to debug a list comprehension is to use a simple for loop :

from:

[i for i in list_b if i == x]

use:

for x in list_a:
    costum_list = []
    for i in list_b:
        if i == x:
            costum_list.append(i)
    print(costum_list)

but I just run your code and seems to be all fine

kederrac
  • 16,819
  • 6
  • 32
  • 55
  • I agree it's simpler to debug for loops. However for the sake writing clean and readable code I prefer using list comprehension and want to directly debug them. – itamar kanter Aug 01 '19 at 08:46
  • you wan to solve the problem or just to find a way to debug keeping the list comprehension? And by the way, generally speaking, using list comprehension instead of for loops is less readable (specially when you have more than one for in the comprehension) – kederrac Aug 01 '19 at 09:05
  • I want to solve the problem. Personally I prefer list comprehension over a for loops – itamar kanter Aug 01 '19 at 10:26
0

I got the same error few days back and what I did was just click Remove All Watches from debug console thanks to this PyCharm referencing older, removed variable question. Right click on your Variables section and click Remove All Watches and re-run your debug process.

enter image description here

Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58
  • It's not that issue, I think it has to do with the debug process. I think it's similar to https://stackoverflow.com/questions/17290314/possible-bug-in-pdb-module-in-python-3-when-using-list-generators or https://github.com/inducer/pudb/issues/103 – itamar kanter Aug 04 '19 at 08:10