2

What is the best (or 'Pythonic') way to test if a class has a specific method defined?

Both of these work but don't feel 'correct' in that in the second one, I just try to access it and trap for an exception if it doesn't exist.

Is there a better / more correct way?

class TestClass(object):
    def TestFunc(self):
        pass



if 'TestFunc' in dir(TestClass):
    print 'yes'
else:
    print 'No'



try:
    if TestClass.__getattribute__(TestClass, 'TestFunc'):
        print 'yes'

except:
    print 'No'
tMC
  • 18,105
  • 14
  • 62
  • 98

2 Answers2

10

Use hasattr:

class Foo(object):
    def bar():
        pass

assert hasattr(Foo, 'bar')

If you really mean to test whether the attribute is a method, you could do this:

assert hasattr(Foo, 'bar') and callable(getattr(Foo, 'bar'))
senderle
  • 145,869
  • 36
  • 209
  • 233
  • 2
    Note that this internally works like the second. A big advantage is that the two work even with properties and other things not in the `__dict__`, `__slots__`, etc. –  Jun 06 '11 at 15:54
  • This won't say if it's a **method** or not - only that it's defined on that class – Gerrat Jun 06 '11 at 16:04
  • @Gerrat, I thought of that, but because the OP's examples did what hasattr does, I assumed that's what he wanted to do. Still, I've edited it to cover the method case. – senderle Jun 06 '11 at 16:08
3

You're close.

It's Easier to Ask Forgiveness than to Ask Permission.

try:
    testClassInstance.testFunc()

except AttributeError:
    pass # Ask forgiveness.

Don't "pre-test" for things like this. Assume they exist and cope with their absence.

S.Lott
  • 384,516
  • 81
  • 508
  • 779