The pythonic approach

Peter Hansen peter at engcorp.com
Wed Sep 15 13:21:48 EDT 2004


Steven Bethard wrote:

> Peter Hansen <peter <at> engcorp.com> writes:
>>(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. 
> 
> I actually wrote code not too long ago that did make a call like .get(x, x).  
> I had a dictionary of word stems, e.g. 
> {"invention":"invent", "assistance":"assist", ...} read in from a file.  For 
> the particular app, if there was no stem for a word, I wanted to get the word 
> back.  I didn't have a function for it in my code, but I don't see why a 
> function like:
> 
> def getstem(self, word):
>     return self.stemdict.get(word, word)
> 
> would be so unreasonable.

It wouldn't be "so unreasonable".  Furthermore, it's a valid
example with context that makes it understandable and therefore
easier to discuss.  I also point out that it uses a dictionary
with much more in it than one item...  And the function name
makes sense in the problem domain, helping one understand the
purpose of the function and, thus, the reason for that particular
code pattern.  (Even so, I would tend to include a doc-string
or comment describing the basic algorithm, to let another
programmer more easily comprehend the approach taken.)

> I don't know why you would have to "pause to realize" that .get(x, x) returns 
> x as the default any more than you'd have to "pause to realize" that .get(x, 
> y) returns y as the default...

Principle of least surprise.  One rarely encounters .get(x, x)
and so, upon seeing it, at least in the context of the contrived
example (as opposed to in your own example), one might at first
think it was a mistake.

Personally, I'd use a regular lookup and catch the KeyError,
making it very explicit what the intent of the author was.
And that's the subject of the thread, after all: what is
the more pythonic approach.  For me, it's the one that
leads to the least surprise and potential for confusion.
(For others, it quickly gets into discussions of which
approach is "faster", as we may shortly see. ;-)

-Peter



More information about the Python-list mailing list