Skip to content

Commit 9896bb1

Browse files
jbrockmendelPingviinituutti
authored andcommitted
modernize compat imports (pandas-dev#25192)
1 parent 7e566a3 commit 9896bb1

28 files changed

+61
-60
lines changed

pandas/compat/__init__.py

-11
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
* lists: lrange(), lmap(), lzip(), lfilter()
1010
* unicode: u() [no unicode builtin in Python 3]
1111
* longs: long (int in Python 3)
12-
* callable
1312
* iterable method compatibility: iteritems, iterkeys, itervalues
1413
* Uses the original method if available, otherwise uses items, keys, values.
1514
* types:
@@ -378,14 +377,6 @@ class ResourceWarning(Warning):
378377
string_and_binary_types = string_types + (binary_type,)
379378

380379

381-
try:
382-
# callable reintroduced in later versions of Python
383-
callable = callable
384-
except NameError:
385-
def callable(obj):
386-
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
387-
388-
389380
if PY2:
390381
# In PY2 functools.wraps doesn't provide metadata pytest needs to generate
391382
# decorated tests using parametrization. See pytest GH issue #2782
@@ -411,8 +402,6 @@ def wrapper(cls):
411402
return metaclass(cls.__name__, cls.__bases__, orig_vars)
412403
return wrapper
413404

414-
from collections import OrderedDict, Counter
415-
416405
if PY3:
417406
def raise_with_traceback(exc, traceback=Ellipsis):
418407
if traceback == Ellipsis:

pandas/compat/numpy/function.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
and methods that are spread throughout the codebase. This module will make it
1818
easier to adjust to future upstream changes in the analogous numpy signatures.
1919
"""
20+
from collections import OrderedDict
2021

2122
from numpy import ndarray
2223

23-
from pandas.compat import OrderedDict
2424
from pandas.errors import UnsupportedFunctionCall
2525
from pandas.util._validators import (
2626
validate_args, validate_args_and_kwargs, validate_kwargs)

pandas/core/base.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
"""
22
Base and utility classes for pandas objects.
33
"""
4+
from collections import OrderedDict
45
import textwrap
56
import warnings
67

78
import numpy as np
89

910
import pandas._libs.lib as lib
1011
import pandas.compat as compat
11-
from pandas.compat import PYPY, OrderedDict, builtins, map, range
12+
from pandas.compat import PYPY, builtins, map, range
1213
from pandas.compat.numpy import function as nv
1314
from pandas.errors import AbstractMethodError
1415
from pandas.util._decorators import Appender, Substitution, cache_readonly
@@ -376,7 +377,7 @@ def nested_renaming_depr(level=4):
376377
# eg. {'A' : ['mean']}, normalize all to
377378
# be list-likes
378379
if any(is_aggregator(x) for x in compat.itervalues(arg)):
379-
new_arg = compat.OrderedDict()
380+
new_arg = OrderedDict()
380381
for k, v in compat.iteritems(arg):
381382
if not isinstance(v, (tuple, list, dict)):
382383
new_arg[k] = [v]
@@ -444,22 +445,22 @@ def _agg(arg, func):
444445
run the aggregations over the arg with func
445446
return an OrderedDict
446447
"""
447-
result = compat.OrderedDict()
448+
result = OrderedDict()
448449
for fname, agg_how in compat.iteritems(arg):
449450
result[fname] = func(fname, agg_how)
450451
return result
451452

452453
# set the final keys
453454
keys = list(compat.iterkeys(arg))
454-
result = compat.OrderedDict()
455+
result = OrderedDict()
455456

456457
# nested renamer
457458
if is_nested_renamer:
458459
result = list(_agg(arg, _agg_1dim).values())
459460

460461
if all(isinstance(r, dict) for r in result):
461462

462-
result, results = compat.OrderedDict(), result
463+
result, results = OrderedDict(), result
463464
for r in results:
464465
result.update(r)
465466
keys = list(compat.iterkeys(result))

pandas/core/common.py

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

77
import collections
8+
from collections import OrderedDict
89
from datetime import datetime, timedelta
910
from functools import partial
1011
import inspect
@@ -13,7 +14,7 @@
1314

1415
from pandas._libs import lib, tslibs
1516
import pandas.compat as compat
16-
from pandas.compat import PY36, OrderedDict, iteritems
17+
from pandas.compat import PY36, iteritems
1718

1819
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
1920
from pandas.core.dtypes.common import (

pandas/core/computation/ops.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88

99
import numpy as np
1010

11+
from pandas._libs.tslibs import Timestamp
1112
from pandas.compat import PY3, string_types, text_type
1213

1314
from pandas.core.dtypes.common import is_list_like, is_scalar
1415

15-
import pandas as pd
1616
from pandas.core.base import StringMixin
1717
import pandas.core.common as com
1818
from pandas.core.computation.common import _ensure_decoded, _result_type_many
@@ -399,8 +399,9 @@ def evaluate(self, env, engine, parser, term_type, eval_in_python):
399399
if self.op in eval_in_python:
400400
res = self.func(left.value, right.value)
401401
else:
402-
res = pd.eval(self, local_dict=env, engine=engine,
403-
parser=parser)
402+
from pandas.core.computation.eval import eval
403+
res = eval(self, local_dict=env, engine=engine,
404+
parser=parser)
404405

405406
name = env.add_tmp(res)
406407
return term_type(name, env=env)
@@ -422,7 +423,7 @@ def stringify(value):
422423
v = rhs.value
423424
if isinstance(v, (int, float)):
424425
v = stringify(v)
425-
v = pd.Timestamp(_ensure_decoded(v))
426+
v = Timestamp(_ensure_decoded(v))
426427
if v.tz is not None:
427428
v = v.tz_convert('UTC')
428429
self.rhs.update(v)
@@ -431,7 +432,7 @@ def stringify(value):
431432
v = lhs.value
432433
if isinstance(v, (int, float)):
433434
v = stringify(v)
434-
v = pd.Timestamp(_ensure_decoded(v))
435+
v = Timestamp(_ensure_decoded(v))
435436
if v.tz is not None:
436437
v = v.tz_convert('UTC')
437438
self.lhs.update(v)

pandas/core/computation/pytables.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import numpy as np
77

8+
from pandas._libs.tslibs import Timedelta, Timestamp
89
from pandas.compat import DeepChainMap, string_types, u
910

1011
from pandas.core.dtypes.common import is_list_like
@@ -185,12 +186,12 @@ def stringify(value):
185186
if isinstance(v, (int, float)):
186187
v = stringify(v)
187188
v = _ensure_decoded(v)
188-
v = pd.Timestamp(v)
189+
v = Timestamp(v)
189190
if v.tz is not None:
190191
v = v.tz_convert('UTC')
191192
return TermValue(v, v.value, kind)
192193
elif kind == u('timedelta64') or kind == u('timedelta'):
193-
v = pd.Timedelta(v, unit='s').value
194+
v = Timedelta(v, unit='s').value
194195
return TermValue(int(v), v, kind)
195196
elif meta == u('category'):
196197
metadata = com.values_from_object(self.metadata)

pandas/core/computation/scope.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111

1212
import numpy as np
1313

14+
from pandas._libs.tslibs import Timestamp
1415
from pandas.compat import DeepChainMap, StringIO, map
1516

16-
import pandas as pd # noqa
1717
from pandas.core.base import StringMixin
1818
import pandas.core.computation as compu
1919

@@ -48,7 +48,7 @@ def _raw_hex_id(obj):
4848

4949

5050
_DEFAULT_GLOBALS = {
51-
'Timestamp': pd._libs.tslib.Timestamp,
51+
'Timestamp': Timestamp,
5252
'datetime': datetime.datetime,
5353
'True': True,
5454
'False': False,

pandas/core/frame.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from __future__ import division
1414

1515
import collections
16+
from collections import OrderedDict
1617
import functools
1718
import itertools
1819
import sys
@@ -33,7 +34,7 @@
3334

3435
from pandas import compat
3536
from pandas.compat import (range, map, zip, lmap, lzip, StringIO, u,
36-
OrderedDict, PY36, raise_with_traceback,
37+
PY36, raise_with_traceback,
3738
string_and_binary_types)
3839
from pandas.compat.numpy import function as nv
3940
from pandas.core.dtypes.cast import (

pandas/core/groupby/groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class providing the base-class of operations.
1818

1919
from pandas._libs import Timestamp, groupby as libgroupby
2020
import pandas.compat as compat
21-
from pandas.compat import callable, range, set_function_name, zip
21+
from pandas.compat import range, set_function_name, zip
2222
from pandas.compat.numpy import function as nv
2323
from pandas.errors import AbstractMethodError
2424
from pandas.util._decorators import Appender, Substitution, cache_readonly

pandas/core/groupby/grouper.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import numpy as np
99

1010
import pandas.compat as compat
11-
from pandas.compat import callable, zip
11+
from pandas.compat import zip
1212
from pandas.util._decorators import cache_readonly
1313

1414
from pandas.core.dtypes.common import (

pandas/core/panel.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44
# pylint: disable=E1103,W0231,W0212,W0621
55
from __future__ import division
66

7+
from collections import OrderedDict
78
import warnings
89

910
import numpy as np
1011

1112
import pandas.compat as compat
12-
from pandas.compat import OrderedDict, map, range, u, zip
13+
from pandas.compat import map, range, u, zip
1314
from pandas.compat.numpy import function as nv
1415
from pandas.util._decorators import Appender, Substitution, deprecate_kwarg
1516
from pandas.util._validators import validate_axis_style_args

pandas/core/resample.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
343343
grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis)
344344

345345
try:
346-
if isinstance(obj, ABCDataFrame) and compat.callable(how):
346+
if isinstance(obj, ABCDataFrame) and callable(how):
347347
# Check if the function is reducing or not.
348348
result = grouped._aggregate_item_by_item(how, *args, **kwargs)
349349
else:

pandas/core/series.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@
33
"""
44
from __future__ import division
55

6+
from collections import OrderedDict
67
from textwrap import dedent
78
import warnings
89

910
import numpy as np
1011

1112
from pandas._libs import iNaT, index as libindex, lib, tslibs
1213
import pandas.compat as compat
13-
from pandas.compat import PY36, OrderedDict, StringIO, u, zip
14+
from pandas.compat import PY36, StringIO, u, zip
1415
from pandas.compat.numpy import function as nv
1516
from pandas.util._decorators import Appender, Substitution, deprecate
1617
from pandas.util._validators import validate_bool_kwarg

pandas/core/sparse/scipy_sparse.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
44
Currently only includes SparseSeries.to_coo helpers.
55
"""
6-
from pandas.compat import OrderedDict, lmap
6+
from collections import OrderedDict
7+
8+
from pandas.compat import lmap
79

810
from pandas.core.index import Index, MultiIndex
911
from pandas.core.series import Series

pandas/io/excel.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
# ---------------------------------------------------------------------
66
# ExcelFile class
77
import abc
8+
from collections import OrderedDict
89
from datetime import date, datetime, time, timedelta
910
from distutils.version import LooseVersion
1011
from io import UnsupportedOperation
@@ -17,7 +18,7 @@
1718
import pandas._libs.json as json
1819
import pandas.compat as compat
1920
from pandas.compat import (
20-
OrderedDict, add_metaclass, lrange, map, range, string_types, u, zip)
21+
add_metaclass, lrange, map, range, string_types, u, zip)
2122
from pandas.errors import EmptyDataError
2223
from pandas.util._decorators import Appender, deprecate_kwarg
2324

@@ -274,7 +275,7 @@ def register_writer(klass):
274275
"""Adds engine to the excel writer registry. You must use this method to
275276
integrate with ``to_excel``. Also adds config options for any new
276277
``supported_extensions`` defined on the writer."""
277-
if not compat.callable(klass):
278+
if not callable(klass):
278279
raise ValueError("Can only register callables as engines")
279280
engine_name = klass.engine
280281
_writers[engine_name] = klass

pandas/io/formats/html.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55

66
from __future__ import print_function
77

8+
from collections import OrderedDict
89
from textwrap import dedent
910

10-
from pandas.compat import OrderedDict, lzip, map, range, u, unichr, zip
11+
from pandas.compat import lzip, map, range, u, unichr, zip
1112

1213
from pandas.core.dtypes.generic import ABCMultiIndex
1314

pandas/io/packers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ def read(fh):
219219
finally:
220220
if fh is not None:
221221
fh.close()
222-
elif hasattr(path_or_buf, 'read') and compat.callable(path_or_buf.read):
222+
elif hasattr(path_or_buf, 'read') and callable(path_or_buf.read):
223223
# treat as a buffer like
224224
return read(path_or_buf)
225225

pandas/tests/frame/test_constructors.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import print_function
44

5+
from collections import OrderedDict
56
from datetime import datetime, timedelta
67
import functools
78
import itertools
@@ -11,8 +12,7 @@
1112
import pytest
1213

1314
from pandas.compat import (
14-
PY3, PY36, OrderedDict, is_platform_little_endian, lmap, long, lrange,
15-
lzip, range, zip)
15+
PY3, PY36, is_platform_little_endian, lmap, long, lrange, lzip, range, zip)
1616

1717
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
1818
from pandas.core.dtypes.common import is_integer_dtype

pandas/tests/frame/test_dtypes.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import print_function
44

5+
from collections import OrderedDict
56
from datetime import timedelta
67

78
import numpy as np
@@ -66,7 +67,7 @@ def test_empty_frame_dtypes_ftypes(self):
6667
assert_series_equal(norows_int_df.ftypes, pd.Series(
6768
'int32:dense', index=list("abc")))
6869

69-
odict = compat.OrderedDict
70+
odict = OrderedDict
7071
df = pd.DataFrame(odict([('a', 1), ('b', True), ('c', 1.0)]),
7172
index=[1, 2, 3])
7273
ex_dtypes = pd.Series(odict([('a', np.int64),
@@ -100,7 +101,7 @@ def test_datetime_with_tz_dtypes(self):
100101
def test_dtypes_are_correct_after_column_slice(self):
101102
# GH6525
102103
df = pd.DataFrame(index=range(5), columns=list("abc"), dtype=np.float_)
103-
odict = compat.OrderedDict
104+
odict = OrderedDict
104105
assert_series_equal(df.dtypes,
105106
pd.Series(odict([('a', np.float_),
106107
('b', np.float_),
@@ -295,7 +296,7 @@ def test_select_dtypes_include_exclude_mixed_scalars_lists(self):
295296

296297
def test_select_dtypes_duplicate_columns(self):
297298
# GH20839
298-
odict = compat.OrderedDict
299+
odict = OrderedDict
299300
df = DataFrame(odict([('a', list('abc')),
300301
('b', list(range(1, 4))),
301302
('c', np.arange(3, 6).astype('u1')),

pandas/tests/groupby/aggregate/test_aggregate.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@
33
"""
44
test .agg behavior / note that .apply is tested generally in test_groupby.py
55
"""
6+
from collections import OrderedDict
67

78
import numpy as np
89
import pytest
910

10-
from pandas.compat import OrderedDict
11-
1211
import pandas as pd
1312
from pandas import DataFrame, Index, MultiIndex, Series, concat
1413
from pandas.core.base import SpecificationError

0 commit comments

Comments
 (0)