List comprehension scope error from Python debugger

后端 未结 2 1162
鱼传尺愫
鱼传尺愫 2020-12-03 02:41

In debugging my code, I want to use a list comprehension. However, it seems I cannot evaluate a list comprehension from the debugger when I\'m inside a function.

I a

2条回答
  •  攒了一身酷
    2020-12-03 02:57

    pdb seems to be running the code with:

    eval(compiled_code, globals(), locals())
    

    (or maybe even just eval(string, globals(), locals())).

    Unfortunately, on compilation Python doesn't know of the local variables. This doesn't matter normally:

    import dis
    
    dis.dis(compile("x", "", "eval"))
    #>>>   1           0 LOAD_NAME                0 (x)
    #>>>               3 RETURN_VALUE
    

    but when another scope is introduced, such as with a list comprehension of lambda, this compiles badly:

    dis.dis(compile("(lambda: x)()", "", "eval"))
    #>>>   1           0 LOAD_CONST               0 ( at 0x7fac20708d20, file "", line 1>)
    #>>>               3 LOAD_CONST               1 ('')
    #>>>               6 MAKE_FUNCTION            0
    #>>>               9 CALL_FUNCTION            0 (0 positional, 0 keyword pair)
    #>>>              12 RETURN_VALUE
    
    # The code of the internal lambda
    dis.dis(compile("(lambda: x)()", "", "eval").co_consts[0])
    #>>>   1           0 LOAD_GLOBAL              0 (x)
    #>>>               3 RETURN_VALUE
    

    Note how that's a LOAD_GLOBAL where x is in the local scope.


    Here's a totally stupid hack to get around it:

    (Pdb) eval("(lambda: x)()", vars())
    [1, 2, 3, 3, 4]
    

提交回复
热议问题