|
| 1 | +""" |
| 2 | +Metadata propagation through pandas operations. |
| 3 | +
|
| 4 | +This module contains the infrastructure for propagating ``NDFrame._metadata`` |
| 5 | +through operations. We perform an operation (say :meth:`pandas.Series.copy`) that |
| 6 | +returns an ``NDFrame`` and would like to propagate the metadata (say ``Series.name``) |
| 7 | +from ``self`` to the new ``NDFrame``. |
| 8 | +
|
| 9 | +.. note:: |
| 10 | +
|
| 11 | + Currently, pandas doesn't provide a clean, documented API on |
| 12 | +
|
| 13 | + * which methods call finalize |
| 14 | + * the types passed to finalize for each method |
| 15 | +
|
| 16 | + This is a known limitation we would like to address in the future. |
| 17 | +""" |
| 18 | +from collections import defaultdict |
| 19 | +from functools import wraps |
| 20 | +from typing import TYPE_CHECKING, Any, Callable, Union |
| 21 | + |
| 22 | +from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries |
| 23 | + |
| 24 | +if TYPE_CHECKING: |
| 25 | + from pandas.core.generic import NDFrame |
| 26 | + |
| 27 | +dispatch = defaultdict(dict) |
| 28 | +dispatch_method_type = Union[Callable[..., "NDFrame"], str] |
| 29 | + |
| 30 | + |
| 31 | +def key_of(method): |
| 32 | + if isinstance(method, str): |
| 33 | + # TODO: figure out if this is OK. May be necessary when we have |
| 34 | + # things like pd.merge and DataFrame.merge that hit the same finalize. |
| 35 | + return method |
| 36 | + elif method: |
| 37 | + return method.__module__, method.__name__ |
| 38 | + |
| 39 | + |
| 40 | +class PandasMetadata: |
| 41 | + """ |
| 42 | + Dispatch metadata finalization for pandas metadata. |
| 43 | +
|
| 44 | + Users should instantiate a single `PandasMetadata` instance |
| 45 | + for their piece of metadata and register finalizers for various |
| 46 | + pandas methods using :meth:`PandsaMetadata.register`. |
| 47 | +
|
| 48 | + Parameters |
| 49 | + ---------- |
| 50 | + name : str |
| 51 | + The name of the attribute being finalized. |
| 52 | +
|
| 53 | + Examples |
| 54 | + -------- |
| 55 | + >>> maxmeta = PandasMetadata("attr") |
| 56 | +
|
| 57 | + Register a finalizer for a given pandas method: |
| 58 | +
|
| 59 | + >>> @maxmeta.register(pd.concat) |
| 60 | + ... def _(new, concatenator): |
| 61 | + ... new.attr = max(x.attr_meta for x in concatenator.objs) |
| 62 | +
|
| 63 | + >>> pd.DataFrame._metadata = ['attr'] |
| 64 | + >>> x = pd.DataFrame({"x"}); x.attr = 1 |
| 65 | + >>> y = pd.DataFrame({"y"}); y.attr = 2 |
| 66 | + >>> pd.concat([x, y]).attr |
| 67 | + 2 |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__(self, name: str): |
| 71 | + self.name = name |
| 72 | + |
| 73 | + def register(self, pandas_method: dispatch_method_type): |
| 74 | + """ |
| 75 | + A decorator to register a finalizer for a specific pandas method. |
| 76 | +
|
| 77 | + Parameters |
| 78 | + ---------- |
| 79 | + pandas_method : callable or str |
| 80 | + A pandas method, like :meth:`pandas.concat`, that this finalizer |
| 81 | + should be used for. The function being decorated will be called |
| 82 | + with the relevant arguments (typically the output and the source NDFrame). |
| 83 | + When `NDFrame.__finalize__` is called as a result of `pandas_method`, |
| 84 | + the registered finalizer will be called. |
| 85 | + """ |
| 86 | + |
| 87 | + def decorate(func): |
| 88 | + # TODO: warn of collisions? |
| 89 | + dispatch[key_of(pandas_method)][self.name] = func |
| 90 | + |
| 91 | + @wraps(func) |
| 92 | + def wrapper(*args, **kwargs): |
| 93 | + return func(*args, **kwargs) |
| 94 | + |
| 95 | + return wrapper |
| 96 | + |
| 97 | + return decorate |
| 98 | + |
| 99 | + |
| 100 | +def default_finalizer(new: "NDFrame", other: Any, *, name: str): |
| 101 | + """ |
| 102 | + The default finalizer when this method, attribute hasn't been overridden. |
| 103 | +
|
| 104 | + This copies the ``_metadata`` attribute from ``other`` to ``self``, modifying |
| 105 | + ``self`` inplace. |
| 106 | +
|
| 107 | + Parameters |
| 108 | + ---------- |
| 109 | + new : NDFrame |
| 110 | + The newly created NDFrame being finalized. |
| 111 | + other : NDFrame |
| 112 | + The source NDFrame attributes will be extracted from. |
| 113 | + """ |
| 114 | + object.__setattr__(new, name, getattr(other, name, None)) |
| 115 | + |
| 116 | + |
| 117 | +# ---------------------------------------------------------------------------- |
| 118 | +# Pandas Internals. |
| 119 | + |
| 120 | + |
| 121 | +def ndframe_finalize(new: "NDFrame", other: Any, method: dispatch_method_type): |
| 122 | + """ |
| 123 | + Finalize a new NDFrame. |
| 124 | +
|
| 125 | + The finalizer is looked up from finalizers registered with PandasMetadata. |
| 126 | + `new` is modified inplace, and nothing is returned. |
| 127 | +
|
| 128 | + Parameters |
| 129 | + ---------- |
| 130 | + new : NDFrame |
| 131 | + other : NDFrame |
| 132 | + Or a list of them? TBD |
| 133 | + method : callable or str |
| 134 | + """ |
| 135 | + # To avoid one isinstance per _metadata name, we check up front. |
| 136 | + # Most of the time `other` is an ndframe, but in some cases (e.g. concat) |
| 137 | + # it's `_Concatenator` object |
| 138 | + other_is_ndframe = isinstance(other, (ABCSeries, ABCDataFrame)) |
| 139 | + |
| 140 | + for name in new._metadata: |
| 141 | + finalizer = dispatch.get(key_of(method), {}).get(name) |
| 142 | + |
| 143 | + if finalizer: |
| 144 | + finalizer(new, other) |
| 145 | + elif other_is_ndframe: |
| 146 | + default_finalizer(new, other, name=name) |
0 commit comments