4

Comparing a string with an int in Python 2.7.2 looks very inconsistent:

x = '12'; y = 3
print x > y      # True
x = 12; y = '3'
print x > y      # False

According to How does Python compare string and int? in Python 3 these will raise an exception. Is there a way to get Python 2 already behave that way? Looking at the__future__I could not figure out if there is such a feature.

Community
  • 1
  • 1
szabgab
  • 6,202
  • 11
  • 50
  • 64
  • hey hope you can find your solution in this question :- http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int – Anurag-Sharma Oct 12 '13 at 07:31
  • 3
    @AnuragSharma: Given that he had that same link in his question, and summarized its answer, I doubt that will help him much. – abarnert Oct 12 '13 at 07:42

2 Answers2

4

No. Your choices are:

  • Write and use wrapper classes that raise on unwanted comparisons.

  • Write and use custom comparison functions in place of the usual operators.

  • Use something like MacroPy to make your custom comparison functions less odious to use.

  • Don't rely on these semantics.

  • Pre-check values before comparing.

  • Use Python 3 when you want Python 3.

abarnert
  • 354,177
  • 51
  • 601
  • 671
2

You can't monkeypatch builtin types (at least not without going to the C source), nor should you. You can only subclass them and have them raise TypeError on illegal comparisons.

This is the correct, if problematic, behavior for Python 2, so the best thing you could do is switch to Python 3 which is more sensible in this and many other regards.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561