In dynamic programming environments or when loading modules at runtime, you may need to verify if a function exists before calling it. Calling an undefined function raises a NameError or AttributeError, crashing your script.
This guide explains how to check for function existence using the in operator, hasattr(), and callable().
Method 1: Checking Local/Global Scope
If the function is defined in your current script, its name resides in either the locals() or globals() dictionary.
def greet():
print("Hello!")
if "greet" in globals():
print("Function 'greet' exists.")
greet()
else:
print("Function not found.")
if "goodbye" not in globals():
print("Function 'goodbye' does not exist.")Output:
Function 'greet' exists.
Hello!
Function 'goodbye' does not exist.Method 2: Using hasattr() for Modules and Classes
When working with imported modules or objects, hasattr() is the standard way to check for the existence of functions (which are attributes of the module/object).
Checking a Module
import math
if hasattr(math, "sqrt"):
print(f"sqrt(16) = {math.sqrt(16)}")
else:
print("math.sqrt not found.")Output:
sqrt(16) = 4.0Checking an Object
class Robot:
def speak(self):
print("Beep boop.")
bot = Robot()
if hasattr(bot, "speak"):
bot.speak()Output:
sqrt(16) = 4.0
Beep boop.Method 3: Verifying Callability with callable()
Just because an attribute exists doesn't mean it's a function. It could be a variable (integer, string, etc.). To ensure you can actually execute it, use callable().
def my_func():
return "I run!"
my_var = 42
if callable(my_func):
print("my_func is callable.")
if not callable(my_var):
print("my_var exists but is NOT callable.")Output:
my_func is callable.
my_var exists but is NOT callable.Conclusion
To check if a function exists in Python:
- Use
name in globals()for functions defined in the current script. - Use
hasattr(obj, "name")for functions inside modules or classes. - Use
callable(obj)to verify that the object is actually a function and not a variable.