The pythonic approach

Peter Hansen peter at engcorp.com
Wed Sep 15 08:16:40 EDT 2004


Timo Virkkala wrote:

> def thisReallyWorks(x):
>     if x == "6$":
>         return "$10 000"
>     else:
>         return x
> 
> # or maybe
> 
> investments = {"6$": "$10 000"}
> def thisReallyWorks(x):
>     return investments.get(x, x)

I really hope this is a contrived example, because if
I ever saw something like this in real code I'd barf.

Nevertheless, solely for the particular example shown
above, I'd have to say (a) is much better.  The (b)
approach is obscure and indirect.  One has to pause and
realize that the .get(x, x) thing means that if x
doesn't exist as a key in the dictionary, it will
instead be returned as the actual result.  Using
x as the input, the lookup key, and the default result
makes the whole thing look bizarre and ill-conceived.

(My gut tells me that if this were something that was
required in real code, it would actually be using an
existing dictionary (not one created with a single
entry just before the function) and the best code
would be an inline .get() rather than a function call,
and that x might not even be its own default, but
I can't imagine what real code this corresponds to
so that's all I have to say about that. :-)

-Peter



More information about the Python-list mailing list