sufficiently pythonic code for testing type of function

Theerasak Photha hanumizzle at gmail.com
Fri Oct 13 10:28:00 EDT 2006


On 10/11/06, Bruno Desthuilliers <onurb at xiludom.gro> wrote:
> Theerasak Photha wrote:
> > On 10/11/06, Fredrik Lundh <fredrik at pythonware.com> wrote:
> >
> >> can be a lot better than a 30-level traceback that ends with a line
> >> looking something like
> >>
> >>      fnut.index(gah)
> >
> > Despite long experience with Perl, I am not a big follower of the
> > "goose_level: blah" method of error reporting...
> >
> >> also, checking for __method__ is, in general, not the right way to check
> >> if an object implements a given interface.
> >
> > I had a vague feeling it might not be a Right Thing(tm).
> > <flame-proof-underwear>I kind of miss
> > responds_to?</flame-proof-underwear>
>
> getattr(obj, name[,default]) is your friend. Remember that methods are
> just callable attributes.

I am familiar with getattr from the Introspection material in Dive
into Python of course.

Earlier in the thread we decided that using getattr is the Wrong
Way(tm) to decide whether an object has such and such operation
(respond_to?) because implementation details can hide this.

So I learned the best thing to do is Suck It And See (an electrical
joke, not a penis joke, BION) aka EAFP.

I just found out Ruby isn't much better in this regard:

class Foo
  def self.method_missing(meth, *args)
    puts meth
  end
end

Foo.bar()
puts Foo.respond_to?(:bar)

===>
bar
false

WTF?

-- Theerasak



More information about the Python-list mailing list