Skip to content

Commit

Permalink
fix: Unable to access nested list property
Browse files Browse the repository at this point in the history
  • Loading branch information
arajkumar committed Mar 12, 2020
1 parent 1fe65dd commit d21182f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions flask_restplus/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ def is_indexable_but_not_string(obj):
return not hasattr(obj, "strip") and hasattr(obj, "__iter__")


def is_integer_indexable(obj):
return isinstance(obj, list) or isinstance(obj, tuple)


def get_value(key, obj, default=None):
'''Helper for pulling a keyed value off various types of objects'''
if isinstance(key, int):
Expand All @@ -66,6 +70,11 @@ def _get_value_for_key(key, obj, default):
return obj[key]
except (IndexError, TypeError, KeyError):
pass
if is_integer_indexable(obj):
try:
return obj[int(key)]
except (IndexError, TypeError, ValueError):
pass
return getattr(obj, key, default)


Expand Down
18 changes: 18 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1379,3 +1379,21 @@ def __getitem__(self, n):

obj = Test('hi')
assert fields.get_value('value', obj) == 'hi'

def test_get_value_int_indexable_list(self):
assert fields.get_value('bar.0', {'bar': [42]}) == 42

def test_get_value_int_indexable_list_with_str(self):
assert fields.get_value('bar.abc', {'bar': [42]}) == None

def test_get_value_int_indexable_nested_list(self):
assert fields.get_value('bar.0.val', {'bar': [{'val': 42}]}) == 42

def test_get_value_int_indexable_tuple_with_str(self):
assert fields.get_value('bar.abc', {'bar': (42, 43)}) == None

def test_get_value_int_indexable_tuple(self):
assert fields.get_value('bar.0', {'bar': (42, 43)}) == 42

def test_get_value_int_indexable_nested_tuple(self):
assert fields.get_value('bar.0.val', {'bar': [{'val': 42}]}) == 42

0 comments on commit d21182f

Please sign in to comment.