File: pyutils.py

package info (click to toggle)
strawberry-graphql-django 0.67.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,988 kB
  • sloc: python: 27,682; sh: 20; makefile: 20
file content (49 lines) | stat: -rw-r--r-- 1,165 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from collections.abc import Mapping
from typing import Any, TypeAlias, TypeVar

_K = TypeVar("_K", bound=Any)
_V = TypeVar("_V", bound=Any)

DictTree: TypeAlias = dict[str, "DictTree"]


def dicttree_merge(dict1: Mapping[_K, _V], dict2: Mapping[_K, _V]) -> dict[_K, _V]:
    new = {
        **dict1,
        **dict2,
    }

    for k, v1 in dict1.items():
        if not isinstance(v1, dict):
            continue

        v2 = dict2.get(k)
        if isinstance(v2, Mapping):
            new[k] = dicttree_merge(v1, v2)  # type: ignore

    for k, v2 in dict2.items():
        if not isinstance(v2, dict):
            continue

        v1 = dict1.get(k)
        if isinstance(v1, Mapping):
            new[k] = dicttree_merge(v1, v2)  # type: ignore

    return new


def dicttree_insersection_differs(
    dict1: Mapping[_K, _V],
    dict2: Mapping[_K, _V],
) -> bool:
    for k in set(dict1) & set(dict2):
        v1 = dict1[k]
        v2 = dict2[k]

        if isinstance(v1, Mapping) and isinstance(v2, Mapping):
            if dicttree_insersection_differs(v1, v2):
                return True
        elif v1 != v2:
            return True

    return False