mastodon
mastodon

Reputation: 497

Strange python's comparison behaviour

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?

Upvotes: 2

Views: 171

Answers (3)

Mark Byers
Mark Byers

Reputation: 839114

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.

Upvotes: 4

liori
liori

Reputation: 42377

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.

Upvotes: 2

Lie Ryan
Lie Ryan

Reputation: 64933

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

Upvotes: -2

Related Questions