Conditional expressions (again)
Steven D. Majewski
sdm7g at Virginia.EDU
Fri Oct 26 11:46:38 EDT 2001
On Fri, 26 Oct 2001 gbreed at cix.compulink.co.uk wrote:
> Compare
>
> order.append(
> spam if customer == michae1 else
> eggs if customer == john else
> cheese)
>
> with
>
> if customer == michael:
> side0rder = spam
> elif customer == john:
> sideOrder = eggs
> else:
> sideOrder = cheese
> order.append(sideOrder)
>
> in terms of how likely each error is to arise in testing, and how much
> time it would take to work out what was going wrong. I find that almost
> convincing ;-)
>
How about something like:
>>> custorders = { 'michael' : 'spam', 'john' : 'eggs' }
>>> default = 'cheese'
>>> order.append( custorders.get( customer, default ) )
In general, table driven code is often the most clear and clean
representation, and mappings can often be a good replacement
for conditionals.
-- Steve
More information about the Python-list
mailing list