I am writing a short code to process a data file and stumbled on something I don't understand in the way lambda functions work.
Here is the problem: I have a list of keywords, and a list of the indexes of the lines where those keywords appears in a data file, and want to apply certain operations to said lines (and/or the adjacent lines, hence the need for a list of indexes and not simply a list of lines).
To do so, I defined a dictionary associating every keyword with a lambda function that will apply the wanted operation to the wanted line. For example:
methnames = {'acell' : lambda i : float(dat[i][1]) } #with dat the data file
(except with multiple keywords, and more complex functions).
Now, to execute that, as I expected, it required to have a global variable named dat to be defined, so I just put a dat=[], as I would call those function from within a local scope where dat would be defined.
Except when I execute the whole code, I get an IndexError, and the traceback tells me that, even if the that lambda was indeed called from within a local scope where dat should normally be defined, it still uses the global dat.
Even if I could go around that, this seems a very strange behaviour for Python, so I am probably missing something.
Here is a simplified version of the code :
dat=[]
methnames = {'acell' : lambda i : float(dat[i][1]) }
def test(dat):
return(methnames['acell'](0))
a=test([['acell',0,1,1]])
which should normally give a=0, and here is the return:
Traceback (most recent call last):
File "<ipython-input-21-cc8eb6df810c>", line 1, in <module>
runfile('/home/penwwern/Documents/mineralo/MinPhys/FrI/out/test.py', wdir='/home/penwwern/Documents/mineralo/MinPhys/FrI/out')
File "/usr/lib/python3/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/penwwern/Documents/mineralo/MinPhys/FrI/out/test.py", line 18, in <module>
a=test([['acell',0,1,1]])
File "/home/penwwern/Documents/mineralo/MinPhys/FrI/out/test.py", line 15, in test
return(methnames['acell'](0))
File "/home/penwwern/Documents/mineralo/MinPhys/FrI/out/test.py", line 9, in <lambda>
methnames = {'acell' : lambda i : float(dat[i][1]) }
IndexError: list index out of range
lambdais accessing, though.