On Fri, 2007-07-20 at 20:10 +0000, Alex Popescu wrote: > Carsten Haese <[EMAIL PROTECTED]> wrote in > news:[EMAIL PROTECTED]: > > > On Fri, 2007-07-20 at 19:08 +0000, Alex Popescu wrote: > >> Hi all! > >> > > > > > [snip...] > > > > > > This is called "Look before you leap." Note that "if key in my_dict" > > is preferred over has_key(). > > > > Can you please detail why in is prefered over has_key? Is it about > readability/performance?
Yes, it's about both readability and performance: [EMAIL PROTECTED] ~]$ python -m timeit -s "a={}" "a.has_key('foo')" 1000000 loops, best of 3: 0.601 usec per loop [EMAIL PROTECTED] ~]$ python -m timeit -s "a={}" "'foo' in a" 1000000 loops, best of 3: 0.307 usec per loop > Unfortunately, the get(key, None) suggestion is not 100% equivalent to > my posted code, and once I add the addition of the new object to the map > I think 1/ and 3/ are equivalent (if no other > readability/performance/etc is involved). Indeed, I missed that in 1/ and 2/ you're also adding the value to the dictionary. You could use setdefault instead of get: my_obj = my_dict.setdefault(key, myobject()) But if you want to defer creation of the default value until it's actually needed, you're better off with the "Look before you leap" approach. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list