Skip to content

REF: Store metadata in an attrs dict #29062

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 22, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
37 changes: 36 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
import re
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
FrozenSet,
Hashable,
List,
Mapping,
Optional,
Sequence,
Set,
Expand Down Expand Up @@ -188,6 +190,9 @@ class NDFrame(PandasObject, SelectionMixin):
_is_copy = None
_data = None # type: BlockManager

if TYPE_CHECKING:
_attrs = {} # type: Dict[Hashable, Any]

# ----------------------------------------------------------------------
# Constructors

Expand All @@ -197,6 +202,7 @@ def __init__(
axes: Optional[List[Index]] = None,
copy: bool = False,
dtype: Optional[Dtype] = None,
attrs: Optional[Mapping[Hashable, Any]] = None,
fastpath: bool = False,
):

Expand All @@ -213,6 +219,11 @@ def __init__(
object.__setattr__(self, "_is_copy", None)
object.__setattr__(self, "_data", data)
object.__setattr__(self, "_item_cache", {})
if attrs is None:
attrs = {}
else:
attrs = dict(attrs)
object.__setattr__(self, "_attrs", attrs)

def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
Expand All @@ -233,6 +244,19 @@ def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):

# ----------------------------------------------------------------------

@property
def attrs(self) -> Dict[Hashable, Any]:
"""
Dictionary of global attributes on this object.
"""
if self._attrs is None:
self._attrs = {}
return self._attrs

@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)

@property
def is_copy(self):
"""
Expand Down Expand Up @@ -2029,7 +2053,13 @@ def to_dense(self):

def __getstate__(self):
meta = {k: getattr(self, k, None) for k in self._metadata}
return dict(_data=self._data, _typ=self._typ, _metadata=self._metadata, **meta)
return dict(
_data=self._data,
_typ=self._typ,
_metadata=self._metadata,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are attrs linked to _metadata in any way?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not yet, though perhaps eventually if we can find a suitable way to deprecate _metadata for subclasses. With this PR, pandas doesn't use _metadata itself anymore (previously, we just used it for Series.name.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait, then we should deprecate _metadata right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most likely? I have no idea who is using it or what they're using it for though.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok can you open an issue to deprecate that

attrs=self.attrs,
**meta
)

def __setstate__(self, state):

Expand All @@ -2038,6 +2068,8 @@ def __setstate__(self, state):
elif isinstance(state, dict):
typ = state.get("_typ")
if typ is not None:
attrs = state.get("_attrs", {})
object.__setattr__(self, "_attrs", attrs)

# set in the order of internal names
# to avoid definitional recursion
Expand Down Expand Up @@ -5213,6 +5245,9 @@ def __finalize__(self, other, method=None, **kwargs):

"""
if isinstance(other, NDFrame):
for name in other.attrs:
self.attrs[name] = other.attrs[name]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.attrs.update(other) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That'd work for now, but we'll need a for loop in my other PR since we'll have per-attr logic to resolve these.

# For subclasses using _metadata.
for name in self._metadata:
object.__setattr__(self, name, getattr(other, name, None))
return self
Expand Down
30 changes: 13 additions & 17 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from io import StringIO
from shutil import get_terminal_size
from textwrap import dedent
from typing import Any, Callable
from typing import Any, Callable, Hashable, List
import warnings

import numpy as np
Expand All @@ -29,7 +29,6 @@
is_dict_like,
is_extension_array_dtype,
is_extension_type,
is_hashable,
is_integer,
is_iterator,
is_list_like,
Expand All @@ -45,6 +44,7 @@
ABCSeries,
ABCSparseArray,
)
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import (
isna,
na_value_for_dtype,
Expand Down Expand Up @@ -173,7 +173,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
Copy input data.
"""

_metadata = ["name"]
_metadata = [] # type: List[str]
_accessors = {"dt", "cat", "str", "sparse"}
_deprecations = (
base.IndexOpsMixin._deprecations
Expand Down Expand Up @@ -324,7 +324,6 @@ def __init__(
data = SingleBlockManager(data, index, fastpath=True)

generic.NDFrame.__init__(self, data, fastpath=True)

self.name = name
self._set_axis(0, index, fastpath=True)

Expand Down Expand Up @@ -457,19 +456,6 @@ def _update_inplace(self, result, **kwargs):
# we want to call the generic version and not the IndexOpsMixin
return generic.NDFrame._update_inplace(self, result, **kwargs)

@property
def name(self):
"""
Return name of the Series.
"""
return self._name

@name.setter
def name(self, value):
if value is not None and not is_hashable(value):
raise TypeError("Series.name must be a hashable type")
object.__setattr__(self, "_name", value)

# ndarray compatibility
@property
def dtype(self):
Expand All @@ -485,6 +471,16 @@ def dtypes(self):
"""
return self._data.dtype

@property
def name(self) -> Hashable:
return self.attrs.get("name", None)

@name.setter
def name(self, value: Hashable) -> None:
if not is_hashable(value):
raise TypeError("Series.name must be a hashable type")
self.attrs["name"] = value

@property
def ftype(self):
"""
Expand Down