### Build project with uv Source: https://github.com/qlustered/deepdiff/blob/master/README.md Build the project using uv after installing dependencies. ```bash uv build ``` -------------------------------- ### Install DeepDiff from PyPi Source: https://github.com/qlustered/deepdiff/blob/master/README.md Use this command to install the core DeepDiff library. ```bash pip install deepdiff ``` -------------------------------- ### Install DeepDiff with performance optimizations Source: https://github.com/qlustered/deepdiff/blob/master/README.md Install DeepDiff with the 'optimize' extra for improved performance, particularly with JSON serialization. ```bash pip install "deepdiff[optimize]" ``` -------------------------------- ### Install DeepDiff with CLI support Source: https://github.com/qlustered/deepdiff/blob/master/README.md Install DeepDiff with the 'cli' extra to enable command-line usage. ```bash pip install "deepdiff[cli]" ``` -------------------------------- ### Tree View Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst An example of the 'tree' view, which allows traversal of the comparison results and provides access to specific change details. ```python >>> tree = DeepDiff(t1, t2, view='tree') >>> tree {'set_item_removed': [, ], 'set_item_added': []} ``` ```python >>> tree['set_item_added'][0] ``` ```python >>> tree['set_item_added'][0].t2 3 ``` -------------------------------- ### Install Xcode Command Line Tools on MacOS Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/troubleshoot.rst On MacOS Mojave, users may need to install Xcode command line tools to resolve Murmur3 installation issues. This command initiates the installation process. ```bash xcode-select --install ``` -------------------------------- ### Install DeepDiff with Development Dependencies Source: https://github.com/qlustered/deepdiff/blob/master/AGENTS.md Installs the DeepDiff library with all necessary development dependencies. It is recommended to use 'uv' for package management. ```bash # Install with all development dependencies uv pip install -e ".[cli,coverage,dev,docs,static,test]" # OR using uv (recommended) uv sync --all-extras ``` -------------------------------- ### Install DeepDiff dependencies with uv Source: https://github.com/qlustered/deepdiff/blob/master/README.md Use uv to synchronize all dependencies and extras for local development. ```bash uv sync --all-extras ``` -------------------------------- ### Basic Tree View Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst Demonstrates the basic usage of the 'tree' view to show changed values between two simple objects. ```python >>> print(DeepDiff(t1, t2, view='tree')) {'values_changed': []} ``` -------------------------------- ### Install Murmur3 Hashing Library Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/troubleshoot.rst Install the Murmur3 library using pip. This is a prerequisite for DeepDiff versions prior to 5.2.0 if hashing is required. ```bash pip install mmh3 ``` -------------------------------- ### Include Object Callback Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/ignore_types_or_values.rst Shows how to include objects based on a callback function. The object is included if the function returns True for it. ```python def include_obj_callback(obj, path): return True if "include" in path or isinstance(obj, int) else False t1 = {"x": 10, "y": "b", "z": "c", "include_me": "a"} t2 = {"x": 10, "y": "b", "z": "c", "include_me": "b"} DeepDiff(t1, t2, include_obj_callback=include_obj_callback) ``` -------------------------------- ### 2D Group By with DeepDiff Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/basics.rst This example shows how to use a list of keys for 'group_by' to perform a 2D grouping on a list of dictionaries. ```python from pprint import pprint from deepdiff import DeepDiff t1 = [ {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'}, {'id': 'BB', 'name': 'James', 'last_name': 'Blue'}, {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red'}, {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'}, ] t2 = [ {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'}, {'id': 'BB', 'name': 'James', 'last_name': 'Brown'}, {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'}, ] diff = DeepDiff(t1, t2, group_by=['id', 'name']) pprint(diff) ``` -------------------------------- ### Callable Group By Example Source: https://github.com/qlustered/deepdiff/blob/master/docs/basics.rst Demonstrates using a callable function for grouping complex nested dictionary structures. ```python >>> from deepdiff import DeepDiff >>> >>> t1 = [ ... {'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}, ... {'id': 'BB', 'demographics': {'names': {'first': 'James', 'middle': 'Joyce', 'last': 'Blue'}}, ... {'id': 'CC', 'demographics': {'names': {'first': 'Mike', 'middle': 'Mark', 'last': 'Apple'}}, ... ] >>> >>> t2 = [ ... {'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}, ... ``` -------------------------------- ### Install DeepDiff dependencies with pip Source: https://github.com/qlustered/deepdiff/blob/master/README.md Use pip to install DeepDiff in editable mode with development, testing, and documentation extras. ```bash pip install -e ".[cli,coverage,dev,docs,static,test]" ``` -------------------------------- ### Max Passes Example Source: https://github.com/qlustered/deepdiff/blob/master/docs/ignore_order.rst Illustrates the use of the max_passes parameter to limit the number of comparison passes when ignore_order is True. This example is truncated due to the nature of the source. ```python from pprint import pprint from deepdiff import DeepDiff t1 = [ { 'key3': [[[[[1, 2, 4, 5]]]]], 'key4': [7, 8], }, { 'key5': 'val5', 'key6': 'val6', }, ] t2 = [ { 'key5': 'CHANGE', 'key6': 'val6', }, { 'key3': [[[[[1, 3, 5, 4]]]]], 'key4': [7, 8], }, ] ``` -------------------------------- ### Example of Patched YAML File Source: https://github.com/qlustered/deepdiff/blob/master/docs/commandline.rst Illustrates the content of a YAML file after a patch has been successfully applied. Note that the original file formatting may be altered during the patching process. ```yaml - first_name: Joe last_name: Nobody zip: 90011 - first_name: Jack last_name: Doit zip: 22222 - first_name: Sara last_name: Stanley zip: 90002 ``` -------------------------------- ### DeepDiff Text View Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst Demonstrates the default text view of DeepDiff, showing added and removed dictionary items. The output is a dictionary where values are sets of strings representing the diff. ```python >>> from decimal import Decimal >>> from deepdiff import DeepDiff >>> t1 = {1:1, 3:3, 4:4} >>> t2 = {1:1, 3:3, 5:5, 6:6} >>> ddiff = DeepDiff(t1, t2) >>> print(ddiff) {'dictionary_item_added': [root[5], root[6]], 'dictionary_item_removed': [root[4]]} ``` -------------------------------- ### Truncate Datetime Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/ignore_types_or_values.rst Demonstrates truncating datetime objects to a specified precision (e.g., 'minute') before comparison. This is useful for ignoring minor time differences. ```python import datetime from deepdiff import DeepDiff d1 = {'a': datetime.datetime(2020, 5, 17, 22, 15, 34, 913070)} d2 = {'a': datetime.datetime(2020, 5, 17, 22, 15, 39, 296583)} DeepDiff(d1, d2, truncate_datetime='minute') ``` -------------------------------- ### Navigating Added Items in Tree View Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst Shows how to access and navigate added items within an iterable in the tree view. The example demonstrates accessing the added item, its parent, and its path. ```python >>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}} >>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}} >>> ddiff = DeepDiff(t1, t2, view='tree') >>> pprint(ddiff, indent = 2) { 'iterable_item_added': [], 'values_changed': [, ]} >>> >>> # Note that iterable_item_added is a set with one item. >>> # So in order to get that one item from it, we can do: >>> >>> (added,) = ddiff['iterable_item_added'] >>> added >>> added.up.up >>> added.up.up.path() 'root[4]' >>> added.up.up.path(output_format='list') # gives you the list of keys and attributes that make up the path [4] >>> added.up.up.down >>> >>> # going up twice and then down twice gives you the same node in the tree: >>> added.up.up.down.down == added True ``` -------------------------------- ### No Cache and No NumPy Performance Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/optimizations.rst Shows the performance statistics when diffing lists of numbers without caching and without NumPy installed. This configuration resulted in a significantly longer diff time. ```text {'PASSES COUNT': 1, 'DIFF COUNT': 439944, 'DISTANCE CACHE HIT COUNT': 0, 'MAX PASS LIMIT REACHED': False, 'MAX DIFF LIMIT REACHED': False, 'DURATION SEC': 30} ``` -------------------------------- ### Search using regular expressions Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/search_doc.rst Utilize regular expressions to find patterns within nested data structures. This example searches for strings starting with 'some'. ```python obj = ["something here", {"long": "somewhere", "someone": 2, 0: 0, "somewhere": "around"}] ds = obj | grep("some.*", use_regexp=True) pprint(ds, indent=2) ``` -------------------------------- ### Build DeepDiff Documentation Source: https://github.com/qlustered/deepdiff/blob/master/docs/CLAUDE.md Navigate to the docs directory, activate the virtual environment, and run the build script. The output is configured via .env and placed in a versioned directory. ```bash cd docs && source ~/.venvs/deep/bin/activate && python buildme.py ``` -------------------------------- ### Comparing Named Tuples with DeepDiff Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst Shows a basic example of comparing two named tuples using DeepDiff. This snippet highlights the initial setup for comparing custom objects. ```python >>> from collections import namedtuple >>> Point = namedtuple('Point', ['x', 'y']) >>> t1 = Point(x=11, y=22) >>> t2 = Point(x=11, y=23) ``` -------------------------------- ### Pretty Output with Custom Prefix String Source: https://github.com/qlustered/deepdiff/blob/master/docs/view.rst Demonstrates using a string prefix with the pretty() method for formatted output. ```python from deepdiff import DeepDiff t1={1,2,4} t2={2,3} print(DeepDiff(t1, t2).pretty(prefix='Diff: ')) ``` -------------------------------- ### Custom Operator to Ignore GUIDs Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/custom.rst Implements a custom operator that ignores differences in GUIDs within strings. This operator is useful when exact GUID values are not important, but the structure of the string should be compared. ```python import re from typing import Any from deepdiff import DeepDiff from deepdiff.operator import BaseOperatorPlus d1 = { "Name": "SUB_OBJECT_FILES", "Values": { "Value": [ "{f254498b-b752-4f35-bef5-6f1844b61eb7}", "{7fb2a550-1849-45c0-b273-9aa5e4eb9f2b}", "{a9cbecc0-21dc-49ce-8b2c-d36352dae139}" ] } } d2 = { "Name": "SUB_OBJECT_FILES", "Values": { "Value": [ "{e5d18917-1a2c-4abe-b601-8ec002629953}", "{ea71ba1f-1339-4fae-bc28-a9ce9b8a8c67}", "{66bb6192-9cd2-4074-8be1-f2ac52877c70}", ] } } class RemoveGUIDsOperator(BaseOperatorPlus): _pattern = r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" _substitute = "guid" def match(self, level) -> bool: return isinstance(level.t1, str) and isinstance(level.t2, str) @classmethod def _remove_pattern(cls, t: str): return re.sub(cls._pattern, cls._substitute, t) def give_up_diffing(self, level, diff_instance): t1 = self._remove_pattern(level.t1) t2 = self._remove_pattern(level.t2) return t1 == t2 def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any: """ Used for ignore_order=True """ if isinstance(obj, str): return self._remove_pattern(obj) return obj operator = RemoveGUIDsOperator() diff1 = DeepDiff(d1, d2, custom_operators=[operator], log_stacktrace=True) diff1 diff2 = DeepDiff(d1, d2, ignore_order=True, custom_operators=[operator], log_stacktrace=True) diff2 ``` -------------------------------- ### Enable and View Progress Logs Source: https://github.com/qlustered/deepdiff/blob/master/docs/stats.rst Demonstrates how to enable progress logging by setting log_frequency_in_sec and shows the expected log output including duration and stats. ```python >>> DeepDiff(t1, t2, log_frequency_in_sec=1) INFO:deepdiff.diff:DeepDiff 1 seconds in progress. Pass #1634, Diff #8005 INFO:deepdiff.diff:DeepDiff 2 seconds in progress. Pass #3319, Diff #16148 INFO:deepdiff.diff:stats {'PASSES COUNT': 3960, 'DIFF COUNT': 19469, 'DISTANCE CACHE HIT COUNT': 11847, 'MAX PASS LIMIT REACHED': False, 'MAX DIFF LIMIT REACHED': False, 'DURATION SEC': 2} ``` -------------------------------- ### Pretty Print with Prefix String Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/view.rst Shows how to use the `prefix` parameter with a string to prepend text to each line of the `pretty()` output, useful for logging. ```python >>> from deepdiff import DeepDiff >>> t1={1,2,4} >>> t2={2,3} >>> print(DeepDiff(t1, t2).pretty(prefix='Diff: ')) Diff: Item root[3] added to set. Diff: Item root[4] removed from set. Diff: Item root[1] removed from set. ``` -------------------------------- ### Run Single Test File Source: https://github.com/qlustered/deepdiff/blob/master/AGENTS.md Executes tests from a specific file. Remember to activate the virtual environment first. ```bash source ~/.venvs/deep/bin/activate && pytest tests/test_diff_text.py ``` -------------------------------- ### Using Pre-computed Hashes Source: https://github.com/qlustered/deepdiff/blob/master/docs/deephash_doc.rst Demonstrates how to provide a dictionary of pre-computed hashes to reuse them for identical objects encountered during hashing. ```python obj1 = {"a": 1} obj2 = {"a": 1} hashes_dict = {id(obj1): DeepHash(obj1)} print(DeepHash(obj2, hashes=hashes_dict)) ``` -------------------------------- ### Pretty Output with Callable Prefix Source: https://github.com/qlustered/deepdiff/blob/master/docs/view.rst Shows how to use a callable function as a prefix for pretty() output, dynamically generating prefixes. ```python from deepdiff import DeepDiff t1={1,2,4} t2={2,3} def callback(**kwargs): kwargs['diff']._diff_count = 1 + getattr(kwargs['diff'], '_diff_count', 0) return f"Diff #{kwargs['diff']._diff_count}: " print(DeepDiff(t1, t2).pretty(prefix=callback)) ``` -------------------------------- ### DeepHash with Numeric Type Changes (Example 2) Source: https://github.com/qlustered/deepdiff/blob/master/docs/deephash_doc.rst Provides another example of ignoring numeric type changes, showing that `DeepHash(t1)[1]` and `DeepHash(t1, ignore_numeric_type_changes=True)[1.0]` produce the same hash when numeric type changes are ignored. ```python from deepdiff import DeepHash t1 = {1: 1, 2: 2.22} print(DeepHash(t1)[1]) ``` ```python from deepdiff import DeepHash t1 = {1: 1, 2: 2.22} print(DeepHash(t1, ignore_numeric_type_changes=True)[1] == DeepHash(t1, ignore_numeric_type_changes=True)[1.0]) ``` -------------------------------- ### Math Epsilon for Fraction Comparison Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/numbers.rst Demonstrates using math_epsilon to set a tolerance for comparing Fraction values. Fractions within this tolerance are treated as equal. ```python from fractions import Fraction d1 = {"a": Fraction(7175, 1000)} d2 = {"a": Fraction(7174, 1000)} DeepDiff(d1, d2, math_epsilon=0.01) ``` -------------------------------- ### Detecting Removed List Items Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/basics.rst This example demonstrates how DeepDiff identifies items that have been removed from a list. ```python t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}} t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}} ddiff = DeepDiff(t1, t2) pprint (ddiff, indent = 2) ``` -------------------------------- ### Delta Commandline Help Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/index.rst Display help information for the Delta command-line tool. ```bash $ deep patch --help ``` -------------------------------- ### Use uv pip for Package Management Source: https://github.com/qlustered/deepdiff/blob/master/CLAUDE.md Emphasizes the use of 'uv pip' instead of the standard 'pip' for package management within this project, as 'uv' is the preferred tool for dependency management. ```bash uv pip install -e .[cli,coverage,dev,docs,static,test] ``` -------------------------------- ### Serialize Delta to File and Load using delta_path Source: https://github.com/qlustered/deepdiff/blob/master/docs/delta.rst Illustrates saving a Delta object to a file using dump() and then loading it back using the delta_path parameter. ```python from deepdiff import DeepDiff, Delta from pprint import pprint t1 = [1, 2, 3] t2 = ['a', 2, 3, 4] diff = DeepDiff(t1, t2) delta = Delta(diff, bidirectional=True) with open('/tmp/delta1', 'wb') as dump_file: delta.dump(dump_file) delta3 = Delta(delta_path='/tmp/delta1') t1 + delta3 == t2 ``` -------------------------------- ### Get String Representation Before Hashing Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Retrieve the string representation of an object before it's hashed by setting apply_hash to False. ```python obj = {"a": 1, "b": 2} print(DeepHash(obj, apply_hash=False)) ``` -------------------------------- ### Get Deep Distance for Lists Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deep_distance.rst Calculates the deep distance between two lists. The distance is a value between 0 and 1. ```python from deepdiff import DeepDiff DeepDiff([1], [1], get_deep_distance=True) ``` ```python from deepdiff import DeepDiff DeepDiff([1], [1, 2], get_deep_distance=True) ``` ```python from deepdiff import DeepDiff DeepDiff([1], [1, 2, 3], get_deep_distance=True) ``` -------------------------------- ### Get Deep Distance for Numbers Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deep_distance.rst Calculates the deep distance between two numbers. The distance is a value between 0 and 1. ```python from deepdiff import DeepDiff DeepDiff(10.0, 10.1, get_deep_distance=True) ``` ```python from deepdiff import DeepDiff DeepDiff(10.0, 100.1, get_deep_distance=True) ``` ```python from deepdiff import DeepDiff DeepDiff(10.0, 1000.1, get_deep_distance=True) ``` -------------------------------- ### Deep Grep Command Help Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/commandline.rst Displays the available options and usage for the deep grep command. ```bash $ deep grep --help ``` -------------------------------- ### Cache Size 5000 Performance Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/optimizations.rst Demonstrates the performance impact of setting cache_size to 5000 and disabling cache tuning. This configuration resulted in a diff calculation under 1 second with moderate memory usage. ```text {'PASSES COUNT': 1486, 'DIFF COUNT': 6637, 'DISTANCE CACHE HIT COUNT': 3440, 'MAX PASS LIMIT REACHED': False, 'MAX DIFF LIMIT REACHED': False, 'DURATION SEC': 0} ``` -------------------------------- ### Deep Diff Command Help Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/commandline.rst Displays the available options and usage for the deep diff command. ```bash $ deep diff --help ``` -------------------------------- ### DeepHash with custom_number_to_string_func Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Allows defining a custom function to convert numbers to strings before hashing. This example makes numbers below 100 hash the same. ```python from deepdiff import DeepHash from deepdiff.helper import number_to_string def custom_number_to_string(number, *args, **kwargs): number = 100 if number < 100 else number return number_to_string(number, *args, **kwargs) t1 = [10, 12, 100000] t2 = [50, 63, 100021] t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="e", number_to_string_func=custom_number_to_string) t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="e", number_to_string_func=custom_number_to_string) print(t1_hash[t1] == t2_hash[t2]) ``` -------------------------------- ### DeepHash with number_format_notation='f' Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Uses fixed-point notation for numbers when hashing. This example shows two numbers that hash differently with this setting. ```python from deepdiff import DeepHash t1=10002 t2=10004 t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="f") t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="f") print(t1_hash[t1] == t2_hash[t2]) ``` -------------------------------- ### Dump Delta to File and Load from Path Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/delta.rst Demonstrates dumping a Delta object to a file using dump() and then loading it back using the delta_path parameter. This is an alternative to using dumps() for file-based persistence. ```python from deepdiff import DeepDiff, Delta t1 = [1, 2, 3] t2 = ['a', 2, 3, 4] diff = DeepDiff(t1, t2) delta = Delta(diff, bidirectional=True) with open('/tmp/delta1', 'wb') as dump_file: delta.dump(dump_file) delta3 = Delta(delta_path='/tmp/delta1') t1 + delta3 == t2 ``` -------------------------------- ### Detecting Type Changes in Dictionary Items Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/basics.rst This example shows how DeepDiff identifies when the type of a dictionary item has changed between two objects. ```python t1 = {1:1, 2:2, 3:3} t2 = {1:1, 2:"2", 3:3} pprint(DeepDiff(t1, t2), indent=2) ``` -------------------------------- ### DeepDiff Type Change Example Source: https://github.com/qlustered/deepdiff/blob/master/docs/ignore_types_or_values.rst Demonstrates a type change between a list and a string. Use verbose_level=0 to simplify the output when only type changes matter. ```python t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}} t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}} ddiff = DeepDiff(t1, t2) pprint (ddiff, indent = 2) ``` ```python t1 = {1:1, 2:2, 3:3} t2 = {1:1, 2:"2", 3:3} pprint(DeepDiff(t1, t2, verbose_level=0), indent=2) ``` -------------------------------- ### Dumping and Loading Delta with Safe Imports Source: https://github.com/qlustered/deepdiff/blob/master/docs/delta.rst Demonstrates how to dump a Delta object to a string and then load it, specifying custom modules that are safe to import. ```python from deepdiff import DeepDiff, Delta t1 = [1, 2, [3, 5, 6]] t2 = [2, 3, [3, 6, 8]] diff = DeepDiff(t1, t2) delta = Delta(diff) dump = delta.dumps() delta = Delta(dump, safe_to_import={'mypackage.mymodule'}) ``` -------------------------------- ### DeepHash with number_format_notation='e' Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Uses scientific notation for numbers when hashing. This example shows two numbers that hash the same with this setting and significant digits. ```python from deepdiff import DeepHash t1=10002 t2=10004 # Now we use the scientific notation t1_hash = DeepHash(t1, significant_digits=3, number_format_notation="e") t2_hash = DeepHash(t2, significant_digits=3, number_format_notation="e") print(t1_hash[t1] == t2_hash[t2]) ``` -------------------------------- ### Basic DeepHash Usage Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Demonstrates how to use DeepHash to get the hash of a dictionary and its contents. The hash of the object itself is retrieved by indexing the result with the object. ```python from deepdiff import DeepHash obj = {1: 2, 'a': 'b'} hashes = DeepHash(obj) hashes[obj] ``` -------------------------------- ### Ignore String to None and Bytes Comparison Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/ignore_types_or_values.rst Example of ignoring type changes between string, None, and bytes using values instead of types in `ignore_type_in_groups`. ```python from deepdiff import DeepDiff import datetime t1 = [1, 2, 3, 'a', None] t2 = [1.0, 2.0, 3.3, b'a', 'hello'] DeepDiff(t1, t2, ignore_type_in_groups=[(1, 1.0), (None, str, bytes)]) ``` -------------------------------- ### Delta Mutation Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/delta.rst Illustrates the `mutate` parameter for applying deltas. When `mutate=True`, the original object is modified in place. This is not always successful with immutable types. ```python t1 = [1, 2, [3, 5, 6]] t2 = [2, 3, [3, 6, 8]] diff = DeepDiff(t1, t2, ignore_order=True, report_repetition=True) delta = Delta(diff) t3 = ["a", 2, [3, "b", "c"]] t3 + delta ['a', 2, [3, 'b', 'c']] delta2 = Delta(diff, mutate=True) t3 + delta2 [3, 2, [3, 8, 'c']] t3 [3, 2, [3, 8, 'c']] ``` -------------------------------- ### Deep Extract Command Help Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/commandline.rst Displays the available options and usage for the deep extract command. ```bash $ deep extract --help ``` -------------------------------- ### Custom Operator Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/custom.rst Demonstrates the use of a custom operator to compare elements within nested lists. The custom operator is applied when initializing DeepDiff. ```python from deepdiff import DeepDiff class MyOperator: def __init__(self): self.custom_operators = { 'MyOperator': self.compare } def compare(self, value1, value2): return value1 == value2 def give_up_diffing(self, level, diff_instance) -> bool: return any(diff_instance.tree.values()) t1 = [[1, 2], [3, 4], [5, 6]] t2 = [[1, 3], [3, 5], [5, 7]] DeepDiff(t1, t2, custom_operators=[ MyOperator() ]) ``` -------------------------------- ### Loading Delta from a File Path Source: https://github.com/qlustered/deepdiff/blob/master/docs/delta.rst Demonstrates how to load a serialized Delta object from a file path. ```APIDOC ## Loading Delta from a File Path ### Description This shows how to save a Delta object to a file and then load it back using the `delta_path` parameter. ### Method ```python from deepdiff import DeepDiff, Delta t1 = [1, 2, 3] t2 = ['a', 2, 3, 4] diff = DeepDiff(t1, t2) delta = Delta(diff) # Dump the delta object to a file with open('/tmp/delta1', 'wb') as dump_file: delta.dump(dump_file) # Load the delta object from the file path delta3 = Delta(delta_path='/tmp/delta1') # Verify the loaded delta print(t1 + delta3 == t2) ``` ``` -------------------------------- ### Applying Delta with Force Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/delta.rst Demonstrates how to use the Delta object with the 'force' parameter set to True to handle type changes when applying differences. This is useful when the original object's type is unknown or needs to be overridden. ```python >>> delta = Delta(diff) >>> {} + delta # doctest: +SKIP {} ``` ```python >>> delta = Delta(diff, force=True) >>> {} + delta {'x': {'y': {3: 4}}, 'q': {'t': 0.5}} ``` -------------------------------- ### Comparing Dictionaries with Value and String Changes Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/basics.rst This example highlights how DeepDiff reports changes in both simple values and nested string values within dictionaries. ```python t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}} t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}} ddiff = DeepDiff(t1, t2) pprint (ddiff, indent = 2) ``` -------------------------------- ### Worker Function for Subtree Diffs Source: https://github.com/qlustered/deepdiff/blob/master/docs/multi_processing.md This is the module-level worker function used for parallel subtree diff computations, designed to work with the `spawn` start method. ```python _subtree_diff_worker() ``` -------------------------------- ### Import DeepDiff Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/basics.rst Import the DeepDiff class from the deepdiff library and pprint for pretty printing. ```python from deepdiff import DeepDiff from pprint import pprint ``` -------------------------------- ### Include Object Callback Strict Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/ignore_types_or_values.rst Illustrates including objects based on a strict callback function. The object is included only if the function returns True for both objects. ```python def include_obj_callback_strict(obj, path): return True if isinstance(obj, int) and obj > 10 else False t1 = {"x": 10, "y": "b", "z": "c"} t2 = {"x": 12, "y": "b", "z": "c"} DeepDiff(t1, t2, include_obj_callback=include_obj_callback_strict) DeepDiff(t1, t2, include_obj_callback_strict=include_obj_callback_strict) ``` -------------------------------- ### Create and Apply Delta Object Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/delta.rst Demonstrates creating a Delta object from a DeepDiff result and applying it to reconstruct the second object from the first. Also shows how to create a bidirectional Delta to reverse the operation. ```python from deepdiff import DeepDiff, Delta from pprint import pprint t1 = [1, 2, 3] t2 = ['a', 2, 3, 4] diff = DeepDiff(t1, t2) delta = Delta(diff) print(delta) t1 + delta == t2 delta = Delta(diff, bidirectional=True) t2 - delta == t1 ``` -------------------------------- ### Exclude Object Callback Strict Example Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/ignore_types_or_values.rst Demonstrates excluding objects based on a strict callback function. This function must return True for both objects to be excluded. ```python def exclude_obj_callback_strict(obj, path): return True if isinstance(obj, int) and obj > 10 else False t1 = {"x": 10, "y": "b", "z": "c"} t2 = {"x": 12, "y": "b", "z": "c"} DeepDiff(t1, t2, exclude_obj_callback=exclude_obj_callback_strict) DeepDiff(t1, t2, exclude_obj_callback_strict=exclude_obj_callback_strict) ``` -------------------------------- ### Basic DeepHash Usage Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Demonstrates how to generate a deep hash for a dictionary object. The output is a dictionary mapping object IDs to their hashes. ```python >>> from deepdiff import DeepHash >>> obj = {1: 2, 'a': 'b'} >>> DeepHash(obj)[obj] # doctest: +SKIP ``` -------------------------------- ### Get Deep Distance for Lists Source: https://github.com/qlustered/deepdiff/blob/master/docs/deep_distance.rst Shows how to calculate deep distance between lists. An empty diff indicates identical lists, while added items increase the distance. ```python DeepDiff([1], [1], get_deep_distance=True) {} ``` ```python DeepDiff([1], [1, 2], get_deep_distance=True) {'iterable_item_added': {'root[1]': 2}, 'deep_distance': 0.2} ``` ```python DeepDiff([1], [1, 2, 3], get_deep_distance=True) {'iterable_item_added': {'root[1]': 2, 'root[2]': 3}, 'deep_distance': 0.3333333333333333} ``` -------------------------------- ### Pre-populate Hashes Dictionary Source: https://github.com/qlustered/deepdiff/blob/master/deepdiff/docstrings/deephash_doc.rst Initialize the hashing process with a dictionary of pre-calculated hashes for specific objects or object IDs to reuse them. ```python obj1 = {"a": 1} obj2 = {"b": 2} hashes_dict = {id(obj1): DeepHash(obj1)} print(DeepHash(obj2, hashes=hashes_dict)) ``` -------------------------------- ### Type Check Entire Module with Pyright Source: https://github.com/qlustered/deepdiff/blob/master/AGENTS.md Runs Pyright to type check an entire Python module. Activate the virtual environment beforehand. ```bash source ~/.venvs/deep/bin/activate && pyright deepdiff/ ``` -------------------------------- ### Custom Operator Example Source: https://github.com/qlustered/deepdiff/blob/master/docs/custom.rst Demonstrates using a custom operator to modify how values are compared. This is useful for handling specific data types or comparison rules not covered by default. ```python class MyOperator: def __init__(self, name='my_operator', operator_type='replace', **kwargs): self.name = name self.operator_type = operator_type self.kwargs = kwargs def __call__(self, obj1, obj2): # Example: Treat odd numbers as equal to the next even number if isinstance(obj1, int) and obj1 % 2 != 0: obj1 += 1 if isinstance(obj2, int) and obj2 % 2 != 0: obj2 += 1 return obj1 == obj2 def __str__(self): return self.name def __repr__(self): return f"<{self.__class__.__name__}(name='{self.name}', operator_type='{self.operator_type}')>" def give_up_diffing(self, level, diff_instance) -> bool: return any(diff_instance.tree.values()) t1 = [[1, 2], [3, 4], [5, 6]] t2 = [[1, 3], [3, 5], [5, 7]] DeepDiff(t1, t2, custom_operators=[ MyOperator() ]) ```