Back to all reviewers

Safe attribute access pattern

pydantic/pydantic
Based on 4 comments
Python

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.

Null Handling Python

Reviewer Prompt

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:

  1. Provides fallback values for missing attributes
  2. Makes null cases explicit and handled
  3. Reduces runtime errors from missing attributes
  4. Makes code more maintainable by centralizing null handling

When using this pattern, choose meaningful default values that make sense in the context rather than always defaulting to None.

4
Comments Analyzed
Python
Primary Language
Null Handling
Category

Source Discussions