sábado, 1 de noviembre de 2008

Caipirinha and Python tricks

Yes, I don't have anything to blog about. And I know the rule, "If you are not better than the silence, then shut up".
But here I'm been part of the interweb, where everyone show and nobody watch.

Anyways, been doing a lot django development lately (yeah, that's -how- flexible my work is) and since we have to do a lot of things dynamic, I will show you a couple of tricks that might be useful.

First, I have been learning lisp on my free time, and that is why lately my code is all one liners:

if a ? b : c
in python:
( b, c)[ a ]
("bigger", "smaller or equal") [ a <20 ]

dynamic arguments:
function( *a, **b)
function( **{ 'name': 'nico'} )
is the same as: function(name="nico")

django's trick:
Model's OR search:
from django.db.models import Q
model.objects.filter( Q(name="nico") | Q(lastname="waisman") )

COUNT and GROUP BY (undocumented):
Find the names that get more repeated:
c = model.objects.extra( select = {'entry_count': "count(name)"} )
c.query.group_by = ['name']

The information can get for the result object by accesing the "entry_count" fields. This will be unsorted, if you want to get the top 5 then (i wish there were another way, but couldn't find it):
names = sorted( c, lambda x,y: cmp( y.entry_count, x.entry_count) )

Don't you love lambda? Once you get used to the whole map, filter and reduce is like heroin, impossible to quit, unless you get into religion.

Now the Caipirinha part of the post: Next thursday Pablo Solé and I will be flying to the beatiful city of Sao Paulo in Brazil to present at the H2HC conference. Immunity will have a booth, so please came by to said hi so we don't feel lonely :).
We will be doing the NOP certification for the first time in latin america, so if you are around and hungry for stack overflows, contact us!


No hay comentarios: