When working with dynamic imports, plugins, or introspection, you often need to check if a module (or any object) contains a specific attribute (be it a function, class, or variable) before attempting to use it. Accessing a non-existent attribute raises an AttributeError.
This guide covers how to safely check for and retrieve attributes using hasattr() and getattr().
Method 1: Using hasattr() (Boolean Check)
The built-in hasattr(object, name) function is the most direct way to check for existence. It returns True if the attribute exists and False otherwise.
import math
if hasattr(math, 'sqrt'):
print("Math module has 'sqrt'.")
else:
print("Math module does not have 'sqrt'.")
if hasattr(math, 'unknown_func'):
print("Found 'unknown_func'.")
else:
print("'unknown_func' not found.")Output:
Math module has 'sqrt'.
'unknown_func' not found.Method 2: Using getattr() (Safe Access)
If your goal is to use the attribute if it exists, getattr(object, name, default) is often cleaner than hasattr. It attempts to get the attribute and returns a default value if it's missing.
import math
pi_val = getattr(math, 'pi', 3.14)
print(f"PI: {pi_val}")
magic_num = getattr(math, 'magic_number', 0)
print(f"Magic Number: {magic_num}")Output:
PI: 3.141592653589793
Magic Number: 0Method 3: Exception Handling (EAFP)
Python often encourages the "Easier to Ask for Forgiveness than Permission" (EAFP) style. Instead of checking first, just try to use it and catch the error.
import math
try:
result = math.super_log(10)
except AttributeError:
print("Attribute 'super_log' not found. Using default logic.")
result = math.log(10)
print(f"Result: {result}")Output:
Attribute 'super_log' not found. Using default logic.
Result: 2.302585092994046Method 4: Inspecting __dict__
You can inspect the module's namespace directly using its __dict__ attribute or the dir() function. This is useful for debugging or filtering attributes.
import math
if 'cos' in math.__dict__:
print("'cos' is available.")
all_attributes = dir(math)
if 'sin' in all_attributes:
print("'sin' is available.")Output:
'cos' is available.
'sin' is available.Conclusion
To check for attributes in a Python module:
- Use
hasattr(mod, 'attr')for simple True/False checks. - Use
getattr(mod, 'attr', default)when you want to retrieve the value safely with a fallback. - Use
try...except AttributeErrorwhen you want to execute logic immediately and handle failures gracefully.