Skip to content

CLN: NDFrame.__init__ unnecessary code #32131

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 1 commit into from
Feb 22, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def __init__(
else:
raise ValueError("DataFrame constructor not properly called!")

NDFrame.__init__(self, mgr, fastpath=True)
NDFrame.__init__(self, mgr)

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

Expand Down
40 changes: 15 additions & 25 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
from pandas._libs import Timestamp, iNaT, lib
from pandas._typing import (
Axis,
Dtype,
FilePathOrBuffer,
FrameOrSeries,
JSONSerializable,
Expand Down Expand Up @@ -200,22 +199,10 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
def __init__(
self,
data: BlockManager,
axes: Optional[List[Index]] = None,
copy: bool = False,
dtype: Optional[Dtype] = None,
attrs: Optional[Mapping[Optional[Hashable], Any]] = None,
fastpath: bool = False,
):

if not fastpath:
if dtype is not None:
data = data.astype(dtype)
elif copy:
data = data.copy()

if axes is not None:
for i, ax in enumerate(axes):
data = data.reindex_axis(ax, axis=i)
# copy kwarg is retained for mypy compat, is not used

object.__setattr__(self, "_is_copy", None)
object.__setattr__(self, "_data", data)
Expand All @@ -226,12 +213,13 @@ def __init__(
attrs = dict(attrs)
object.__setattr__(self, "_attrs", attrs)

def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
@classmethod
def _init_mgr(cls, mgr, axes=None, dtype=None, copy=False):
""" passed a manager and a axes dict """
for a, axe in axes.items():
if axe is not None:
mgr = mgr.reindex_axis(
axe, axis=self._get_block_manager_axis(a), copy=False
axe, axis=cls._get_block_manager_axis(a), copy=False
)

# make a copy if explicitly requested
Expand Down Expand Up @@ -262,7 +250,8 @@ def attrs(self) -> Dict[Optional[Hashable], Any]:
def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None:
self._attrs = dict(value)

def _validate_dtype(self, dtype):
@classmethod
def _validate_dtype(cls, dtype):
""" validate the passed dtype """
if dtype is not None:
dtype = pandas_dtype(dtype)
Expand All @@ -271,7 +260,7 @@ def _validate_dtype(self, dtype):
if dtype.kind == "V":
raise NotImplementedError(
"compound dtypes are not implemented "
f"in the {type(self).__name__} constructor"
f"in the {cls.__name__} constructor"
)

return dtype
Expand Down Expand Up @@ -324,8 +313,9 @@ def _construct_axes_dict(self, axes=None, **kwargs):
d.update(kwargs)
return d

@classmethod
def _construct_axes_from_arguments(
self, args, kwargs, require_all: bool = False, sentinel=None
cls, args, kwargs, require_all: bool = False, sentinel=None
):
"""
Construct and returns axes if supplied in args/kwargs.
Expand All @@ -339,7 +329,7 @@ def _construct_axes_from_arguments(
"""
# construct the args
args = list(args)
for a in self._AXIS_ORDERS:
for a in cls._AXIS_ORDERS:

# look for a argument by position
if a not in kwargs:
Expand All @@ -349,7 +339,7 @@ def _construct_axes_from_arguments(
if require_all:
raise TypeError("not enough/duplicate arguments specified!")

axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS}
axes = {a: kwargs.pop(a, sentinel) for a in cls._AXIS_ORDERS}
return axes, kwargs

@classmethod
Expand Down Expand Up @@ -495,7 +485,7 @@ def ndim(self) -> int:
return self._data.ndim

@property
def size(self):
def size(self) -> int:
"""
Return an int representing the number of elements in this object.

Expand Down Expand Up @@ -3660,7 +3650,7 @@ def get(self, key, default=None):
return default

@property
def _is_view(self):
def _is_view(self) -> bool_t:
"""Return boolean indicating if self is view of another array """
return self._data.is_view

Expand Down Expand Up @@ -5176,12 +5166,12 @@ def _consolidate(self, inplace: bool_t = False):
return self._constructor(cons_data).__finalize__(self)

@property
def _is_mixed_type(self):
def _is_mixed_type(self) -> bool_t:
f = lambda: self._data.is_mixed_type
return self._protect_consolidate(f)

@property
def _is_numeric_mixed_type(self):
def _is_numeric_mixed_type(self) -> bool_t:
f = lambda: self._data.is_numeric_mixed_type
return self._protect_consolidate(f)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def __init__(

data = SingleBlockManager(data, index, fastpath=True)

generic.NDFrame.__init__(self, data, fastpath=True)
generic.NDFrame.__init__(self, data)
self.name = name
self._set_axis(0, index, fastpath=True)

Expand Down
26 changes: 0 additions & 26 deletions pandas/tests/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@
import numpy as np
import pytest

from pandas.errors import AbstractMethodError

from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype

import pandas as pd
from pandas import DataFrame, Index, NaT, Series
import pandas._testing as tm
from pandas.core.generic import NDFrame
from pandas.core.indexers import validate_indices
from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice
from pandas.tests.indexing.common import _mklbl
Expand Down Expand Up @@ -1094,29 +1091,6 @@ def test_extension_array_cross_section_converts():
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize(
"idxr, error, error_message",
[
(lambda x: x, AbstractMethodError, None),
(
lambda x: x.loc,
AttributeError,
"type object 'NDFrame' has no attribute '_AXIS_NAMES'",
),
(
lambda x: x.iloc,
AttributeError,
"type object 'NDFrame' has no attribute '_AXIS_NAMES'",
),
],
)
def test_ndframe_indexing_raises(idxr, error, error_message):
# GH 25567
frame = NDFrame(np.random.randint(5, size=(2, 2, 2)))
with pytest.raises(error, match=error_message):
idxr(frame)[0]


def test_readonly_indices():
# GH#17192 iloc with read-only array raising TypeError
df = pd.DataFrame({"data": np.ones(100, dtype="float64")})
Expand Down