Variable alternates whether or not it exists in Python Debugger

╄→гoц情女王★ 提交于 2019-12-02 05:57:35

问题


Can anyone explain this? (Python 2.7, Django 1.7)

foo = data['selected_items']
(Pdb) foo
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) u'1,2'
foo
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) u'1,2'
foo
(Pdb) *** NameError: name 'foo' is not defined
foo
(Pdb) u'1,2'

Here is the view function that triggered it:

def process_form(request, model_name):
    form = BulkEditForm(request.POST)
    if form.is_valid():
        data = form.clean()

        if data['select_all']:
            pass
        else:
            import pdb; pdb.set_trace()

request.POST:

{'select_all': False, 'primary_tech': <Person: Bob>, 'primary_biz': <Person: Mary>, 'selected_items': u'1,2', 'backup_tech': None, 'backup_biz': None}

回答1:


You have two threads which stopped at the same breakpoint.

So basically, there are two instances of pdb, competing for your prompt, i.e. your prompts are alternating between the different threads. You first assign to the name foo in one, than the other one gets a chance to run, knowing nothing about foo, then when you press enter, the other is back, with foo defined.

The best indicator that this is the case is that your prompt is not aligned with your commands and their outputs. Instead of:

<PROMPT> COMMAND
OUTPUT
<PROMPT> COMMAND
OUTPUT

You see:

COMMAND
<PROMPT> OUTPUT
COMMAND
<PROMPT> OUTPUT

Everytime you press enter, the "other" thread sneaks in its prompt before the "first" thread manages to write its output.


EDIT

A simple way to reproduce in a standalone, without django:

from threading import Thread

def f(x):
    import pdb; pdb.set_trace()
    while True: pass

t1 = Thread(target=lambda: f(1))
t2 = Thread(target=lambda: f(2))
t1.start(); t2.start()

(Pdb) x
2
(Pdb) x
1



回答2:


When the statement appears in PDB, it hasn't actually been executed yet. It will be executed once you use 'next'.



来源:https://stackoverflow.com/questions/25146489/variable-alternates-whether-or-not-it-exists-in-python-debugger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!