[Tutor] Quick question

Jerry Hill malaclypse2 at gmail.com
Fri Sep 21 21:44:33 CEST 2007


On 9/21/07, Tino Dai <tinoloc at gmail.com> wrote:
> Is there a more pythonic way of doing this:
>
>   if queuePacket.has_key('procSeq') and \
>   queuePacket.has_key('opacSeq') and \
>   queuePacket.has_key('keySeq') and \
>   len(queuePacket['procSeq']) == 0 and \
>   len(queuePacket['opacSeq']) == 0 and \
>  len(queuePacket['keySeq']) == 0:

Assuming we're talking about Python 2.5 or greater I find the
following pretty readable:

all(queuePacket.has_key(k) for k in ('procSeq', 'opacSeq', 'keySeq')) and \
all(len(queuePacket[k])==0 for k in ('procSeq', 'opacSeq', 'keySeq'))

If you're not familiar with how those work, they use generator
expressions, which are very similar to list comprehensions.  See PEP
289 [1] for more information on generator expressions, and either the
tutorial [2] or PEP 202 [3] for more on list comprehensions.

1: http://www.python.org/dev/peps/pep-0289/
2: http://docs.python.org/tut/node7.html#SECTION007140000000000000000
3: http://www.python.org/dev/peps/pep-0202/

-- 
Jerry


More information about the Tutor mailing list