Common Python Idioms

Duncan Booth duncan.booth at invalid.invalid
Thu Dec 7 08:33:15 EST 2006


"Stephen Eilert" <spedrosa at gmail.com> wrote:

> I've always used has_key(), thinking it was the only way to do it.
> Given that Python says that "There Should Be Only One Way to Do It", I
> didn't bother searching for alternatives.

The full quote is actually: 
    	There should be one-- and preferably only one --obvious way to do it.
    	Although that way may not be obvious at first unless you're Dutch.

It might be more accurate to add a third line:
    	And the one true way may change with new versions of Python

In this case, dict objects used to not support the 'in' operator, but at 
some point it was added. I believe it wasn't there originally because Guido 
wasn't sure whether people would expect it should match keys or keys and 
values.

> 
> Is there a list somewhere listing those not-so-obvious-idioms? I've
> seen some in this thread (like the replacement for .startswith).
> 
The release notes for each new version. Unfortunately the rest of the 
documentation sometimes lags behind the release notes.


> I do think that, if it is faster, Python should translate
> "x.has_key(y)" to "y in x".

Python doesn't know whether x has a __contains__ method until it tries to 
call it. In particular there may be user-defined dictionary-like objects in 
your program which support has_key but not 'in'. e.g. in at least some 
versions of Zope HTTPRequest objects support has_key but not __contains__.



More information about the Python-list mailing list