Testing methods

Jp Calderone exarkun at intarweb.us
Sat Apr 19 13:47:48 EDT 2003


On Sat, Apr 19, 2003 at 10:38:40AM -0700, Ovid wrote:
> Hello,
> 
> Relatively new to Python and I thought I would teach myself the
> language by building a test harness.  After I'm done, I will probably
> be throwing it away in favor of Pyunit, but it seemed like a good way
> to learn some of the fiddly bits.
> 
> Fiddly bits such as "can this object do that?"  In my test code, I
> want to test whether or not a given class *or* instance of that class
> can execute a particular method (i.e., if it has or inherits the
> method).  For example, one way (in Perl), to test if object "$foo" can
> execute an arbitrary method would be:
> 
>   if ( $foo->can($some_method) )
> 
> For the life of me, I can't figure out the equivalent in Python.  I
> suppose I could do:
> 
>   if some_method in Foo.__dict__:
> 

  The Pythonic (Gee, I hope I'm still allowed to use that word) way to do
this is simply:

    try:
        foo.some_method()
    except:
        print "Foo can't do it"
    else:
        print "Foo can do it"

  Sometimes this is undesirable, but then the right answer depends on the
particulars of why it is undesirable.  There are other approaches, but none
that work as reliably.  For example:

    if hasattr(foo, 'some_method') and callable(foo.some_method):
        ...

  callable() may return false positives, though.  I don't think it will ever
return false negatives.

  Jp

-- 
Seduced, shaggy Samson snored.
She scissored short.  Sorely shorn,
Soon shackled slave, Samson sighed,
Silently scheming,
Sightlessly seeking
Some savage, spectacular suicide.
                -- Stanislaw Lem, "Cyberiad"
-- 
 up 30 days, 13:02, 4 users, load average: 0.29, 0.22, 0.16





More information about the Python-list mailing list