Skip to content

Commit ee36aae

Browse files
jbrockmendelquintusdias
authored andcommitted
CLN: avoid runtime imports (pandas-dev#27461)
1 parent 8c971d9 commit ee36aae

21 files changed

+75
-111
lines changed

pandas/_libs/lib.pyx

+7-7
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,13 @@ def is_scalar(val: object) -> bool:
157157

158158
return (cnp.PyArray_IsAnyScalar(val)
159159
# PyArray_IsAnyScalar is always False for bytearrays on Py3
160-
or isinstance(val, (Fraction, Number))
161-
# We differ from numpy, which claims that None is not scalar;
162-
# see np.isscalar
163-
or val is None
164160
or PyDate_Check(val)
165161
or PyDelta_Check(val)
166162
or PyTime_Check(val)
163+
# We differ from numpy, which claims that None is not scalar;
164+
# see np.isscalar
165+
or val is None
166+
or isinstance(val, (Fraction, Number))
167167
or util.is_period_object(val)
168168
or is_decimal(val)
169169
or is_interval(val)
@@ -1192,7 +1192,9 @@ def infer_dtype(value: object, skipna: object=None) -> str:
11921192
# e.g. categoricals
11931193
try:
11941194
values = getattr(value, '_values', getattr(value, 'values', value))
1195-
except:
1195+
except TypeError:
1196+
# This gets hit if we have an EA, since cython expects `values`
1197+
# to be an ndarray
11961198
value = _try_infer_map(value)
11971199
if value is not None:
11981200
return value
@@ -1208,8 +1210,6 @@ def infer_dtype(value: object, skipna: object=None) -> str:
12081210
construct_1d_object_array_from_listlike)
12091211
values = construct_1d_object_array_from_listlike(value)
12101212

1211-
values = getattr(values, 'values', values)
1212-
12131213
# make contiguous
12141214
values = values.ravel()
12151215

pandas/compat/pickle_compat.py

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import pickle as pkl
77
import sys
88

9-
import pandas # noqa
109
from pandas import Index
1110

1211

pandas/core/algorithms.py

+1-7
Original file line numberDiff line numberDiff line change
@@ -1977,12 +1977,6 @@ def diff(arr, n, axis=0):
19771977
out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
19781978

19791979
if is_timedelta:
1980-
from pandas import TimedeltaIndex
1981-
1982-
out_arr = (
1983-
TimedeltaIndex(out_arr.ravel().astype("int64"))
1984-
.asi8.reshape(out_arr.shape)
1985-
.astype("timedelta64[ns]")
1986-
)
1980+
out_arr = out_arr.astype("int64").view("timedelta64[ns]")
19871981

19881982
return out_arr

pandas/core/arrays/array_.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ def array(
212212
"""
213213
from pandas.core.arrays import (
214214
period_array,
215-
ExtensionArray,
216215
IntervalArray,
217216
PandasArray,
218217
DatetimeArray,
@@ -226,7 +225,7 @@ def array(
226225

227226
data = extract_array(data, extract_numpy=True)
228227

229-
if dtype is None and isinstance(data, ExtensionArray):
228+
if dtype is None and isinstance(data, ABCExtensionArray):
230229
dtype = data.dtype
231230

232231
# this returns None for not-found dtypes.

pandas/core/arrays/categorical.py

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

77
from pandas._config import get_option
88

9-
from pandas._libs import algos as libalgos, lib
9+
from pandas._libs import algos as libalgos, hashtable as htable, lib
1010
from pandas.compat.numpy import function as nv
1111
from pandas.util._decorators import (
1212
Appender,
@@ -50,7 +50,14 @@
5050
from pandas.core import ops
5151
from pandas.core.accessor import PandasDelegate, delegate_names
5252
import pandas.core.algorithms as algorithms
53-
from pandas.core.algorithms import factorize, take, take_1d, unique1d
53+
from pandas.core.algorithms import (
54+
_get_data_algo,
55+
_hashtables,
56+
factorize,
57+
take,
58+
take_1d,
59+
unique1d,
60+
)
5461
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
5562
import pandas.core.common as com
5663
from pandas.core.missing import interpolate_2d
@@ -1527,9 +1534,7 @@ def value_counts(self, dropna=True):
15271534
See Also
15281535
--------
15291536
Series.value_counts
1530-
15311537
"""
1532-
from numpy import bincount
15331538
from pandas import Series, CategoricalIndex
15341539

15351540
code, cat = self._codes, self.categories
@@ -1538,9 +1543,9 @@ def value_counts(self, dropna=True):
15381543

15391544
if dropna or clean:
15401545
obs = code if clean else code[mask]
1541-
count = bincount(obs, minlength=ncat or 0)
1546+
count = np.bincount(obs, minlength=ncat or 0)
15421547
else:
1543-
count = bincount(np.where(mask, code, ncat))
1548+
count = np.bincount(np.where(mask, code, ncat))
15441549
ix = np.append(ix, -1)
15451550

15461551
ix = self._constructor(ix, dtype=self.dtype, fastpath=True)
@@ -2329,9 +2334,6 @@ def mode(self, dropna=True):
23292334
-------
23302335
modes : `Categorical` (sorted)
23312336
"""
2332-
2333-
import pandas._libs.hashtable as htable
2334-
23352337
codes = self._codes
23362338
if dropna:
23372339
good = self._codes != -1
@@ -2671,8 +2673,6 @@ def _get_codes_for_values(values, categories):
26712673
"""
26722674
utility routine to turn values into codes given the specified categories
26732675
"""
2674-
from pandas.core.algorithms import _get_data_algo, _hashtables
2675-
26762676
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
26772677

26782678
if dtype_equal:
@@ -2722,8 +2722,6 @@ def _recode_for_categories(codes, old_categories, new_categories):
27222722
>>> _recode_for_categories(codes, old_cat, new_cat)
27232723
array([ 1, 0, 0, -1])
27242724
"""
2725-
from pandas.core.algorithms import take_1d
2726-
27272725
if len(old_categories) == 0:
27282726
# All null anyway, so just retain the nulls
27292727
return codes.copy()

pandas/core/arrays/datetimelike.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@
3434
is_unsigned_integer_dtype,
3535
pandas_dtype,
3636
)
37-
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
37+
from pandas.core.dtypes.generic import (
38+
ABCDataFrame,
39+
ABCIndexClass,
40+
ABCPeriodArray,
41+
ABCSeries,
42+
)
3843
from pandas.core.dtypes.inference import is_array_like
3944
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
4045

@@ -1679,11 +1684,10 @@ def _ensure_datetimelike_to_i8(other, to_utc=False):
16791684
i8 1d array
16801685
"""
16811686
from pandas import Index
1682-
from pandas.core.arrays import PeriodArray
16831687

16841688
if lib.is_scalar(other) and isna(other):
16851689
return iNaT
1686-
elif isinstance(other, (PeriodArray, ABCIndexClass, DatetimeLikeArrayMixin)):
1690+
elif isinstance(other, (ABCPeriodArray, ABCIndexClass, DatetimeLikeArrayMixin)):
16871691
# convert tz if needed
16881692
if getattr(other, "tz", None) is not None:
16891693
if to_utc:

pandas/core/arrays/integer.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from pandas.core.dtypes.missing import isna, notna
2626

2727
from pandas.core import nanops, ops
28+
from pandas.core.algorithms import take
2829
from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
2930
from pandas.core.tools.numeric import to_numeric
3031

@@ -420,8 +421,6 @@ def __iter__(self):
420421
yield self._data[i]
421422

422423
def take(self, indexer, allow_fill=False, fill_value=None):
423-
from pandas.api.extensions import take
424-
425424
# we always fill with 1 internally
426425
# to avoid upcasting
427426
data_fill_value = 1 if isna(fill_value) else fill_value

pandas/core/arrays/interval.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from pandas.core.dtypes.dtypes import IntervalDtype
2626
from pandas.core.dtypes.generic import (
2727
ABCDatetimeIndex,
28+
ABCIndexClass,
2829
ABCInterval,
2930
ABCIntervalIndex,
3031
ABCPeriodIndex,
@@ -35,7 +36,7 @@
3536
from pandas.core.arrays.base import ExtensionArray, _extension_array_shared_docs
3637
from pandas.core.arrays.categorical import Categorical
3738
import pandas.core.common as com
38-
from pandas.core.indexes.base import Index, ensure_index
39+
from pandas.core.indexes.base import ensure_index
3940

4041
_VALID_CLOSED = {"left", "right", "both", "neither"}
4142
_interval_shared_docs = {}
@@ -510,7 +511,7 @@ def __getitem__(self, value):
510511
right = self.right[value]
511512

512513
# scalar
513-
if not isinstance(left, Index):
514+
if not isinstance(left, ABCIndexClass):
514515
if isna(left):
515516
return self._fill_value
516517
return Interval(left, right, self.closed)

pandas/core/arrays/numpy_.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@
1111
from pandas.core.dtypes.dtypes import ExtensionDtype
1212
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
1313
from pandas.core.dtypes.inference import is_array_like, is_list_like
14+
from pandas.core.dtypes.missing import isna
1415

1516
from pandas import compat
1617
from pandas.core import nanops
17-
from pandas.core.algorithms import searchsorted
18+
from pandas.core.algorithms import searchsorted, take, unique
1819
from pandas.core.missing import backfill_1d, pad_1d
1920

2021
from .base import ExtensionArray, ExtensionOpsMixin
@@ -249,8 +250,6 @@ def nbytes(self):
249250
return self._ndarray.nbytes
250251

251252
def isna(self):
252-
from pandas import isna
253-
254253
return isna(self._ndarray)
255254

256255
def fillna(self, value=None, method=None, limit=None):
@@ -281,8 +280,6 @@ def fillna(self, value=None, method=None, limit=None):
281280
return new_values
282281

283282
def take(self, indices, allow_fill=False, fill_value=None):
284-
from pandas.core.algorithms import take
285-
286283
result = take(
287284
self._ndarray, indices, allow_fill=allow_fill, fill_value=fill_value
288285
)
@@ -298,8 +295,6 @@ def _values_for_factorize(self):
298295
return self._ndarray, -1
299296

300297
def unique(self):
301-
from pandas import unique
302-
303298
return type(self)(unique(self._ndarray))
304299

305300
# ------------------------------------------------------------------------

pandas/core/arrays/sparse.py

-10
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,6 @@ class SparseDtype(ExtensionDtype):
105105
_metadata = ("_dtype", "_fill_value", "_is_na_fill_value")
106106

107107
def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None:
108-
from pandas.core.dtypes.missing import na_value_for_dtype
109-
from pandas.core.dtypes.common import pandas_dtype, is_string_dtype, is_scalar
110108

111109
if isinstance(dtype, type(self)):
112110
if fill_value is None:
@@ -178,20 +176,14 @@ def fill_value(self):
178176

179177
@property
180178
def _is_na_fill_value(self):
181-
from pandas.core.dtypes.missing import isna
182-
183179
return isna(self.fill_value)
184180

185181
@property
186182
def _is_numeric(self):
187-
from pandas.core.dtypes.common import is_object_dtype
188-
189183
return not is_object_dtype(self.subtype)
190184

191185
@property
192186
def _is_boolean(self):
193-
from pandas.core.dtypes.common import is_bool_dtype
194-
195187
return is_bool_dtype(self.subtype)
196188

197189
@property
@@ -928,8 +920,6 @@ def values(self):
928920
return self.to_dense()
929921

930922
def isna(self):
931-
from pandas import isna
932-
933923
# If null fill value, we want SparseDtype[bool, true]
934924
# to preserve the same memory usage.
935925
dtype = SparseDtype(bool, self._null_fill_value)

pandas/core/base.py

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

3333
from pandas.core import algorithms, common as com
3434
from pandas.core.accessor import DirNamesMixin
35+
from pandas.core.algorithms import duplicated, unique1d, value_counts
3536
from pandas.core.arrays import ExtensionArray
3637
import pandas.core.nanops as nanops
3738

@@ -1381,8 +1382,6 @@ def value_counts(
13811382
1.0 1
13821383
dtype: int64
13831384
"""
1384-
from pandas.core.algorithms import value_counts
1385-
13861385
result = value_counts(
13871386
self,
13881387
sort=sort,
@@ -1400,8 +1399,6 @@ def unique(self):
14001399

14011400
result = values.unique()
14021401
else:
1403-
from pandas.core.algorithms import unique1d
1404-
14051402
result = unique1d(values)
14061403

14071404
return result
@@ -1631,8 +1628,6 @@ def drop_duplicates(self, keep="first", inplace=False):
16311628
return result
16321629

16331630
def duplicated(self, keep="first"):
1634-
from pandas.core.algorithms import duplicated
1635-
16361631
if isinstance(self, ABCIndexClass):
16371632
if self.is_unique:
16381633
return np.zeros(len(self), dtype=np.bool)

pandas/core/common.py

-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,6 @@ def asarray_tuplesafe(values, dtype=None):
254254

255255
if result.ndim == 2:
256256
# Avoid building an array of arrays:
257-
# TODO: verify whether any path hits this except #18819 (invalid)
258257
values = [tuple(x) for x in values]
259258
result = construct_1d_object_array_from_listlike(values)
260259

pandas/core/dtypes/concat.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -361,9 +361,7 @@ def _maybe_unwrap(x):
361361
new_codes = np.concatenate(codes)
362362

363363
if sort_categories and not ignore_order and ordered:
364-
raise TypeError(
365-
"Cannot use sort_categories=True with " "ordered Categoricals"
366-
)
364+
raise TypeError("Cannot use sort_categories=True with ordered Categoricals")
367365

368366
if sort_categories and not categories.is_monotonic_increasing:
369367
categories = categories.sort_values()
@@ -386,7 +384,7 @@ def _maybe_unwrap(x):
386384
else:
387385
# ordered - to show a proper error message
388386
if all(c.ordered for c in to_union):
389-
msg = "to union ordered Categoricals, " "all categories must be the same"
387+
msg = "to union ordered Categoricals, all categories must be the same"
390388
raise TypeError(msg)
391389
else:
392390
raise TypeError("Categorical.ordered must be the same")

pandas/core/dtypes/dtypes.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCDateOffset, ABCIndexClass
1313

1414
from .base import ExtensionDtype
15-
from .inference import is_list_like
15+
from .inference import is_bool, is_list_like
1616

1717
str_type = str
1818

@@ -149,7 +149,7 @@ def __repr__(self) -> str_type:
149149
return str(self)
150150

151151
def __hash__(self) -> int:
152-
raise NotImplementedError("sub-classes should implement an __hash__ " "method")
152+
raise NotImplementedError("sub-classes should implement an __hash__ method")
153153

154154
def __getstate__(self) -> Dict[str_type, Any]:
155155
# pickle support; we don't want to pickle the cache
@@ -320,7 +320,7 @@ def _from_values_or_dtype(
320320
raise ValueError(msg.format(dtype=dtype))
321321
elif categories is not None or ordered is not None:
322322
raise ValueError(
323-
"Cannot specify `categories` or `ordered` " "together with `dtype`."
323+
"Cannot specify `categories` or `ordered` together with `dtype`."
324324
)
325325
elif is_categorical(values):
326326
# If no "dtype" was passed, use the one from "values", but honor
@@ -490,8 +490,6 @@ def validate_ordered(ordered: OrderedType) -> None:
490490
TypeError
491491
If 'ordered' is not a boolean.
492492
"""
493-
from pandas.core.dtypes.common import is_bool
494-
495493
if not is_bool(ordered):
496494
raise TypeError("'ordered' must either be 'True' or 'False'")
497495

0 commit comments

Comments
 (0)