Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pdb lambda function global name error

I was testing a fix using pdb.set_trace() to make sure it worked the way I expected before implementing it and kept getting a weird error.

(Pdb) test = [1,2,3,4,4,3,2,1]
(Pdb) max(range(len(test)),key=lambda i: test[i])
*** NameError: global name 'test' is not defined

So I moved to my localmachine to make sure I could reproduce as simply as possible before asking for help. In ipython I get the exact same behavior.

In [1]: test = [1,2,3,4,4,3,2,1]

In [2]: max(range(len(test)),key=lambda i: test[i])
Out[2]: 3

In [3]: import pdb; pdb.set_trace()
--Call--
> /Users/tristanmatthews/anaconda/lib/python2.7/site-packages/IPython/core/displayhook.py(237)__call__()
-> def __call__(self, result=None):
(Pdb) test = [1,2,3,4,4,3,2,1]
(Pdb) max(range(len(test)),key=lambda i: test[i])
*** NameError: global name 'test' is not defined

But at the normal command line it works just fine:

tristan:~$ python
Python 2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test = [1,2,3,4,4,3,2,1]
>>> max(range(len(test)),key=lambda i: test[i])
3
>>> import pdb; pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) test = [1,2,3,4,4,3,2,1]
(Pdb) max(range(len(test)),key=lambda i: test[i])
3

If anyone has any idea what is going on here I would REALLY love to know.

For the record the fix works fine in my code, just not in the debugger.

For reference my versions of python are: Original error:

'2.7.3 (default, Apr 10 2013, 06:20:15) \n[GCC 4.6.3]'

Local Machine both ipython and the command line are the same:

In [5]: sys.version
Out[5]: '2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09) \n[GCC 4.0.1 (Apple Inc. build 5493)]'
>>> sys.version
'2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09) \n[GCC 4.0.1 (Apple Inc. build 5493)]'
like image 504
TristanMatthews Avatar asked Feb 22 '14 01:02

TristanMatthews


1 Answers

I can confirm this issue with Python 2.7. There is a bug report for Python 3 which suggests a workaround: 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.

like image 106
kynan Avatar answered Oct 11 '22 16:10

kynan