Issue Description
When passing an out-of-range int index to utils.get_value, a TypeError is raised instead of returning the provided default value. Based on the documentation and function’s behavior in string cases, I’d expect it to fall back to default when the index is invalid. FYI, this issue seems to occur because handling IndexError requires falling back to getattr(obj, key, default). This logic was introduced in PR #1063 following git blame. I think this issue can be fixed by handling this TypeError to return default value. I can make an PR if this change make sense to you.
Reproducing Code Example
from marshmallow import utils
### Case 1: List
lst = [0, 1, 2, 3, 4, 5]
print(utils.get_value(lst, 999, default=3))
### Case 1: Dictionary with integer keys
dictionary = {1: 'a', 2: 'b', 3: 'c'}
print(utils.get_value(dictionary, 4, default='z'))
### Case 3: List of object
class PointClass:
def __init__(self, x, y):
self.x = x
self.y = y
list_obj = [[PointClass(24, 42),{"x": 24, "y": 42}]]
print(utils.get_value(list_obj, 3, default=None))
Expected Result
Case 1: 3
Case 2: z
Case 3: None
Actual Behavior
Traceback (most recent call last):
File "test.py", line 3, in <module>
print(utils.get_value(lst, 999, default=3))
File ".../site-packages/marshmallow/utils.py", line 108, in get_value
return _get_value_for_key(obj, key, default)
File ".../site-packages/marshmallow/utils.py", line 126, in _get_value_for_key
return getattr(obj, key, default)
TypeError: getattr(): attribute name must be string
Issue Description
When passing an out-of-range
intindex toutils.get_value, aTypeErroris raised instead of returning the provideddefaultvalue. Based on the documentation and function’s behavior instringcases, I’d expect it to fall back to default when the index is invalid. FYI, this issue seems to occur because handlingIndexErrorrequires falling back togetattr(obj, key, default). This logic was introduced in PR #1063 following git blame. I think this issue can be fixed by handling thisTypeErrorto returndefaultvalue. I can make an PR if this change make sense to you.Reproducing Code Example
Expected Result
Actual Behavior