List slicing on Python 2.7

Vlastimil Brom vlastimil.brom at gmail.com
Thu Mar 15 09:57:20 EDT 2018


2018-03-15 12:54 GMT+01:00 Arkadiusz Bulski <arek.bulski at gmail.com>:
> I have a custom class (a lazy list-like container) that needs to support
> slicing. The __getitem__ checks if index is of slice type, and does a list
> comprehension over individual integer indexes. The code works fine on
> Python 3 but fails on 2.7, both CPython and PyPy. The print inside
> __getitem__ doesnt even get executed when its a slice. Does 2.7 have
> different object model, where slices are handled by a different method than
> __getitem__?
>
> The implementation and error log
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
> https://travis-ci.org/construct/construct/jobs/353782126#L887
>
> --
> ~ Arkadiusz Bulski
> --
> https://mail.python.org/mailman/listinfo/python-list

Hi,
it looks like, the older method __getslice__ is still used in python 2.7
cf.:
https://docs.python.org/2/reference/datamodel.html#object.__getslice__

You might need to implement this method in your class as well for
compatibility with python 2.

regards
    vbr



More information about the Python-list mailing list