Better writing in python

Duncan Booth duncan.booth at invalid.invalid
Wed Oct 24 15:46:50 CEST 2007


Alexandre Badez <alexandre.badez at gmail.com> wrote:

> Thanks for your try Cliff, I was very confused :P
> More over I made some mistake when I post (to make it easiest).
> 
> 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)
> 
> So, as you see, we agree each other about "if bool" or "if bool is
> True" ;)
> 
> So, my question was how to give it a better 'python like' look ?
> Any idea ?
> 
> 

For a 'python like' look lose the Hungarian notation (even Microsoft 
have largely stopped using it), increase the indentation to 4 spaces, 
and also get rid of the spurious parentheses around the result. 
Otherwise it is fine: clear and to the point.

If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
    (m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
    action[bool(cls.dArguments[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?



More information about the Python-list mailing list