tMC
tMC

Reputation: 19355

Testing for specific method in a Python class

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'

Upvotes: 2

Views: 188

Answers (2)

senderle
senderle

Reputation: 151137

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'))

Upvotes: 10

S.Lott
S.Lott

Reputation: 391992

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.

Upvotes: 3

Related Questions