Testing methods

Anton Muhin antonmuhin at sendmail.ru
Sat Apr 19 14:00:09 EDT 2003


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__:
> 
> But that doesn't tell me whether or not "some_method" is a method. 
> Further, if I have an instance of a class, that doesn't seem to work. 
> I've been searching through the docs, but I can't quite figure this
> out.
> 
> I'm a clueless newbie here, so please be kind :)
> 
> Cheers,
> Ovid

There are several ways to do it.

1. More Pythonic IMHO:

class Foo:
     def bar(self):
         print "Foo.bar"

foo = Foo()

try:
     foo.absent_method()
except (AttributeError, TypeError), e:
     print "Failed. Message @%s@" % e, "Type: %s" % e.__class__.__name__
else:
     print "OK"

2. Look at hasattr and callable functions

foo = Foo()
foo.xxx = 239

print hasattr(foo, "absent_method") # false
print hasattr(foo, "xxx") # true
print callable(foo.xxx) # false
print callable(foo.bar) # true

Sure, there are circumstances, then one of methods is better.

BTW, look for a thread about typing in Python---you might find 
interesting information there.

hth,
Anton.





More information about the Python-list mailing list