6

I have some nested datastructures, each something like:

[ ('foo', [ {'a':1, 'b':2},
                 {'a':3.3, 'b':7} ]),
  ('bar', [ {'a':4, 'd':'efg', 'e':False} ])   ]

I need to compare these structures, to see if there are any differences. Short of writing a function to explicitly walk the structure, is there an existing library or method of doing this kind of recursive comparison?

Phil H
  • 19,234
  • 7
  • 64
  • 103

3 Answers3

6

The built-in aggregation types (list, tuple, dict, etc.) already support equality and relational comparison. For types you create, you need to implement the rich comparison methods.

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
3

Your example data structures will already do appropriate equality testing, because you are using built-in data types which properly implement __eq__ and __ne__, including recursing into nested values.

If you want to include your own classes, you need to implement both of these methods (note that implementing __eq__ does not imply that if you do a != comparison your __eq__ will be called, you must implement __ne__, too).

Jeffrey Harris
  • 3,292
  • 23
  • 29
0

If I don't need to use the diff within Python itself, I would probably end up hacking it. Convert both to yaml, and run a diff on them. :D