Better writing in python

B

Bruno Desthuilliers

Bjoern Schliessmann a écrit :
Alexandre said:
I'm just wondering, if I could write a in a "better" way this code
[...]
I think there is a better way, but I can't see how...

What's "better" for you? Shorter? More performant? More readable?
Complying with best practice? Closely following a specific
programming paradigm?

I think the OP meant "more pythonic".
 
B

beginner

I'm just wondering, if I could write a in a "better" way this
code
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.append(arg)
else:
lOptional.append(arg)
return (lMandatory, lOptional)
I think there is a better way, but I can't see how...

You can do it shorter, not sure that it also qualifies as better....

d = { True : [] , False : [] }
for arg in cls.arguments:
d[arg == True].append(arg)

return d[True], d[False]

One potential problem here is that 'arg == True' may not be the same as 'if
arg:'. I couldn't come up with a better equivalent expression, maybe one of the
other readers knows more about this?

Albert

d[bool(arg)].append(arg) resolves your concern?
 
A

Alexandre Badez

For a 'python like' look lose the Hungarian notation (even Microsoft
have largely stopped using it)

I wish I could.
But my corporation do not want to apply python.org coding rules
increase the indentation to 4 spaces,

Well, it is in my python file.
I do not do it here, because I'm a bit lazy.
and also get rid of the spurious parentheses around the result.
Thanks

Otherwise it is fine: clear and to the point.
Thanks


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?

And finally thanks again ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top