Skip to main content

How to Check If a Module Has a Specific Attribute in Python

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

# ✅ Check if 'sqrt' exists in the math module
if hasattr(math, 'sqrt'):
print("Math module has 'sqrt'.")
else:
print("Math module does not have 'sqrt'.")

# Check for a non-existent attribute
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

# ✅ Get 'pi' safely. If missing, return 3.14
pi_val = getattr(math, 'pi', 3.14)
print(f"PI: {pi_val}")

# Try getting a missing attribute with a default
magic_num = getattr(math, 'magic_number', 0)
print(f"Magic Number: {magic_num}")

Output:

PI: 3.141592653589793
Magic Number: 0
tip

This pattern is excellent for optional dependencies or configuration modules where settings might be missing.

Method 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:
# ⛔️ Warning: 'super_log' doesn't exist
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.302585092994046

Method 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

# ✅ Check if key exists in the module's namespace dictionary
if 'cos' in math.__dict__:
print("'cos' is available.")

# Using dir()
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:

  1. Use hasattr(mod, 'attr') for simple True/False checks.
  2. Use getattr(mod, 'attr', default) when you want to retrieve the value safely with a fallback.
  3. Use try...except AttributeError when you want to execute logic immediately and handle failures gracefully.