Using slice objects

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Using slice objects

Post by deshipu » Sat Oct 08, 2016 10:01 pm

In Python, when we try to slice our own objects, an instance of slice object is passed to the __getitem__, __setitem__ or __delitem__ methods of that object, and we can detect that and then use the slice.start, slice.stop and slice.step attributes to implement our own operations. There is also a very convenient slice.indices(length) method, that gives us an iterable of positions that should be affected by our operation.

In MicroPython, this seems to be a little different. I can see that I still get a slice object in place of the index, but that object doesn't seem to have any attributes or methods on it, and it's also not subscriptable. I tried the following code:

Code: Select all

>>> a = A()
>>> s = a[0:1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'A' object is not subscriptable
>>> class A:
...     def __getitem__(self, index):
...         return index
...         
...         
... 
>>> a = A()
>>> s = a[0:1]
>>> s
slice(0, 1, None)
>>> s.start
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'slice' object has no attribute 'start'
>>> s.indices(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'slice' object has no attribute 'indices'
>>> dir(s)
[]
>>> s[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'slice' object is not subscriptable
>>>
Any ideas how this is supposed to work?

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: Using slice objects

Post by deshipu » Tue Oct 11, 2016 10:38 am

Answering my own question, for posterity.

Turns out that the ESP8266 build has the slice.start, slice.stop and slice.step attributes disabled by default. They can be enabled by setting MICROPY_PY_BUILTINS_SLICE_ATTRS in the esp8266/mpconfigport.h to 1. I asked if it could be enabled by default.

There is no slice.indices method, because it's only a convenience, and easy to implement in python instead.

Post Reply