Python variable is evaluated differently in pdb and print statements

心已入冬 提交于 2019-12-11 18:11:26

问题


I am using threads in a python program and recently found a problem where a float is not being interpreted correctly and whenever I go to print it out in pdb or in a logging statement, it shows up correctly most of the time.

Oddly, it takes a different amounts of prints to show up in these two threads I just ran. Also the first two prints use the same format, but the value still changes in thread 1.

for x in imports:
    if float(x.prob) == 0.0:
        logging.debug(float(x.prob))
        logging.debug(float(x.prob))
        logging.debug(x.prob)
        logging.debug(str(x.prob))
        logging.debug(str(float(x.prob)))
        import pdb; pdb.set_trace()

[DEBUG] (Thread-1  ) 0.0
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-2  ) 0.0
[DEBUG] (Thread-2  ) 0.0
[DEBUG] (Thread-2  ) 0
[DEBUG] (Thread-2  ) 0.0592
[DEBUG] (Thread-2  ) 0.0592

and

(Pdb) float(x.prob) == 0.0
False

What is the cause? what can I do so it's interpreted correctly the first time?

Similar to this question: https://stackoverflow.com/questions/2485338/pdb-show-different-variable-values-than-print-statements


回答1:


Its pretty impossible to tell from what you've posted. Floats don't switch from 0.0 to ~0.05 randomly, something is changing the value stored in that memory location (variable). Are you setting the value from other thread?

Also, be aware that in your demo code, if you're looking for x.prob to have the value of 0.0592 from the beginning, it will fail the equality test in the if statement and never trigger your print statements.



来源:https://stackoverflow.com/questions/5644521/python-variable-is-evaluated-differently-in-pdb-and-print-statements

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