Always use safe attribute access patterns to handle potentially null or undefined attributes. Instead of direct attribute access that might raise AttributeError, use getattr()
with a default value. This pattern prevents null reference errors and makes code more robust.
Example:
# Unsafe:
version = obj.__version__
value = obj.as_tuple()
# Safe:
version = getattr(obj, '__version__', '')
try:
value = getattr(obj, 'as_tuple')()
except AttributeError:
value = None
This approach:
When using this pattern, choose meaningful default values that make sense in the context rather than always defaulting to None.
Enter the URL of a public GitHub repository