5

That is, a lambda that takes no input and returns nothing.

I was thinking of clever ways to mimic switch statements in Python. Here's what I attempted (to no avail):

statement = {
    "Bob": lambda: print "Looking good, Bob!",
    "Jane": lambda: print "Greetings, Jane!",
    "Derek": lambda: print "How goes it, Derek?"
}[person]()
timgeb
  • 76,762
  • 20
  • 123
  • 145
Coffee Maker
  • 1,543
  • 1
  • 16
  • 29
  • http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python – Pavel Jun 05 '14 at 15:55
  • All lambdas, like functions, return *something*; the default is `None`. Just ignore the return value. Your problem is with trying to use a statement where only expressions can be used. – Martijn Pieters Jun 05 '14 at 15:56

2 Answers2

8

The contents of a lambda function must be a single expression; no statements are allowed. Moreover, print is a statement in Python 2.x. This means that you cannot use it inside a lambda.

If you want to use the Python 3.x print function, you can import it from __future__ like so:

# Add this line to the top of your script file
from __future__ import print_function

Now, print can be used inside lambdas because it is a function:

statement = {
    "Bob": lambda: print("Looking good, Bob!"),
    "Jane": lambda: print("Greetings, Jane!"),
    "Derek": lambda: print("How goes it, Derek?")
}[person]()
1

For this use case, you're probably better off doing:

print {
    "Bob": "Looking good, Bob!",
    "Jane": "Greetings, Jane!",
    "Derek": "How goes it, Derek?"
}[person]

or

statement = {
    "Bob": "Looking good, Bob!",
    "Jane": "Greetings, Jane!",
    "Derek": "How goes it, Derek?"
}[person]
print statement

For more complex switch-like applications, the dict could hold function references, of course.

I'm also fond of composing function names as strings:

class Greeter(object):
    ... 
    def _greet_Bob(self): ...
    def _greet_Jane(self): ...
    def _greet_Derek(self): ...

    def greet(self,person):
        getattr( self, "_greet_"+person )()  
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50