'NameError: global name is not defined' under pdb, for dictionary that does exist

一个人想着一个人 提交于 2019-12-03 16:09:32

You set a new local with pdb, but that is not visible to expressions using nested scopes in this debugger session. Any expression in a nested scope such as the lambda used for the key argument, using a name that is local to the current frame, would need to be a closure and will have this problem.

That's a limitation of how the debugger and Python compilation work; closures can only be created if the function that need to produce them was compiled in the same session. Since the function you are debugging was compiled without foo being a closure, it cannot be used by the lambda expression as such.

You can bind the local to the lambda (making it a local rather than a closure):

max(foo, key=lambda x, foo=foo: foo[x]['extra_data']['budget'])

See What exactly is contained within a obj.__closure__? for details on how the Python compiler creates closures.

There is a bug report for Python 3 (however this issue affects Python 2.7 as well as you found out) which suggests a workaround as an alternative to Martijn's solution: interact at the pdb prompt drops you into an interactive session which is populated with globals() and locals() and your lambda should work as expected.

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