views:

62

answers:

3

I have a sample code looking like this, values (position = 2, object.position = 3) :

    new_position = position
    old_position = object.position    

    logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position))

    if old_position != new_position:
        logging.debug("old position other than new position")
        if new_position > old_position:
            logging.debug("Why am I here ?")

and now the debug:

DEBUG 1. new_position: 2, old_position: 3
DEBUG 2. old position other than new position
DEBUG Why am I here?

What's going on ?

A: 

assuming a sane comparison operator, old_position != new_position is equivalent to old_position < new_position or old_position > new_position

Lie Ryan
+1  A: 

Are you sure old_position and new_position are integers? Any object can be made to print '2' and '3' when using %s... even when they implement comparisons in totally different way.

Try %r instead.

liori
+3  A: 

It's probably because you are comparing different incompatible types (e.g. strings and integers). If so, then the order depends on the alphabetical order of the type names.

>>> '2' > 3
True

This applies to Python 2.x. In Python 3.x this will raise a TypeError instead.

Mark Byers
of course I thought about it jsut after submitting post. thx anyway !
mastodon
@mastodon - IMHO, it's best to always print out `repr` (aka `%r`) rather than (or in addition to) versions converted to strings (aka `str` or `%s) when you're trying to debug things.
Omnifarious