What is the fastest way to check if a class has a function defined?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 What Is The Fastest Way To Check If A Class Has A Function Defined?
00:58 Accepted Answer Score 312
01:22 Answer 2 Score 22
02:15 Answer 3 Score 5
02:41 Answer 4 Score 81
03:08 Thank you
--
Full question
https://stackoverflow.com/questions/5268...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 312
Yes, use getattr() to get the attribute, and callable() to verify it is a method:
invert_op = getattr(self, "invert_op", None)
if callable(invert_op):
    invert_op(self.path.parent_op)
Note that getattr() normally throws exception when the attribute doesn't exist. However, if you specify a default value (None, in this case), it will return that instead.
ANSWER 2
Score 81
It works in both Python 2 and Python 3
hasattr(connection, 'invert_opt') and callable(connection.invert_opt)
hasattr returns True if connection object has an attribute invert_opt defined. callable checks to see if the attribute is callable (e.g. a function). Here is the documentation for you to graze:
ANSWER 3
Score 22
Is there a faster way to check to see if the function is not defined than catching an exception?
Why are you against that? In most Pythonic cases, it's better to ask forgiveness than permission. ;-)
hasattr is implemented by calling getattr and checking if it raises, which is not what I want.
Again, why is that? The following is quite Pythonic:
    try:
        invert_op = self.invert_op
    except AttributeError:
        pass
    else:
        parent_inverse = invert_op(self.path.parent_op)
        ops.remove(parent_inverse)
Or,
    # if you supply the optional `default` parameter, no exception is thrown
    invert_op = getattr(self, 'invert_op', None)  
    if invert_op is not None:
        parent_inverse = invert_op(self.path.parent_op)
        ops.remove(parent_inverse)
Note, however, that getattr(obj, attr, default) is basically implemented by catching an exception, too. There is nothing wrong with that in Python land!
ANSWER 4
Score 5
Like anything in Python, if you try hard enough, you can get at the guts and do something really nasty. Now, here's the nasty part:
def invert_op(self, op):
    raise NotImplementedError
def is_invert_op_implemented(self):
    # Only works in CPython 2.x of course
    return self.invert_op.__code__.co_code == 't\x00\x00\x82\x01\x00d\x00\x00S'
Please do us a favor, just keep doing what you have in your question and DON'T ever use this unless you are on the PyPy team hacking into the Python interpreter. What you have up there is Pythonic, what I have here is pure EVIL.