Base class for defining a strategy for merging metadata from two sources, left and right, into a single output.
The primary functionality for the class is the
merge(cls, left, right)class method. This takes
rightside arguments and returns a single merged output.
The first class attribute is
types. This is defined as a list of (left_types, right_types) tuples that indicate for which input types the merge strategy applies. In determining whether to apply this merge strategy to a pair of (left, right) objects, a test is done:
isinstance(left, left_types) and isinstance(right, right_types). For example:
types = [(np.ndarray, np.ndarray), # Two ndarrays (np.ndarray, (list, tuple)), # ndarray and (list or tuple) ((list, tuple), np.ndarray)] # (list or tuple) and ndarray
As a convenience,
typescan be defined as a single two-tuple instead of a list of two-tuples, e.g.
types = (np.ndarray, np.ndarray).
The other class attribute is
enabled, which defaults to
Falsein the base class. By defining a subclass of
MergeStrategythe new merge strategy is automatically registered to be available for use in merging. However, by default the new merge strategy is not enabled. This prevents inadvertently changing the behavior of unrelated code that is performing metadata merge operations.
In most cases (particularly in library code that others might use) it is recommended to leave custom strategies disabled and use the
enable_merge_strategiescontext manager to locally enable the desired strategies. However, if one is confident that the new strategy will not produce unexpected behavior, then one can globally enable it by setting the
enabledclass attribute to
Here we define a custom merge strategy that takes an int or float on the left and right sides and returns a list with the two values.
>>> from astropy.utils.metadata import MergeStrategy >>> class MergeNumbersAsList(MergeStrategy): ... types = ((int, float), (int, float)) # (left_types, right_types) ... ... @classmethod ... def merge(cls, left, right): ... return [left, right]