What is the fastest way to check if a class has a function defined?
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.
It works in both Python 2 and Python 3
hasattr(connection, 'invert_opt')
hasattr
returns True
if connection object has a function invert_opt
defined. Here is the documentation for you to graze
https://docs.python.org/2/library/functions.html#hasattr https://docs.python.org/3/library/functions.html#hasattr