deepdiff icon indicating copy to clipboard operation
deepdiff copied to clipboard

Possible enhancement/alternate view? - "Flat tree" mode

Open techdragon opened this issue 6 years ago • 2 comments

I often find myself doing something like this

  1. Diff two objects,
  2. Do something if a key has changed. This may or may not care what has changed about the key

I've done it so many times I've boiled down to a pattern, where I do something like this:

_diff = deepdiff.DeepDiff(first_object, second_object)
first_level_changes = itertools.chain.from_iterable([_diff[_key] for _key in deepdiff.model.REPORT_KEYS if _key in _diff])

or

_diff = deepdiff.DeepDiff(first_object, second_object)
first_level_changes = {
    _k[6:-2]: _v for _k, _v in collections.ChainMap(*[_diff[_key] for _key in REPORT_KEYS if _key in diff]).items()
}
  1. if """root['name_of_key_i_care_about']""" in first_level_changes: and then I do stuff in the conditional here.

But each time I do this, I wonder if there is a better way. So I'm asking here, as either a usage question or a feature request.

DeepDiff is fast enough that I wind up using it a LOT (its a fantastic library), so I don't even mind if the way would involve a subclass with some overriding. It would just mean I setup my 'special diff' and happily use that in my code.

Intuitively it feels like this data exists in some form (even if its just an implicit/transient form) during the construction of the diff tree, before being thrown away, and then I have to 'waste time' rebuilding it after the diff is done with my list comprehension and itertools trickery. Is there a better way?

techdragon avatar May 28 '19 11:05 techdragon

Hi @techdragon Let me see if I understand what you want. You care about some key i.e. ('root['x'][1]). And you want to know whenever that key appears in the diff results?

seperman avatar Jul 12 '19 23:07 seperman

Effectively yes. It the very least it would be useful to have a shortcut/shorthand for "has anything about $keyName changed" Even better would be a more generalised form "has anything about changed." Your example "root['x'][1]" looks more like you're already thinking in terms of a generalised version so thats good for me :smile:

So yes that is pretty much what I want. Since the diff object is constructed by detecting changes, it would be more efficient if they were somehow retained and then I could just perform some check on the diff diffObject.changed("root['x'][1]") and get back a True/False.

If keeping this information and adding the function doesn't fit with the intended use of diff, I'm happy to extend and use a subclass like the Tree output does. (And would appreciate some guidance on that)

techdragon avatar Jul 15 '19 03:07 techdragon