if the else short form

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Wed Oct 6 20:45:11 EDT 2010


On Thu, 07 Oct 2010 01:36:33 +0100, BartC wrote:


> However,  as I mentioned, one problem here is having to evaluate all the
> items in the list before selecting one:
> 
> def fna():
>         print "FNA CALLED"
>         return "One"
> def fnb():
>         print "FNB CALLED"
>         return "Two"
> def fnc():
>         print "FNC CALLED"
>         return "Three"
> 
> i=16
> x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, "None Of The Above") 
> print x
> 
> Other than efficiency concerns, sometimes you don't want the extra
> side-effects.

Try this instead:

i=16
x = {1 : fna, 2 : fnb, 3 : fnc}.get(i, "None Of The Above")()
print x


Also known as the command dispatch pattern.


First class functions are a wonderful thing-ly y'rs, 


-- 
Steven



More information about the Python-list mailing list