How to check if a function is a method of some object?
For example:
def check_method(f):
...
check_method(lambda x: x + 1) # >>>
A twist to the question involves asking to check if some function name would be available as a method. Since duck typing is considered pythonic there should be a simple
hasmethod(obj, 'some_method')
but it seems, there isn't.
Duck typing seems to be best done by just trying:
try:
obj.some_method()
except:
# try something else
If someone wants a function to check programmatically if an object has a method with a certain variable name, then the following function has been mentioned:
def hasmethod(obj, method_name):
return hasattr(obj, method_name) and callable(getattr(obj, method_name))
But for Python 3 and 3.1 at least you need to get callable() back which was removed. A discussion of the want of bringing it back can be found in a python bug entry Resurrect callable with e.g.:
def callable(obj):
return isinstance(obj, collections.Callable)
This is straight from the above mentioned python bugtracker. Other sources on stackoverflow mention
callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable)
which adds the hasattr to the call. Both work fine in my use case
>>> bstr = b'spam'
>>> str = 'eggs'
>>> hasmethod(str, 'decode')
False
>>> hasmethod(bstr, 'decode')
True
For more details look at the already cited other question