A question of style (finding item in list of tuples)

Jon Clements joncle at googlemail.com
Mon May 21 09:39:59 EDT 2012


On Monday, 21 May 2012 13:37:29 UTC+1, Roy Smith  wrote:
> I've got this code in a django app:
> 
>     CHOICES = [
>         ('NONE', 'No experience required'),
>         ('SAIL', 'Sailing experience, new to racing'),
>         ('RACE', 'General racing experience'),
>         ('GOOD', 'Experienced racer'),
>         ('ROCK', 'Rock star'),
>         ]
> 
>     def experience_text(self):
>         for code, text in self.CHOICES:
>             if code == self.level:
>                 return text
>         return "????"
> 
> Calling experience_text("ROCK") should return "Rock star".  Annoyingly, 
> django handles this for you automatically inside a form, but if you also 
> need it in your application code, you have to roll your own.
> 
> The above code works, but it occurs to me that I could use the much 
> shorter:
> 
>     def experience_text(self):
>         return dict(CHOICES).get("self.level", "???")
> 
> So, the question is, purely as a matter of readability, which would you 
> find easier to understand when reading some new code?  Assume the list 
> of choices is short enough that the cost of building a temporary dict on 
> each call is negligible.  I'm just after style and readability here.

Haven't used django in a while, but doesn't the model provide a get_experience_display() method which you could use...

Failing that, if order isn't important, you can not bother with tuples and have CHOICES be a dict, then pass choices=CHOICES.iteritems() as I believe it takes any iterable, and maybe plug an ordereddict if order is important.

hth

Jon.



More information about the Python-list mailing list