Any simpler way to do this

Tim Golden mail at timgolden.me.uk
Fri Dec 7 04:06:02 EST 2007


Lars Johansen wrote:
> I have a function that looks like this:
> 
> def Chooser(color):
> 
>         if color == "RED":
>                 x = term.RED
>         elif color == "BLUE":
>                 x = term.BLUE
>         elif color == "GREEN":
>                 x = term.GREEN
>         elif color == "YELLOW":
>                 x = term.YELLOW
>         elif color == "CYAN":
>                 x = term.CYAN
>         elif color == "MAGENTA":
>                 x = term.MAGENTA
>         return x
> 
> 
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?

One option -- given your source code -- is this. Obviously this only
works if the color name exactly matches the attribute name.

<code - untested>
def Chooser(color):
     return getattr(term, color, None)
</code>

If you needed to vary things then a dictionary lookup
is probably the best bet, eg:

<code - untested>
def Chooser(color):
     color_map = {
       "RED" : term.RED,
       "BLUE" : term.AQUAMARINE
     }
     return color_map.get(color)
</code>

Obviously in either case you have to know what to do with
exceptions, but then that's true of your sample code as well.
My code mirrors yours in that None is returned if no match
is found.

TJG



More information about the Python-list mailing list