Skip to content

Instantly share code, notes, and snippets.

@asfaltboy
Last active July 19, 2016 08:57
Show Gist options
  • Save asfaltboy/53043124bc956d107cb1 to your computer and use it in GitHub Desktop.
Save asfaltboy/53043124bc956d107cb1 to your computer and use it in GitHub Desktop.
deepdiff ipython magic command
from IPython.core.magic import register_line_magic
from IPython.core.getipython import get_ipython
@register_line_magic
def diff(line):
"""
## Reasoning
When you compare dicts a lot, [deepdiff][1] comes in very useful.
This magic command saves a few steps to "deep compare" objects.
## Installation
Drop this file into the ~/.ipython/<your-profile>/startup directory,
or use the install magic:
In [1]:
## Usage
inside iPython shell (use a single percent sign!)
In [1]: a = dict(fields={'foo': 'bar', 'zoop': 'bam'})
In [2]: b = dict(fields={'foo': 'bar2', 'zoo': 'balm'})
In [3]: %%diff a b
Out[8]:
{'dic_item_added': ["root['fields']['zoo']"],
'dic_item_removed': ["root['fields']['zoop']"],
'values_changed': ["root['fields']['foo']:\n--- \n+++ \n@@ -1 +1 @@\n-bar\n+bar2"]}
[1]: https://github.com/seperman/deepdiff
"""
try:
from deepdiff import DeepDiff
except ImportError:
raise Exception("Cannot use diff magic without deepdiff")
params = line.split()
assert len(params) == 2, "Must be passed exactly 2 parameters"
ip = get_ipython()
args = tuple(ip.user_ns[param] for param in params)
res = DeepDiff(*args)
if hasattr(res, 'changes'):
return res.changes
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment