sábado, 10 de noviembre de 2012

Slicing a list when you only know half the slice

I wanted a function that 'crawled' all the users in a django queryset so the whole problem was the old, how to work on a whole list but in small chunks. I needed this for performance reasons because it was expensive to try to generate all the user's thumbnails at once and expecting that nothing would go wrong was insane. Apparently facebook servers are not as stable as you think.
So less bla bla y more code:

    def fanfunders_subset(self,start=None,end=None):
        return UserProfile.objects.fanfunders()[start:end]


So i would call this function like this in a loop
    fanfunders_subset(0,10)
    # and in the next iteration
    fanfunders_subset(10,20)



At this moment i was thankful python lists end in -1, so slicing [0,10] will get you the first number the decond and up to the ninth, if it didnt ended in -1 i would have to do something akward like [0,10] [11,20] [21,30] and that looks ugly.

So what was the trick? oh yeah, you can slice with None! in this context

    >>> list[0,None] == list[0,-1]
        True

And then

    >>> list[None,-1] == list[0,-1]
        True

So you can only give on the two arguments to the function and it will return the correct slice, yeah this trick is more for that, to get this flexible interface, sometimes you want a chunk from the end of the list and sometimes you want it from the begining and somethings you want in the middle, lots of cases are covered safely here it just looks a little weird if you see this at first, thats why i wrote this post :P So more people know it and you don't judge me for using weird tricks in Python.

No hay comentarios:

Publicar un comentario