What's the difference ?
aleax at mac.com
Wed Aug 29 16:44:57 CEST 2007
<kyosohma at gmail.com> wrote:
> Weird. Hetland's book, "Beginning Python" states that it's a matter of
If your taste is for more verbose AND slower notation without any
compensating advantage, sure.
> Martelli's "Python Cookbook 2nd Ed." says to use the get()
> method instead as you never know if a key is in the dict. However, I
> can't seem to find any reference to has_key in his book.
.get is not a direct alternative to ``in'' (it's an alternative to an
idiom where you key into the dict if the key is present and otherwise
supply a default value, and it's MUCH better in that case). has_key is
probably not even mentioned in the Cookbook (2nd edition) since there is
never a good need for it in the Python versions it covers (2.2 and up),
but you can probably find traces in the 1st edition (which also covered
Python back to 1.5.2, where has_key *was* needed); the Nutshell (2nd ed)
mentions it briefly in a table on p. 60.
> According to Chun in "Core Python Programming", has_key will be
> obsoleted in future versions of Python, so he recommends using "in" or
> "not in".
Yes, we're removing has_key in Python 3.0 (whose first alpha will be out
reasonably soon, but is not going to be ready for production use for
quite a bit longer), among other redundant things that exist in 2.* only
for legacy and backwards compatibility reasons. This makes 3.0 simpler
(a little closer to the "only one obvious way" ideal).
But you should use ``in'' and ``not in'' anyway, even if you don't care
about 3.* at all, because they only have advantages wrt has_key, without
any compensating disadvantage.
More information about the Python-list