Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions deepmerge/strategy/type_conflict.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from collections.abc import Sized
from typing import Any, TypeVar

import deepmerge.merger
Expand Down Expand Up @@ -30,5 +31,14 @@ def strategy_use_existing(
def strategy_override_if_not_empty(
config: deepmerge.merger.Merger, path: list, base: T1, nxt: T2
) -> T1 | T2:
"""overrides the new object over the old object only if the new object is not empty or null"""
return nxt if nxt else base
"""overrides the new object over the old object only if the new object is not empty or null.

``None`` is treated as null. Sized objects (``dict``, ``list``, ``set``, ``str``, …) are
treated as empty when ``len(nxt) == 0``. All other values — including falsy primitives such
as ``0``, ``0.0``, and ``False`` — are considered non-empty and will override *base*.
"""
if nxt is None:
return base
if isinstance(nxt, Sized) and len(nxt) == 0:
return base
return nxt
12 changes: 12 additions & 0 deletions deepmerge/tests/strategy/test_type_conflict.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,15 @@ def test_merge_if_not_empty():

strategy = TypeConflictStrategies.strategy_override_if_not_empty({}, [], CONTENT_AS_LIST, None)
assert strategy == CONTENT_AS_LIST


def test_merge_if_not_empty_falsy_primitives():
"""Falsy primitives (0, False) are valid non-empty values and should override base."""
strategy = TypeConflictStrategies.strategy_override_if_not_empty({}, [], "base", 0)
assert strategy == 0, "integer zero is not empty; it should override base"

strategy = TypeConflictStrategies.strategy_override_if_not_empty({}, [], "base", False)
assert strategy is False, "False is not empty; it should override base"

strategy = TypeConflictStrategies.strategy_override_if_not_empty({}, [], "base", 0.0)
assert strategy == 0.0, "0.0 is not empty; it should override base"
Comment thread
toumorokoshi marked this conversation as resolved.
Outdated
Loading