Skip to content

Commit e77be39

Browse files
committed
CLN: move ABC to types/generic.py
1 parent 534dcc7 commit e77be39

File tree

7 files changed

+174
-114
lines changed

7 files changed

+174
-114
lines changed

pandas/core/common.py

+20-75
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
from pandas import compat
1919
from pandas.compat import (BytesIO, range, long, u, zip, map, string_types,
2020
iteritems)
21-
from pandas.types.api import *
21+
from pandas.types import api as gt
22+
from pandas.types.api import * # noqa
2223
from pandas.core.config import get_option
2324

2425

@@ -71,63 +72,6 @@ def __str__(self):
7172
_int64_max = np.iinfo(np.int64).max
7273

7374

74-
# define abstract base classes to enable isinstance type checking on our
75-
# objects
76-
def create_pandas_abc_type(name, attr, comp):
77-
@classmethod
78-
def _check(cls, inst):
79-
return getattr(inst, attr, '_typ') in comp
80-
81-
dct = dict(__instancecheck__=_check, __subclasscheck__=_check)
82-
meta = type("ABCBase", (type, ), dct)
83-
return meta(name, tuple(), dct)
84-
85-
86-
ABCIndex = create_pandas_abc_type("ABCIndex", "_typ", ("index", ))
87-
ABCInt64Index = create_pandas_abc_type("ABCInt64Index", "_typ",
88-
("int64index", ))
89-
ABCRangeIndex = create_pandas_abc_type("ABCRangeIndex", "_typ",
90-
("rangeindex", ))
91-
ABCFloat64Index = create_pandas_abc_type("ABCFloat64Index", "_typ",
92-
("float64index", ))
93-
ABCMultiIndex = create_pandas_abc_type("ABCMultiIndex", "_typ",
94-
("multiindex", ))
95-
ABCDatetimeIndex = create_pandas_abc_type("ABCDatetimeIndex", "_typ",
96-
("datetimeindex", ))
97-
ABCTimedeltaIndex = create_pandas_abc_type("ABCTimedeltaIndex", "_typ",
98-
("timedeltaindex", ))
99-
ABCPeriodIndex = create_pandas_abc_type("ABCPeriodIndex", "_typ",
100-
("periodindex", ))
101-
ABCCategoricalIndex = create_pandas_abc_type("ABCCategoricalIndex", "_typ",
102-
("categoricalindex", ))
103-
ABCIndexClass = create_pandas_abc_type("ABCIndexClass", "_typ",
104-
("index", "int64index", "rangeindex",
105-
"float64index",
106-
"multiindex", "datetimeindex",
107-
"timedeltaindex", "periodindex",
108-
"categoricalindex"))
109-
110-
ABCSeries = create_pandas_abc_type("ABCSeries", "_typ", ("series", ))
111-
ABCDataFrame = create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe", ))
112-
ABCPanel = create_pandas_abc_type("ABCPanel", "_typ", ("panel", ))
113-
ABCSparseSeries = create_pandas_abc_type("ABCSparseSeries", "_subtyp",
114-
('sparse_series',
115-
'sparse_time_series'))
116-
ABCSparseArray = create_pandas_abc_type("ABCSparseArray", "_subtyp",
117-
('sparse_array', 'sparse_series'))
118-
ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ",
119-
("categorical"))
120-
ABCPeriod = create_pandas_abc_type("ABCPeriod", "_typ", ("period", ))
121-
122-
123-
class _ABCGeneric(type):
124-
def __instancecheck__(cls, inst):
125-
return hasattr(inst, "_data")
126-
127-
128-
ABCGeneric = _ABCGeneric("ABCGeneric", tuple(), {})
129-
130-
13175
def isnull(obj):
13276
"""Detect missing values (NaN in numeric arrays, None/NaN in object arrays)
13377
@@ -155,9 +99,9 @@ def _isnull_new(obj):
15599
# hack (for now) because MI registers as ndarray
156100
elif isinstance(obj, pd.MultiIndex):
157101
raise NotImplementedError("isnull is not defined for MultiIndex")
158-
elif isinstance(obj, (ABCSeries, np.ndarray, pd.Index)):
102+
elif isinstance(obj, (gt.ABCSeries, np.ndarray, pd.Index)):
159103
return _isnull_ndarraylike(obj)
160-
elif isinstance(obj, ABCGeneric):
104+
elif isinstance(obj, gt.ABCGeneric):
161105
return obj._constructor(obj._data.isnull(func=isnull))
162106
elif isinstance(obj, list) or hasattr(obj, '__array__'):
163107
return _isnull_ndarraylike(np.asarray(obj))
@@ -181,9 +125,9 @@ def _isnull_old(obj):
181125
# hack (for now) because MI registers as ndarray
182126
elif isinstance(obj, pd.MultiIndex):
183127
raise NotImplementedError("isnull is not defined for MultiIndex")
184-
elif isinstance(obj, (ABCSeries, np.ndarray, pd.Index)):
128+
elif isinstance(obj, (gt.ABCSeries, np.ndarray, pd.Index)):
185129
return _isnull_ndarraylike_old(obj)
186-
elif isinstance(obj, ABCGeneric):
130+
elif isinstance(obj, gt.ABCGeneric):
187131
return obj._constructor(obj._data.isnull(func=_isnull_old))
188132
elif isinstance(obj, list) or hasattr(obj, '__array__'):
189133
return _isnull_ndarraylike_old(np.asarray(obj))
@@ -250,7 +194,7 @@ def _isnull_ndarraylike(obj):
250194
result = np.isnan(values)
251195

252196
# box
253-
if isinstance(obj, ABCSeries):
197+
if isinstance(obj, gt.ABCSeries):
254198
from pandas import Series
255199
result = Series(result, index=obj.index, name=obj.name, copy=False)
256200

@@ -279,7 +223,7 @@ def _isnull_ndarraylike_old(obj):
279223
result = ~np.isfinite(values)
280224

281225
# box
282-
if isinstance(obj, ABCSeries):
226+
if isinstance(obj, gt.ABCSeries):
283227
from pandas import Series
284228
result = Series(result, index=obj.index, name=obj.name, copy=False)
285229

@@ -1687,10 +1631,10 @@ def _possibly_infer_to_datetimelike(value, convert_dates=False):
16871631
16881632
"""
16891633

