Skip to content

utils.get_value raise TypeError with out-of-range int index #2893

@thanhlecongg

Description

@thanhlecongg

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions