Combine attributes from different variables according to combine_attrs
(variable_attrs, combine_attrs, context=None)
| 634 | |
| 635 | |
| 636 | def merge_attrs(variable_attrs, combine_attrs, context=None): |
| 637 | """Combine attributes from different variables according to combine_attrs""" |
| 638 | if not variable_attrs: |
| 639 | # no attributes to merge |
| 640 | return None |
| 641 | |
| 642 | if callable(combine_attrs): |
| 643 | return combine_attrs(variable_attrs, context=context) |
| 644 | elif combine_attrs == "drop": |
| 645 | return {} |
| 646 | elif combine_attrs == "override": |
| 647 | return dict(variable_attrs[0]) |
| 648 | elif combine_attrs == "no_conflicts": |
| 649 | result = dict(variable_attrs[0]) |
| 650 | for attrs in variable_attrs[1:]: |
| 651 | try: |
| 652 | result = compat_dict_union(result, attrs) |
| 653 | except ValueError as e: |
| 654 | raise MergeError( |
| 655 | "combine_attrs='no_conflicts', but some values are not " |
| 656 | f"the same. Merging {result} with {attrs}" |
| 657 | ) from e |
| 658 | return result |
| 659 | elif combine_attrs == "drop_conflicts": |
| 660 | result = {} |
| 661 | dropped_keys = set() |
| 662 | |
| 663 | for attrs in variable_attrs: |
| 664 | for key, value in attrs.items(): |
| 665 | if key in dropped_keys: |
| 666 | continue |
| 667 | |
| 668 | if key not in result: |
| 669 | result[key] = value |
| 670 | elif not equivalent_attrs(result[key], value): |
| 671 | del result[key] |
| 672 | dropped_keys.add(key) |
| 673 | |
| 674 | return result |
| 675 | elif combine_attrs == "identical": |
| 676 | result = dict(variable_attrs[0]) |
| 677 | for attrs in variable_attrs[1:]: |
| 678 | if not dict_equiv(result, attrs): |
| 679 | raise MergeError( |
| 680 | f"combine_attrs='identical', but attrs differ. First is {result} " |
| 681 | f", other is {attrs}." |
| 682 | ) |
| 683 | return result |
| 684 | else: |
| 685 | raise ValueError(f"Unrecognised value for combine_attrs={combine_attrs}") |
| 686 | |
| 687 | |
| 688 | class _MergeResult(NamedTuple): |
no test coverage detected
searching dependent graphs…