Better writing in python
J. Clifford Dyer
jcd at sdf.lonestar.org
Wed Oct 24 08:44:52 EDT 2007
On Wed, Oct 24, 2007 at 12:09:40PM -0000, Alexandre Badez wrote regarding Better writing in python:
>
> 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...
>
I assume cls.dArguments is a dict, correct?
`for arg in cls.dArguments` takes each *key* for cls.dArguments and assigns it to arg, so the line 'if arg is True' will test the truth value of each key. I assume (you haven't shown the details here) that your dict looks like this:
cls.dArguments = { 'a': True, 'b': False, 'c': True, 'd': False, '': True, 0: False }
and you want your for loop to do this:
lMandatory == [ 'a', 'c', '' ]
lOptional == [ 'b', 'd', 0 ]
in fact, since it's testing the truth value of the keys, not the values, you will get this:
lMandatory == [ 'a', 'b', 'c', 'd' ]
lOptional == [ '', 0 ]
In no particular order, of course.
Also, `if x is True:` should be written as `if x:`
Actually, come to think of it, what I said above is false, because the string 'a' *is not* the boolean value True, per se: it is *equal to* True. So if you change `if x is True:` to `if x == True:` then everything I said above holds true, including that you should change `if x == True:` to `if x:`
As it stands, the only key in your dict that has a snowball's chance in key largo of being marked as mandatory is the boolean value True itself.
Cheers,
Cliff
More information about the Python-list
mailing list