How to Check if a Python Object Has a Specific Method
In Python, you often need to determine if an object has a particular method before attempting to call it.
This guide explains the correct and reliable way to check if an object has a specific method, using the hasattr() and callable() functions. We'll also briefly discuss why a simple try/except block is not sufficient for this task.
Checking for a Method with hasattr() and callable() (Recommended)
The most reliable way to check if an object has a specific method involves two steps:
-
Check for attribute existence: Use
hasattr(object, 'method_name')to see if the object has an attribute with the given name. -
Check for callability: Use
callable(getattr(object, 'method_name'))to verify that the attribute is actually a callable method (and not, for example, a variable).
class Employee():
def __init__(self, first, last):
self.first = first
self.last = last
def get_name(self):
return f'{self.first} {self.last}'
emp1 = Employee('Tom', 'Nolan')
if hasattr(emp1, 'get_name') and callable(getattr(emp1, 'get_name')):
print(emp1.get_name()) # Output: Tom Nolan
hasattr(emp1, 'get_name'): This checks if theemp1object has an attribute named'get_name'. This could be any attribute (a method, a variable, etc.). It doesn't tell us if it's callable.getattr(emp1, 'get_name'): This retrieves the attribute named'get_name'fromemp1.callable(...): This is crucial. It checks if the retrieved attribute is callable (i.e., a function or method). This distinguishes a method from a simple data attribute.- The
ifstatement only executes if both checks succeed, making sure that you won't get exceptions.
Why try/except AttributeError is Insufficient
You might be tempted to use a try/except block to catch an AttributeError:
class Employee():
def __init__(self, first, last):
self.first = first
self.last = last
def get_name(self):
return f'{self.first} {self.last}'
emp1 = Employee('Tom', 'Nolan')
try:
result = emp1.get_name() # Call it directly
print(result) # Output: Tom Nolan
except AttributeError:
print('The attribute does NOT exist')
- The problem with using the
try/exceptblock is that it will check for attribute, but it won't tell you if the attribute is a callable.
Using getattr to Check a Method and Call It
You can use the getattr() method to get a method from an object, provide a default value, and execute it if the attribute is callable:
class Employee():
def __init__(self, first, last):
self.first = first
self.last = last
def get_name(self):
return f'{self.first} {self.last}'
emp1 = Employee('Tom', 'Nolan')
method = getattr(emp1, 'get_name', None) # The method returns None
if callable(method):
print(method()) # Output: Tom Nolan
- The code will first attempt to get an attribute with a
get_nameand store it intomethodvariable. - The second argument passed to
getattris the attribute name. - If the attribute does not exist,
getattrwill return the default value, which isNone. - The
callablemethod is used to check if the attribute is callable.