On May 2, 12:14 pm, Paul McGuire <pt...@austin.rr.com> wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > x = <boolean expression> and True or False > > What is "and True or False" adding to this picture? The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? > > -- Paul
I think it's idiomatic -- that it was written by someone who was deep in thought about actually getting something accomplished, and not thinking at the level of the details. As you're actively *looking* for "x and y or z" I'm sure you'll agree that we've probably all written lots of stuff like: x = <expression> and 'some_prefix' or '' x = <expression> and 42 or 0 x = <expression> and ['Hi, mom!'] or [] When you're in this mode of expression, the only thing that would really trip you up and make it "wrong" is if 'some_prefix' or 42 or ['Hi, mom!'] evaluated to False, and then you get the '', 0, or [] you didn't really want. So I know that, to the extent I was thinking deeply about the low level of what I was writing, my mental energy would be going towards making sure that the second sub-expression evaluated to true. So, if you're mentally operating in this mode, and you want True or False, and you forget, don't think about, or are not cognizant of the fact that bool() is available, it's pretty obvious what the result is going to be. I've probably done it myself a few times, although I would probably have to be *really* lost in thought in order to do it when the underlying sub-expression was boolean to start with. Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list