1690-
if isinstance(value, (ABCDatetimeIndex, ABCPeriodIndex)):
1634+
if isinstance(value, (gt.ABCDatetimeIndex, gt.ABCPeriodIndex)):
16911635
return value
1692-
elif isinstance(value, ABCSeries):
1693-
if isinstance(value._values, ABCDatetimeIndex):
1636+
elif isinstance(value, gt.ABCSeries):
1637+
if isinstance(value._values, gt.ABCDatetimeIndex):
16941638
return value._values
16951639

16961640
v = value
@@ -1760,7 +1704,7 @@ def _try_timedelta(v):
17601704

17611705

17621706
def is_bool_indexer(key):
1763-
if isinstance(key, (ABCSeries, np.ndarray)):
1707+
if isinstance(key, (gt.ABCSeries, np.ndarray)):
17641708
if key.dtype == np.object_:
17651709
key = np.asarray(_values_from_object(key))
17661710

@@ -2088,22 +2032,23 @@ def is_period_arraylike(arr):
20882032
""" return if we are period arraylike / PeriodIndex """
20892033
if isinstance(arr, pd.PeriodIndex):
20902034
return True
2091-
elif isinstance(arr, (np.ndarray, ABCSeries)):
2035+
elif isinstance(arr, (np.ndarray, gt.ABCSeries)):
20922036
return arr.dtype == object and lib.infer_dtype(arr) == 'period'
20932037
return getattr(arr, 'inferred_type', None) == 'period'
20942038

