python – What is the fastest way to check if a class has a function defined?
python – 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 doesnt 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
python – What is the fastest way to check if a class has a function defined?
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, its 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!