[python-nl] getitem with slices??

Dirkjan Ochtman dirkjan at ochtman.nl
Thu Apr 19 19:28:58 CEST 2012


On Thu, Apr 19, 2012 at 16:51, Pepijn de Vos <pepijndevos at gmail.com> wrote:
> No explanation, but this is one aspect of "pythonic" that has been bothering me of late.
>
> The general consensus is that you should use duck typing, and in general not have items of a different type in one place.
>
> So the "pythonic" solution would be to have getslice, I would think, but if that is not available, the "pythonic" thing to do is something like:
>
> try:
>    foo.slicy_thing()
> except TypeError:
>    foo.number_thing()
>
> IMO, exceptions are for exceptional occasions, not for disguised if statements. But, that's the way Python seems to work.

I'm not sure what you're getting at here, but I'm pretty sure having
an isinstance() call here and there is perfectly Pythonic. Look Before
You Leap has its place, just like Easier to Ask Forgiveness than
Permission.

I googled and annotated the source a bit and found mailing list
threads from when it was deprecated, but there was no clear rationale.
Still, it's been deprecated a long time, this happened in July 2000,
so the feeling that this is something recent isn't really justified.

Also, since __getitem__() could just as easily return a sequence as a
single item, it seems like there isn't really much point to having
separate things for this, and I find the solution with passing slice()
objects to __getitem__() quite elegant.

Cheers,

Dirkjan


More information about the Python-nl mailing list