20952039

20962040
def is_datetime_arraylike(arr):
20972041
""" return if we are datetime arraylike / DatetimeIndex """
2098-
if isinstance(arr, ABCDatetimeIndex):
2042+
if isinstance(arr, gt.ABCDatetimeIndex):
20992043
return True
2100-
elif isinstance(arr, (np.ndarray, ABCSeries)):
2044+
elif isinstance(arr, (np.ndarray, gt.ABCSeries)):
21012045
return arr.dtype == object and lib.infer_dtype(arr) == 'datetime'
21022046
return getattr(arr, 'inferred_type', None) == 'datetime'
21032047

21042048

21052049
def is_datetimelike(arr):
2106-
return (arr.dtype in _DATELIKE_DTYPES or isinstance(arr, ABCPeriodIndex) or
2050+
return (arr.dtype in _DATELIKE_DTYPES or
2051+
isinstance(arr, gt.ABCPeriodIndex) or
21072052
is_datetimetz(arr))
21082053

21092054

@@ -2334,12 +2279,12 @@ def is_bool_dtype(arr_or_dtype):
23342279

23352280
def is_sparse(array):
23362281
""" return if we are a sparse array """
2337-
return isinstance(array, (ABCSparseArray, ABCSparseSeries))
2282+
return isinstance(array, (gt.ABCSparseArray, gt.ABCSparseSeries))
23382283

23392284

23402285
def is_datetimetz(array):
23412286
""" return if we are a datetime with tz array """
2342-
return ((isinstance(array, ABCDatetimeIndex) and
2287+
return ((isinstance(array, gt.ABCDatetimeIndex) and
23432288
getattr(array, 'tz', None) is not None) or
23442289
is_datetime64tz_dtype(array))
23452290

@@ -2360,7 +2305,7 @@ def is_internal_type(value):
23602305

23612306
def is_categorical(array):
23622307
""" return if we are a categorical possibility """
2363-
return isinstance(array, ABCCategorical) or is_categorical_dtype(array)
2308+
return isinstance(array, gt.ABCCategorical) or is_categorical_dtype(array)
23642309

23652310

23662311
def is_categorical_dtype(arr_or_dtype):

pandas/io/tests/test_pytables.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
isnull)
1717

1818
from pandas.compat import is_platform_windows, PY3, PY35
19+
from pandas.formats.printing import pprint_thing
1920
from pandas.io.pytables import _tables, TableIterator
2021
try:
2122
_tables()
@@ -28,7 +29,6 @@
2829
AttributeConflictWarning, DuplicateWarning,
2930
PossibleDataLossError, ClosedFileError)
3031
from pandas.io import pytables as pytables
31-
import pandas.core.common as com
3232
import pandas.util.testing as tm
3333
from pandas.util.testing import (assert_panel4d_equal,
3434
assert_panel_equal,
@@ -3806,9 +3806,15 @@ def test_string_select(self):
38063806
expected = df[df.x != 'none']
38073807
assert_frame_equal(result, expected)
38083808
except Exception as detail:
3809+
<<<<<<< HEAD
38093810
com.pprint_thing("[{0}]".format(detail))
38103811
com.pprint_thing(store)
38113812
com.pprint_thing(expected)
3813+
=======
3814+
pprint_thing("[{0}]".format(detail))
3815+
pprint_thing(store)
3816+
pprint_thing(expected)
3817+
>>>>>>> e462ffe... wip
38123818

38133819
df2 = df.copy()
38143820
df2.loc[df2.x == '', 'x'] = np.nan

pandas/tests/series/test_misc_api.py

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from pandas import Index, Series, DataFrame, date_range
88
from pandas.tseries.index import Timestamp
9-
import pandas.core.common as com
109

1110
from pandas.compat import range
1211
from pandas import compat

pandas/tests/test_common.py

+1-35
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from pandas import (Series, DataFrame, date_range, DatetimeIndex,
1212
TimedeltaIndex, Timestamp, Float64Index)
1313
from pandas import compat
14-
from pandas.compat import range, long, lrange, lmap, u
14+
from pandas.compat import range, lrange, lmap, u
1515
from pandas.core.common import notnull, isnull, array_equivalent
1616
import pandas.core.common as com
1717
import pandas.core.convert as convert
@@ -70,40 +70,6 @@ def __call__(self):
7070
assert getname(1) is None
7171

7272

73-
# Issue 10859
74-
class TestABCClasses(tm.TestCase):
75-
tuples = [[1, 2, 2], ['red', 'blue', 'red']]
76-
multi_index = pd.MultiIndex.from_arrays(tuples, names=('number', 'color'))
77-
datetime_index = pd.to_datetime(['2000/1/1', '2010/1/1'])
78-
timedelta_index = pd.to_timedelta(np.arange(5), unit='s')
79-
period_index = pd.period_range('2000/1/1', '2010/1/1/', freq='M')
80-
categorical = pd.Categorical([1, 2, 3], categories=[2, 3, 1])
81-
categorical_df = pd.DataFrame({"values": [1, 2, 3]}, index=categorical)
82-
df = pd.DataFrame({'names': ['a', 'b', 'c']}, index=multi_index)
83-
sparse_series = pd.Series([1, 2, 3]).to_sparse()
84-
sparse_array = pd.SparseArray(np.random.randn(10))
85-
86-
def test_abc_types(self):
87-
self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndex)
88-
self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCInt64Index)
89-
self.assertIsInstance(pd.Float64Index([1, 2, 3]), com.ABCFloat64Index)
90-
self.assertIsInstance(self.multi_index, com.ABCMultiIndex)
91-
self.assertIsInstance(self.datetime_index, com.ABCDatetimeIndex)
92-
self.assertIsInstance(self.timedelta_index, com.ABCTimedeltaIndex)
93-
self.assertIsInstance(self.period_index, com.ABCPeriodIndex)
94-
self.assertIsInstance(self.categorical_df.index,
95-
com.ABCCategoricalIndex)
96-
self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndexClass)
97-
self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCIndexClass)
98-
self.assertIsInstance(pd.Series([1, 2, 3]), com.ABCSeries)
99-
self.assertIsInstance(self.df, com.ABCDataFrame)
100-
self.assertIsInstance(self.df.to_panel(), com.ABCPanel)
101-
self.assertIsInstance(self.sparse_series, com.ABCSparseSeries)
102-
self.assertIsInstance(self.sparse_array, com.ABCSparseArray)
103-
self.assertIsInstance(self.categorical, com.ABCCategorical)
104-
self.assertIsInstance(pd.Period('2012', freq='A-DEC'), com.ABCPeriod)
105-
106-
10773
class TestInferDtype(tm.TestCase):
10874

