diff options
author | Nicko van Someren <nicko@nicko.org> | 2019-11-16 17:07:11 -0700 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2019-12-28 23:55:15 +1100 |
commit | 4c93955b7b4d3d860aed1551ca6231ac4e388e69 (patch) | |
tree | 33d4e13a6076d847f98da761febeb5f745e94a3c /tests/basics/slice_indices.py | |
parent | 007a704d82f07d1482dae6f265fecf5710266767 (diff) | |
download | micropython-4c93955b7b4d3d860aed1551ca6231ac4e388e69.tar.gz micropython-4c93955b7b4d3d860aed1551ca6231ac4e388e69.zip |
py/objslice: Add support for indices() method on slice objects.
Instances of the slice class are passed to __getitem__() on objects when
the user indexes them with a slice. In practice the majority of the time
(other than passing it on untouched) is to work out what the slice means in
the context of an array dimension of a particular length. Since Python 2.3
there has been a method on the slice class, indices(), that takes a
dimension length and returns the real start, stop and step, accounting for
missing or negative values in the slice spec. This commit implements such
a indices() method on the slice class.
It is configurable at compile-time via MICROPY_PY_BUILTINS_SLICE_INDICES,
disabled by default, enabled on unix, stm32 and esp32 ports.
This commit also adds new tests for slice indices and for slicing unicode
strings.
Diffstat (limited to 'tests/basics/slice_indices.py')
-rw-r--r-- | tests/basics/slice_indices.py | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/tests/basics/slice_indices.py b/tests/basics/slice_indices.py new file mode 100644 index 0000000000..b7f439ccca --- /dev/null +++ b/tests/basics/slice_indices.py @@ -0,0 +1,27 @@ +# Test builtin slice indices resolution + +# A class that returns an item key +class A: + def __getitem__(self, idx): + return idx + +# Make sure that we have slices and .indices() +try: + A()[2:5].indices(10) +except: + print("SKIP") + raise SystemExit + +print(A()[:].indices(10)) +print(A()[2:].indices(10)) +print(A()[:7].indices(10)) +print(A()[2:7].indices(10)) +print(A()[2:7:2].indices(10)) +print(A()[2:7:-2].indices(10)) +print(A()[7:2:2].indices(10)) +print(A()[7:2:-2].indices(10)) + +print(A()[2:7:2].indices(5)) +print(A()[2:7:-2].indices(5)) +print(A()[7:2:2].indices(5)) +print(A()[7:2:-2].indices(5)) |