Comparison Style

llanitedave llanitedave at veawb.coop
Thu Apr 25 10:19:04 EDT 2013


On Wednesday, April 24, 2013 10:57:49 PM UTC-7, Chris Angelico wrote:
> On Thu, Apr 25, 2013 at 3:49 PM, llanitedave <llanitedave at veawb.coop> wrote:
> 
> > Given that
> 
> >
> 
> > s = some static value
> 
> > i = a value incremented during a loop
> 
> >
> 
> > I'm used to comparing them as
> 
> >
> 
> > if i == s:
> 
> >     # some code
> 
> >
> 
> > But for some unknown reason I did a switch
> 
> >
> 
> > if s == i:
> 
> >     # same code
> 
> >
> 
> > It didn't seem to make any difference at first glance, so I just got to wondering --
> 
> 
> 
> It won't make any difference in any sort of sane code. If there's any
> 
> situation in which == is not reflexive, something seriously nasty is
> 
> going on.
> 
> 
> 
> > Is there a standard for comparison order?  Is there any kind of performance difference?  Is there even a tradition for one or the other?  Are there any gotchas?
> 
> 
> 
> It's conventional to compare variables to constants, not constants to
> 
> variables (even in C where there's the possibility of mucking up the
> 
> operator, most people still compare variables to constants). I'd
> 
> normally use "i == s" there, treating s as a constant for the purpose
> 
> of the loop. Unless you're deliberately being poetical, language such
> 
> as "Three is the number thou shalt count" is distinctly abnormal, so
> 
> saying "if (5 == i)" is equally awkward. It's nothing major; mostly
> 
> it's like the algebraic convention of putting the more-known elements
> 
> earlier in a term (eg 2πix - 2 is known, 3.14159.... is mostly known,
> 
> i is imaginary but at least it's constant, and x is unknown).
> 
> 



Thanks, Chris.  That's kind of along the lines of what I was thinking.  Visually, the code just looked wrong, and I figure if for no other reasons than readability it's preferable in the traditional way.

It's nice to know, though, that the next time dyslexia strikes it's not necessarily a horrible thing.

> 
> > Do I need to get a hobby?
> 
> 
> 
> I thought programming WAS a hobby?
> 

I meant a safer, easier, and more mainstream hobby, like base jumping or motorcycle aerobatics or something.



More information about the Python-list mailing list