How to Check If a Function Exists in Python
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!")
# ✅ Correct: Check if function name exists in global scope
if "greet" in globals():
print("Function 'greet' exists.")
greet()
else:
print("Function not found.")
# Checking for a non-existent function
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
# ✅ Correct: Check if 'sqrt' exists in 'math'
if hasattr(math, "sqrt"):
print(f"sqrt(16) = {math.sqrt(16)}")
else:
print("math.sqrt not found.")
Output:
sqrt(16) = 4.0
Checking an Object
class Robot:
def speak(self):
print("Beep boop.")
bot = Robot()
# ✅ Correct: Check if method exists
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
# 1. Check if it exists (using local scope logic or direct access)
# 2. Check if it is callable
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.
Combining hasattr() and callable() is the safest pattern for dynamic code:
if hasattr(obj, "method") and callable(getattr(obj, "method")): ...
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.