0

Just curious if there is a way in Python to compare two objects that are functionally equal, but expressed differently. For example, these two regular expression objects mean the same thing (both would match "5.5" or "5.55" or "5.5555"), but "a" is verbose.

a = regex.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", regex.X)

b = regex.compile(r"\d+\.\d*")

Printing a == b evaluates to False.

  • It is not possible to compare 2 objects which are expressed differently. However, you can compare 2 objects by attributes. (refer https://stackoverflow.com/questions/1227121/compare-object-instances-for-equality-by-their-attributes-in-python) – Mahesh Karia Nov 04 '17 at 04:04
  • Are you asking about regular expression objects specifically or is it a general question. You always have the option of subclassing an object and defining or overwriting its [comparison methods](https://docs.python.org/3/reference/datamodel.html#object.__lt__) to have the behaviour you need/want. – wwii Nov 04 '17 at 04:06
  • 1
    This is actually quite tricky. And in general it's _impossible_ to create an algorithm that can determine whether two programs will return the same result on all inputs. Here's some info on this fascinating topic on [Computer Science SE](https://cs.stackexchange.com/questions/2059/how-do-you-check-if-two-algorithms-return-the-same-result-for-any-input). – PM 2Ring Nov 04 '17 at 04:10
  • 1
    @PM2Ring Yes, but restricting to *regular expressions* it is possible to determine equality. See also [Computer Science SE](https://cs.stackexchange.com/q/12267). – ephemient Nov 04 '17 at 04:50
  • @ephemient Indeed, but I can't resist an opportunity to mention a connection to Turing's Halting Problem. :) – PM 2Ring Nov 04 '17 at 04:52
  • @wwii it's more of a general question, but I just happened to be working with regex's when it came up. – Courtney Pruitt Nov 04 '17 at 05:33
  • @CourtneyPruitt: Since your two regular expressions differ only in their representations, you could use something hacky to compare them: `repr(re.sre_parse.parse(a.pattern, a.flags)) == repr(re.sre_parse.parse(b.pattern, b.flags))`. Note that this cannot compare `\d\d` and `\d{2}`, since they don't parse to the same object. – Blender Nov 04 '17 at 16:23

0 Answers0