10975
def test_infer_dtype_from_scalar(self):

pandas/types/api.py

+42-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,42 @@
1-
from pandas.types.dtypes import (CategoricalDtype, CategoricalDtypeType,
2-
DatetimeTZDtype, DatetimeTZDtypeType) # noqa
1+
# flake8: noqa
2+
3+
import numpy as np
4+
from pandas.compat import string_types
5+
6+
from .dtypes import (CategoricalDtype, CategoricalDtypeType,
7+
DatetimeTZDtype, DatetimeTZDtypeType)
8+
from .generic import (ABCIndex, ABCInt64Index, ABCRangeIndex,
9+
ABCFloat64Index, ABCMultiIndex,
10+
ABCDatetimeIndex,
11+
ABCTimedeltaIndex, ABCPeriodIndex,
12+
ABCCategoricalIndex,
13+
ABCIndexClass,
14+
ABCSeries, ABCDataFrame, ABCPanel,
15+
ABCSparseSeries, ABCSparseArray,
16+
ABCCategorical, ABCPeriod,
17+
ABCGeneric)
18+
19+
def pandas_dtype(dtype):
20+
"""
21+
Converts input into a pandas only dtype object or a numpy dtype object.
22+
23+
Parameters
24+
----------
25+
dtype : object to be converted
26+
27+
Returns
28+
-------
29+
np.dtype or a pandas dtype
30+
"""
31+
if isinstance(dtype, string_types):
32+
try:
33+
return DatetimeTZDtype.construct_from_string(dtype)
34+
except TypeError:
35+
pass
36+
37+
try:
38+
return CategoricalDtype.construct_from_string(dtype)
39+
except TypeError:
40+
pass
41+
42+
return np.dtype(dtype)

