Pythonic way for missing dict keys

Chris Mellon arkanes at gmail.com
Wed Aug 1 21:31:51 CEST 2007


On 7/28/07, Steven D'Aprano <steve at remove.this.cybersource.com.au> wrote:
> On Sat, 28 Jul 2007 11:52:48 +0000, Alex Popescu wrote:
>
> > jjl at pobox.com (John J. Lee) wrote in news:87lkd0eprj.fsf at pobox.com:
> >
> >> Alex Popescu <nospam.themindstorm at gmail.com> writes:
> >>
> >>> Zentrader <zentraders at gmail.com> wrote in
> >>> news:1185041243.323915.161230 @x40g2000prg.googlegroups.com:
> >>>
> >>>> On Jul 21, 7:48 am, Duncan Booth <duncan.bo... at invalid.invalid>
> >>>> wrote:
> >>>>
> >>>> [snip...]
> >>>>
> >>>>
> >>>>>From the 2.6 PEP #361 (looks like dict.has_key is deprecated)
> >>>> Python 3.0 compatability: ['compatibility'-->someone should use a
> >>>> spell-checker for 'official' releases]
> >>>>         - warnings were added for the following builtins which no
> >>>> longer exist in 3.0:
> >>>>              apply, callable, coerce, dict.has_key, execfile,
> >>>>              reduce,
> >>>> reload
> >>>>
> >>>
> >>> I see... what that document doesn't describe is the alternatives to
> >>> be used. And I see in that list a couple of functions that are
> >>> probably used a lot nowadays (callable, reduce, etc.).
> >>
> >> callable and reduce are rarely used, at least in code I've seen.
> >
> > I thought G would be using that function a lot.
>
> Who or what is G? Guido?
>
> And which of the two functions mentioned is "that function"? callable()?
>
>
> Instead of doing:
>
>
> if callable(function): function()
>
> you should do:
>
> try:
>     function()
> except TypeError:
>     pass
>
>
> That should work for most uses of callable(), but isn't quite the same.
> (What if function() has side-effects, or is expensive, and you want to
> determine if it is callable, but not actually call it _now_?)
>

It's *really* not the same. Not only does it call the function, which
has all kinds of potential problems like you listed, but this also
will convert TypeErrors in the called function into "this is not a
callable", which is almost certainly not what you want. hasattr(x,
'__call__') works but is annoying to write and hides intent. I'd be
happy if inspect grew iscallable.



More information about the Python-list mailing list