How To Check Whether A Method Exists In Python?
In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object? import string
Solution 1:
Check if class has such method?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
or
hasattr(Dynamo, 'mymethod') andcallable(getattr(Dynamo, 'mymethod'))
You can use self.__class__
instead of Dynamo
Solution 2:
It's easier to ask forgiveness than to ask permission.
Don't check to see if a method exists. Don't waste a single line of code on "checking"
try:
dyn.mymethod() # How to check whether this exists or not# Method exists and was used. except AttributeError:
# Method does not exist; What now?
Solution 3:
How about dir()
function before getattr()
?
>>> "mymethod"indir(dyn)
True
Solution 4:
I use below utility function. It works on lambda, class methods as well as instance methods.
Utility Method
defhas_method(o, name):
returncallable(getattr(o, name, None))
Example Usage
Let's define test class
classMyTest:
b = 'hello'
f = lambda x: x
@classmethoddeffs():
passdeffi(self):
pass
Now you can try,
>>>a = MyTest() >>>has_method(a, 'b')
False
>>>has_method(a, 'f')
True
>>>has_method(a, 'fs')
True
>>>has_method(a, 'fi')
True
>>>has_method(a, 'not_exist')
False
Solution 5:
You can try using 'inspect' module:
import inspect
defis_method(obj, name):
returnhasattr(obj, name) and inspect.ismethod(getattr(obj, name))
is_method(dyn, 'mymethod')
Post a Comment for "How To Check Whether A Method Exists In Python?"