Skip to content

Commit 485cbbb

Browse files
jschendelWillAyd
authored andcommitted
CLN: Remove collections.abc classes from pandas.compat (pandas-dev#25957)
1 parent 00c119c commit 485cbbb

File tree

18 files changed

+70
-101
lines changed

18 files changed

+70
-101
lines changed

ci/code_checks.sh

+2
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,10 @@ fi
111111
if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then
112112

113113
# Check for imports from pandas.core.common instead of `import pandas.core.common as com`
114+
# Check for imports from collections.abc instead of `from collections import abc`
114115
MSG='Check for non-standard imports' ; echo $MSG
115116
invgrep -R --include="*.py*" -E "from pandas.core.common import " pandas
117+
invgrep -R --include="*.py*" -E "from collections.abc import " pandas
116118
# invgrep -R --include="*.py*" -E "from numpy import nan " pandas # GH#24822 not yet implemented since the offending imports have not all been removed
117119
RET=$(($RET + $?)) ; echo $MSG "DONE"
118120

pandas/compat/__init__.py

-20
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
import struct
3030
import inspect
3131
from collections import namedtuple
32-
import collections
3332

3433
PY2 = sys.version_info[0] == 2
3534
PY3 = sys.version_info[0] >= 3
@@ -106,16 +105,6 @@ def lmap(*args, **kwargs):
106105

107106
def lfilter(*args, **kwargs):
108107
return list(filter(*args, **kwargs))
109-
110-
Hashable = collections.abc.Hashable
111-
Iterable = collections.abc.Iterable
112-
Iterator = collections.abc.Iterator
113-
Mapping = collections.abc.Mapping
114-
MutableMapping = collections.abc.MutableMapping
115-
Sequence = collections.abc.Sequence
116-
Sized = collections.abc.Sized
117-
Set = collections.abc.Set
118-
119108
else:
120109
# Python 2
121110
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
@@ -138,15 +127,6 @@ def signature(f):
138127
lmap = builtins.map
139128
lfilter = builtins.filter
140129

141-
Hashable = collections.Hashable
142-
Iterable = collections.Iterable
143-
Iterator = collections.Iterator
144-
Mapping = collections.Mapping
145-
MutableMapping = collections.MutableMapping
146-
Sequence = collections.Sequence
147-
Sized = collections.Sized
148-
Set = collections.Set
149-
150130
if PY2:
151131
def iteritems(obj, **kw):
152132
return obj.iteritems(**kw)

pandas/core/arrays/sparse.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
SparseArray data structure
33
"""
4+
from collections import abc
45
import numbers
56
import operator
67
import re
@@ -1377,7 +1378,7 @@ def map(self, mapper):
13771378
if isinstance(mapper, ABCSeries):
13781379
mapper = mapper.to_dict()
13791380

1380-
if isinstance(mapper, compat.Mapping):
1381+
if isinstance(mapper, abc.Mapping):
13811382
fill_value = mapper.get(self.fill_value, self.fill_value)
13821383
sp_values = [mapper.get(x, None) for x in self.sp_values]
13831384
else:

pandas/core/common.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66

77
import collections
8-
from collections import OrderedDict
8+
from collections import OrderedDict, abc
99
from datetime import datetime, timedelta
1010
from functools import partial
1111
import inspect
@@ -14,7 +14,6 @@
1414
import numpy as np
1515

1616
from pandas._libs import lib, tslibs
17-
import pandas.compat as compat
1817
from pandas.compat import PY36, iteritems
1918

2019
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
@@ -374,13 +373,13 @@ def standardize_mapping(into):
374373
375374
Parameters
376375
----------
377-
into : instance or subclass of collections.Mapping
376+
into : instance or subclass of collections.abc.Mapping
378377
Must be a class, an initialized collections.defaultdict,
379-
or an instance of a collections.Mapping subclass.
378+
or an instance of a collections.abc.Mapping subclass.
380379
381380
Returns
382381
-------
383-
mapping : a collections.Mapping subclass or other constructor
382+
mapping : a collections.abc.Mapping subclass or other constructor
384383
a callable object that can accept an iterator to create
385384
the desired Mapping.
386385
@@ -394,7 +393,7 @@ def standardize_mapping(into):
394393
return partial(
395394
collections.defaultdict, into.default_factory)
396395
into = type(into)
397-
if not issubclass(into, compat.Mapping):
396+
if not issubclass(into, abc.Mapping):
398397
raise TypeError('unsupported type: {into}'.format(into=into))
399398
elif into == collections.defaultdict:
400399
raise TypeError(
@@ -471,7 +470,7 @@ def _get_rename_function(mapper):
471470
Returns a function that will map names/labels, dependent if mapper
472471
is a dict, Series or just a function.
473472
"""
474-
if isinstance(mapper, (compat.Mapping, ABCSeries)):
473+
if isinstance(mapper, (abc.Mapping, ABCSeries)):
475474

476475
def f(x):
477476
if x in mapper:

pandas/core/dtypes/inference.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
""" basic inference routines """
22

3+
from collections import abc
34
from numbers import Number
45
import re
56

67
import numpy as np
78

89
from pandas._libs import lib
9-
from pandas.compat import PY2, Set, re_type
10-
11-
from pandas import compat
10+
from pandas.compat import PY2, re_type
1211

1312
is_bool = lib.is_bool
1413

@@ -113,7 +112,7 @@ def _iterable_not_string(obj):
113112
False
114113
"""
115114

116-
return isinstance(obj, compat.Iterable) and not isinstance(obj, str)
115+
return isinstance(obj, abc.Iterable) and not isinstance(obj, str)
117116

118117

119118
def is_iterator(obj):
@@ -288,15 +287,15 @@ def is_list_like(obj, allow_sets=True):
288287
False
289288
"""
290289

291-
return (isinstance(obj, compat.Iterable) and
290+
return (isinstance(obj, abc.Iterable) and
292291
# we do not count strings/unicode/bytes as list-like
293292
not isinstance(obj, (str, bytes)) and
294293

295294
# exclude zero-dimensional numpy arrays, effectively scalars
296295
not (isinstance(obj, np.ndarray) and obj.ndim == 0) and
297296

298297
# exclude sets if allow_sets is False
299-
not (allow_sets is False and isinstance(obj, Set)))
298+
not (allow_sets is False and isinstance(obj, abc.Set)))
300299

301300

302301
def is_array_like(obj):
@@ -436,23 +435,23 @@ def is_named_tuple(obj):
436435
def is_hashable(obj):
437436
"""Return True if hash(obj) will succeed, False otherwise.
438437
439-
Some types will pass a test against collections.Hashable but fail when they
440-
are actually hashed with hash().
438+
Some types will pass a test against collections.abc.Hashable but fail when
439+
they are actually hashed with hash().
441440
442441
Distinguish between these and other types by trying the call to hash() and
443442
seeing if they raise TypeError.
444443
445444
Examples
446445
--------
447446
>>> a = ([],)
448-
>>> isinstance(a, collections.Hashable)
447+
>>> isinstance(a, collections.abc.Hashable)
449448
True
450449
>>> is_hashable(a)
451450
False
452451
"""
453-
# Unfortunately, we can't use isinstance(obj, collections.Hashable), which
454-
# can be faster than calling hash. That is because numpy scalars on Python
455-
# 3 fail this test.
452+
# Unfortunately, we can't use isinstance(obj, collections.abc.Hashable),
453+
# which can be faster than calling hash. That is because numpy scalars
454+
# fail this test.
456455

457456
# Reconsider this decision once this numpy bug is fixed:
458457
# https://github.com/numpy/numpy/issues/5562

pandas/core/frame.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
labeling information
1212
"""
1313
import collections
14-
from collections import OrderedDict
14+
from collections import OrderedDict, abc
1515
import functools
1616
import itertools
1717
import sys
@@ -33,8 +33,7 @@
3333
validate_axis_style_args)
3434

3535
from pandas import compat
36-
from pandas.compat import (
37-
PY36, Iterator, StringIO, lmap, lzip, raise_with_traceback)
36+
from pandas.compat import PY36, StringIO, lmap, lzip, raise_with_traceback
3837
from pandas.compat.numpy import function as nv
3938
from pandas.core.dtypes.cast import (
4039
maybe_upcast,
@@ -426,9 +425,9 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
426425
copy=copy)
427426

428427
# For data is list-like, or Iterable (will consume into list)
429-
elif (isinstance(data, compat.Iterable) and
428+
elif (isinstance(data, abc.Iterable) and
430429
not isinstance(data, (str, bytes))):
431-
if not isinstance(data, compat.Sequence):
430+
if not isinstance(data, abc.Sequence):
432431
data = list(data)
433432
if len(data) > 0:
434433
if is_list_like(data[0]) and getattr(data[0], 'ndim', 1) == 1:
@@ -1203,7 +1202,7 @@ def to_dict(self, orient='dict', into=dict):
12031202
indicates `split`.
12041203
12051204
into : class, default dict
1206-
The collections.Mapping subclass used for all Mappings
1205+
The collections.abc.Mapping subclass used for all Mappings
12071206
in the return value. Can be the actual class or an empty
12081207
instance of the mapping type you want. If you want a
12091208
collections.defaultdict, you must pass it initialized.
@@ -1212,8 +1211,8 @@ def to_dict(self, orient='dict', into=dict):
12121211
12131212
Returns
12141213
-------
1215-
dict, list or collections.Mapping
1216-
Return a collections.Mapping object representing the DataFrame.
1214+
dict, list or collections.abc.Mapping
1215+
Return a collections.abc.Mapping object representing the DataFrame.
12171216
The resulting transformation depends on the `orient` parameter.
12181217
12191218
See Also
@@ -4080,7 +4079,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
40804079
the same length as the calling DataFrame, or a list containing an
40814080
arbitrary combination of column keys and arrays. Here, "array"
40824081
encompasses :class:`Series`, :class:`Index`, ``np.ndarray``, and
4083-
instances of :class:`abc.Iterator`.
4082+
instances of :class:`~collections.abc.Iterator`.
40844083
drop : bool, default True
40854084
Delete columns to be used as the new index.
40864085
append : bool, default False
@@ -4166,7 +4165,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
41664165
missing = []
41674166
for col in keys:
41684167
if isinstance(col, (ABCIndexClass, ABCSeries, np.ndarray,
4169-
list, Iterator)):
4168+
list, abc.Iterator)):
41704169
# arrays are fine as long as they are one-dimensional
41714170
# iterators get converted to list below
41724171
if getattr(col, 'ndim', 1) != 1:
@@ -4213,7 +4212,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
42134212
elif isinstance(col, (list, np.ndarray)):
42144213
arrays.append(col)
42154214
names.append(None)
4216-
elif isinstance(col, Iterator):
4215+
elif isinstance(col, abc.Iterator):
42174216
arrays.append(list(col))
42184217
names.append(None)
42194218
# from here, col can only be a column label

pandas/core/groupby/generic.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
which here returns a DataFrameGroupBy object.
77
"""
88

9-
import collections
9+
from collections import OrderedDict, abc
1010
import copy
1111
from functools import partial
1212
from textwrap import dedent
@@ -226,7 +226,7 @@ def _aggregate_generic(self, func, *args, **kwargs):
226226
axis = self.axis
227227
obj = self._obj_with_exclusions
228228

229-
result = collections.OrderedDict()
229+
result = OrderedDict()
230230
if axis != obj._info_axis_number:
231231
try:
232232
for name, data in self:
@@ -253,7 +253,7 @@ def _aggregate_item_by_item(self, func, *args, **kwargs):
253253
# only for axis==0
254254

255255
obj = self._obj_with_exclusions
256-
result = collections.OrderedDict()
256+
result = OrderedDict()
257257
cannot_agg = []
258258
errors = None
259259
for item in obj:
@@ -770,7 +770,7 @@ def aggregate(self, func_or_funcs, *args, **kwargs):
770770
if isinstance(func_or_funcs, str):
771771
return getattr(self, func_or_funcs)(*args, **kwargs)
772772

773-
if isinstance(func_or_funcs, compat.Iterable):
773+
if isinstance(func_or_funcs, abc.Iterable):
774774
# Catch instances of lists / tuples
775775
# but not the class list / tuple itself.
776776
ret = self._aggregate_multiple_funcs(func_or_funcs,
@@ -834,7 +834,7 @@ def _aggregate_multiple_funcs(self, arg, _level):
834834
columns.append(com.get_callable_name(f))
835835
arg = lzip(columns, arg)
836836

837-
results = collections.OrderedDict()
837+
results = OrderedDict()
838838
for name, func in arg:
839839
obj = self
840840
if name in results:
@@ -911,7 +911,7 @@ def _get_index():
911911
name=self._selection_name)
912912

913913
def _aggregate_named(self, func, *args, **kwargs):
914-
result = collections.OrderedDict()
914+
result = OrderedDict()
915915

916916
for name, group in self:
917917
group.name = name
@@ -1507,7 +1507,7 @@ def _apply_to_column_groupbys(self, func):
15071507
def _fill(self, direction, limit=None):
15081508
"""Overridden method to join grouped columns in output"""
15091509
res = super(DataFrameGroupBy, self)._fill(direction, limit=limit)
1510-
output = collections.OrderedDict(
1510+
output = OrderedDict(
15111511
(grp.name, grp.grouper) for grp in self.grouper.groupings)
15121512

15131513
from pandas import concat

pandas/core/internals/construction.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@
22
Functions for preparing various inputs passed to the DataFrame or Series
33
constructors before passing them to a BlockManager.
44
"""
5-
from collections import OrderedDict
5+
from collections import OrderedDict, abc
66

77
import numpy as np
88
import numpy.ma as ma
99

1010
from pandas._libs import lib
1111
from pandas._libs.tslibs import IncompatibleFrequency
12-
import pandas.compat as compat
1312
from pandas.compat import lmap, lrange, raise_with_traceback
1413

1514
from pandas.core.dtypes.cast import (
@@ -395,7 +394,7 @@ def to_arrays(data, columns, coerce_float=False, dtype=None):
395394
if isinstance(data[0], (list, tuple)):
396395
return _list_to_arrays(data, columns, coerce_float=coerce_float,
397396
dtype=dtype)
398-
elif isinstance(data[0], compat.Mapping):
397+
elif isinstance(data[0], abc.Mapping):
399398
return _list_of_dict_to_arrays(data, columns,
400399
coerce_float=coerce_float, dtype=dtype)
401400
elif isinstance(data[0], ABCSeries):

pandas/core/series.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
Data structure for 1-dimensional cross-sectional and time series data
33
"""
4-
from collections import OrderedDict
4+
from collections import OrderedDict, abc
55
from shutil import get_terminal_size
66
from textwrap import dedent
77
import warnings
@@ -224,8 +224,8 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
224224
raise TypeError("{0!r} type is unordered"
225225
"".format(data.__class__.__name__))
226226
# If data is Iterable but not list-like, consume into list.
227-
elif (isinstance(data, compat.Iterable)
228-
and not isinstance(data, compat.Sized)):
227+
elif (isinstance(data, abc.Iterable) and
228+
not isinstance(data, abc.Sized)):
229229
data = list(data)
230230
else:
231231

@@ -1496,7 +1496,7 @@ def to_dict(self, into=dict):
14961496
Parameters
14971497
----------
14981498
into : class, default dict
1499-
The collections.Mapping subclass to use as the return
1499+
The collections.abc.Mapping subclass to use as the return
15001500
object. Can be the actual class or an empty
15011501
instance of the mapping type you want. If you want a
15021502
collections.defaultdict, you must pass it initialized.
@@ -1505,7 +1505,7 @@ def to_dict(self, into=dict):
15051505
15061506
Returns
15071507
-------
1508-
collections.Mapping
1508+
collections.abc.Mapping
15091509
Key-value representation of Series.
15101510
15111511
Examples

0 commit comments

Comments
 (0)