Fix default value handling for dotted sources by rpkilby · Pull Request #5375 · encode/django-rest-framework (original) (raw)

I had originally just moved the guard, as I thought it was possible for the instance to be None. However, that is never the case due to the following:

Given the above, the instance can only be set to None when iterating over the attrs list. With the guard, None is then returned. Without the guard, a subsequent attr would cause an AttributeError to be raised instead, allowing the default to be used.

with guard

get_attribute({'a': {'b': None}}, ['a', 'b', 'c']) None

without guard

get_attribute({'a': {'b': None}}, ['a', 'b', 'c']) Traceback (most recent call last): File "", line 1, in File "/Users/bagel/Documents/django-rest-framework/rest_framework/fields.py", line 100, in get_attribute instance = getattr(instance, attr) AttributeError: 'NoneType' object has no attribute 'c'