Skip to content

Commit b7c05aa

Browse files
committed
Implement equivalent_attrs function as suggested by @keewis
- Create dedicated equivalent_attrs function that wraps equivalent() - Returns False when ValueError is raised (e.g., for numpy arrays) - Simplifies merge_attrs logic by encapsulating error handling - Makes future behavior changes easier
1 parent 2b85c43 commit b7c05aa

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

xarray/structure/merge.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,17 @@ def merge_coords(
607607
return variables, out_indexes
608608

609609

610+
def equivalent_attrs(a: Any, b: Any) -> bool:
611+
"""Check if two attribute values are equivalent.
612+
613+
Returns False if the comparison raises ValueError (e.g., for numpy arrays).
614+
"""
615+
try:
616+
return equivalent(a, b)
617+
except ValueError:
618+
return False
619+
620+
610621
def merge_attrs(variable_attrs, combine_attrs, context=None):
611622
"""Combine attributes from different variables according to combine_attrs"""
612623
if not variable_attrs:
@@ -635,26 +646,15 @@ def merge_attrs(variable_attrs, combine_attrs, context=None):
635646
dropped_keys = set()
636647

637648
for attrs in variable_attrs:
638-
# Process each attribute in the current attrs dict
639649
for key, value in attrs.items():
640650
if key in dropped_keys:
641-
continue # Already marked as conflicted
651+
continue
642652

643653
if key not in result:
644-
# New key, add it
645654
result[key] = value
646-
else:
647-
# Existing key, check for conflict
648-
try:
649-
if not equivalent(result[key], value):
650-
# Values are different, drop the key
651-
result.pop(key, None)
652-
dropped_keys.add(key)
653-
except ValueError:
654-
# equivalent() failed (likely ambiguous truth value)
655-
# Treat as conflict and drop
656-
result.pop(key, None)
657-
dropped_keys.add(key)
655+
elif not equivalent_attrs(result[key], value):
656+
result.pop(key, None)
657+
dropped_keys.add(key)
658658

659659
return result
660660
elif combine_attrs == "identical":

0 commit comments

Comments
 (0)