[Tutor] Misc question about scoping

Hugo Arts hugo.yoshi at gmail.com
Fri Jun 4 16:52:03 CEST 2010


On Fri, Jun 4, 2010 at 2:46 PM, Tino Dai <oberoc at gmail.com> wrote:
>
>         I'm at a point where I can do most things in Python (maybe) ,
> now I'm looking to do them succinctly and elegantly. For instance, I
> had about 10 - 15 lines of code to do this before with a bunch of
> loops and if blocks, I distilled the product down to this:
>
>        answerDict=dict(map(lambda x: (str(x[1]),x[0]),map(lambda x: \
>           x.values(),Answer.objects.filter(fk_questionSet=1). \
>           filter(fk_question=1).values('widgetAnswer').order_by(). \
>           annotate(widgetCount=Count('widgetAnswer')))))
>

I have a distinct feeling that you would simply love a language like lisp.

> So instead of my python code doing the "leg work", I have the Django
> ORM and that underlying DB do the work. Also, I leveraged lambda
> functions and maps to coerce the data in to the right format. Pretty
> cool IMHO. And I turn it over to the group to see if there is any
> improvements or gotchas that I missed.
>

The code is succinct, and it may very well be called elegant in some
sense of the word. I might call it "clever," which in the python
community is not generally meant as a compliment. Readability counts,
you see, and I find that piece of code nigh impossible to read. I
would suggest changing the map calls into generator expressions, and
using a few temporary variables for clarity. That should keep most of
the brevity but increase legibility:

answers = Answer.objects.filter(fk_questionSet=1,
fk_question=1).values('widgetAnswer')
answers = answers.order_by().annotate(widgetCount=Count('widgetAnswer'))
values = (x.values() for x in answers)
answerDict = dict((str(v[1]), v[0]) for v in values)

Disclaimer: i'm not particularly experienced with django, so this
piece of code is quite possibly not the most efficient way to do this,
and may even be incorrect (e.g. I assumed the filter calls could be
collapsed like in sqlAlchemy). However, the rest of my advice should
still apply.

Hugo


More information about the Tutor mailing list