1

Python 2.7.1

I would like to understand why I can't do the following which seems like a sensible thing to do

def do_stuff():
    # return a function which takes a map as an argument and puts a key in there
    f = lambda map: map['x'] = 'y' #compilation error
    return f 

x = do_stuff()
map = {}
x(map)
print map['x']

I can have that lambda function to be somethign simpler something like f = lambda map: os.path.exists however I cannot get it to change the map. Can someone tell me how I can achieve this? If this is not possible at all why?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101

1 Answers1

15

You can't use assignment in an expression, it is a statement. A lambda can only contain one expression, and statements are not included.

You can assign to the map though, by using the operator.setitem() function instead:

import operator

lambda map: operator.setitem(map, 'x', 'y')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343