Skip to content

Commit

Permalink
chore: Improve merge_dict typing (#271)
Browse files Browse the repository at this point in the history
  • Loading branch information
tony committed May 13, 2023
2 parents 7ae55a0 + 0419604 commit 0c5b471
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 24 deletions.
4 changes: 4 additions & 0 deletions CHANGES
Expand Up @@ -19,6 +19,10 @@ $ pipx install --suffix=@next unihan-etl --pip-args '\--pre' --force

- _Insert changes/features/fixes for next release here_

### Development

- `merge_dict`: Improve typing of generic params (#271)

## unihan-etl 0.18.1 (2022-10-01)

### Packaging
Expand Down
52 changes: 28 additions & 24 deletions src/unihan_etl/util.py
Expand Up @@ -7,6 +7,7 @@
import re
import sys
import typing as t
from collections.abc import Mapping


def ucn_to_unicode(ucn: str) -> str:
Expand Down Expand Up @@ -93,31 +94,34 @@ def format_size(_bytes: int) -> str:
print("\n")


_T = t.TypeVar("_T")
T = t.TypeVar("T", bound="Mapping[str, t.Any]")


def merge_dict(
base: t.Mapping[str, _T], additional: t.Mapping[str, _T]
) -> t.Dict[str, _T]:
if base is None:
return additional

if additional is None:
return base

if not (isinstance(base, t.Mapping) and isinstance(additional, t.Mapping)):
return additional

merged = base
assert isinstance(merged, dict)

for key, value in additional.items():
if isinstance(value, t.Mapping):
assert isinstance(key, str)
assert isinstance(value, dict)
merged.setdefault(key, {})
merged[key] = merge_dict(merged[key], value)
d: T,
u: T,
) -> T:
"""Return updated dict.
Parameters
----------
d : dict
u : dict
Returns
-------
dict :
Updated dictionary
Notes
-----
Thanks: http://stackoverflow.com/a/3233356
"""
for k, v in u.items():
assert isinstance(d, dict)
if isinstance(v, dict):
r = merge_dict(d.get(k, {}), v)
d[k] = r
else:
merged[key] = value

return merged
d[k] = u[k]
return d

0 comments on commit 0c5b471

Please sign in to comment.