From 219c4cc78c34114e88adef54f6294b1cbe254e46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Sat, 15 Feb 2020 18:31:21 +0100 Subject: [PATCH] [formatter] allow for numeric list and string indices --- gallery_dl/util.py | 19 +++++++++++-------- test/test_util.py | 4 ++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index 62f3c5d6..618ab007 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -512,16 +512,19 @@ class Formatter(): for is_attr, key in rest: if is_attr: func = operator.attrgetter - elif ":" in key: - func = operator.itemgetter - start, _, stop = key.partition(":") - stop, _, step = stop.partition(":") - start = int(start) if start else None - stop = int(stop) if stop else None - step = int(step) if step else None - key = slice(start, stop, step) else: func = operator.itemgetter + try: + if ":" in key: + start, _, stop = key.partition(":") + stop, _, step = stop.partition(":") + start = int(start) if start else None + stop = int(stop) if stop else None + step = int(step) if step else None + key = slice(start, stop, step) + except TypeError: + pass # key is an integer + funcs.append(func(key)) return first, funcs diff --git a/test/test_util.py b/test/test_util.py index 91771e8d..b15a4991 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -340,6 +340,10 @@ class TestFormatter(unittest.TestCase): self._run_test("{d[a]|d[b]|d[c]}", "foo") self._run_test("{d[z]|d[y]|d[x]}", "None") + def test_indexing(self): + self._run_test("{l[0]}" , "a") + self._run_test("{a[6]}" , "w") + def test_slicing(self): v = self.kwdict["a"] self._run_test("{a[1:10]}" , v[1:10])