pandas/types/generic.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
""" define generic base classes for pandas objects """
2+
3+
4+
# define abstract base classes to enable isinstance type checking on our
5+
# objects
6+
def create_pandas_abc_type(name, attr, comp):
7+
@classmethod
8+
def _check(cls, inst):
9+
return getattr(inst, attr, '_typ') in comp
10+
11+
dct = dict(__instancecheck__=_check, __subclasscheck__=_check)
12+
meta = type("ABCBase", (type, ), dct)
13+
return meta(name, tuple(), dct)
14+
15+
16+
ABCIndex = create_pandas_abc_type("ABCIndex", "_typ", ("index", ))
17+
ABCInt64Index = create_pandas_abc_type("ABCInt64Index", "_typ",
18+
("int64index", ))
19+
ABCRangeIndex = create_pandas_abc_type("ABCRangeIndex", "_typ",
20+
("rangeindex", ))
21+
ABCFloat64Index = create_pandas_abc_type("ABCFloat64Index", "_typ",
22+
("float64index", ))
23+
ABCMultiIndex = create_pandas_abc_type("ABCMultiIndex", "_typ",
24+
("multiindex", ))
25+
ABCDatetimeIndex = create_pandas_abc_type("ABCDatetimeIndex", "_typ",
26+
("datetimeindex", ))
27+
ABCTimedeltaIndex = create_pandas_abc_type("ABCTimedeltaIndex", "_typ",
28+
("timedeltaindex", ))
29+
ABCPeriodIndex = create_pandas_abc_type("ABCPeriodIndex", "_typ",
30+
("periodindex", ))
31+
ABCCategoricalIndex = create_pandas_abc_type("ABCCategoricalIndex", "_typ",
32+
("categoricalindex", ))
33+
ABCIndexClass = create_pandas_abc_type("ABCIndexClass", "_typ",
34+
("index", "int64index", "rangeindex",
35+
"float64index",
36+
"multiindex", "datetimeindex",
37+
"timedeltaindex", "periodindex",
38+
"categoricalindex"))
39+
40+
ABCSeries = create_pandas_abc_type("ABCSeries", "_typ", ("series", ))
41+
ABCDataFrame = create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe", ))
42+
ABCPanel = create_pandas_abc_type("ABCPanel", "_typ", ("panel", ))
43+
ABCSparseSeries = create_pandas_abc_type("ABCSparseSeries", "_subtyp",
44+
('sparse_series',
45+
'sparse_time_series'))
46+
ABCSparseArray = create_pandas_abc_type("ABCSparseArray", "_subtyp",
47+
('sparse_array', 'sparse_series'))
48+
ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ",
49+
("categorical"))
50+
ABCPeriod = create_pandas_abc_type("ABCPeriod", "_typ", ("period", ))
51+
52+
53+
class _ABCGeneric(type):
54+
def __instancecheck__(cls, inst):
55+
return hasattr(inst, "_data")
56+
57+
ABCGeneric = _ABCGeneric("ABCGeneric", tuple(), {})

0 commit comments

Comments
 (0)