Better writing in python

Tim Chase python.list at tim.thechases.com
Wed Oct 24 10:49:10 EDT 2007


> Here is my real code:
> 
> with
> dArguments = {
>   'argName' : {
>     'mandatory' : bool, # True or False
>     [...], # other field we do not care here
>   }
> }
> 
> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if cls.dArguments[arg]['mandatory']:
>     lMandatory.append(arg)
>   else:
>     lOptional.append(arg)
> return (lMandatory, lOptional)

I'm kinda confused, as you're iterating over cls.dArguments, so 
arg appears to be a dictionary (addressable with ['mandatory']), 
but then you're using it (the arg dictionary) as a key into 
cls.dArguments which seems suspect.  I suspect you want to do 
something like

   for arg in cls.dArguments:
     if arg['manditory']:
       lMandatory.append(arg)
     else:
       lOptional.append(arg)
   return (lMandatory, lOptional)

I've done something like this in the past:

   def partition(i, f):
     # can be made into list-comprehensions instead if iters
     return (x for x in i if f(x)), (x for x in i if not f(x))

   odds,evens = partition(xrange(10), lambda x: x & 1)
   print "Odd numbers:"
   for thing in odds: print thing
   print "Even numbers:"
   for thing in evens: print thing

which could be translated in your case to something like

   return partition(cls.dArguments,
     lambda x: x['manditory']
     )

I don't know if you find it "more pythonic" or easier to read 
(which in a way is an aspect of "more pythonic"), but in some 
cases, I find this fits my brain better.

-tkc









More information about the Python-list mailing list