Skip to content

Commit a0a76a1

Browse files
rhshadrachnickleus27
authored andcommitted
ENH: Use find_stack_level in pandas.core (pandas-dev#44358)
1 parent 66147c9 commit a0a76a1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+169
-135
lines changed

pandas/core/accessor.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import warnings
1010

1111
from pandas.util._decorators import doc
12+
from pandas.util._exceptions import find_stack_level
1213

1314

1415
class DirNamesMixin:
@@ -267,7 +268,7 @@ def decorator(accessor):
267268
f"{repr(name)} for type {repr(cls)} is overriding a preexisting "
268269
f"attribute with the same name.",
269270
UserWarning,
270-
stacklevel=2,
271+
stacklevel=find_stack_level(),
271272
)
272273
setattr(cls, name, CachedAccessor(name, accessor))
273274
cls._accessors.add(name)

pandas/core/arraylike.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import numpy as np
1212

1313
from pandas._libs import lib
14+
from pandas.util._exceptions import find_stack_level
1415

1516
from pandas.core.construction import extract_array
1617
from pandas.core.ops import (
@@ -210,7 +211,7 @@ def _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any):
210211
"or align manually (eg 'df1, df2 = df1.align(df2)') before passing to "
211212
"the ufunc to obtain the future behaviour and silence this warning.",
212213
FutureWarning,
213-
stacklevel=4,
214+
stacklevel=find_stack_level(),
214215
)
215216

216217
# keep the first dataframe of the inputs, other DataFrame/Series is

pandas/core/arrays/categorical.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ def __init__(
390390
"Allowing scalars in the Categorical constructor is deprecated "
391391
"and will raise in a future version. Use `[value]` instead",
392392
FutureWarning,
393-
stacklevel=2,
393+
stacklevel=find_stack_level(),
394394
)
395395
values = [values]
396396

@@ -940,7 +940,7 @@ def set_categories(
940940
"a future version. Removing unused categories will always "
941941
"return a new Categorical object.",
942942
FutureWarning,
943-
stacklevel=2,
943+
stacklevel=find_stack_level(),
944944
)
945945
else:
946946
inplace = False
@@ -1040,7 +1040,7 @@ def rename_categories(self, new_categories, inplace=no_default):
10401040
"a future version. Removing unused categories will always "
10411041
"return a new Categorical object.",
10421042
FutureWarning,
1043-
stacklevel=2,
1043+
stacklevel=find_stack_level(),
10441044
)
10451045
else:
10461046
inplace = False
@@ -1172,7 +1172,7 @@ def add_categories(self, new_categories, inplace=no_default):
11721172
"a future version. Removing unused categories will always "
11731173
"return a new Categorical object.",
11741174
FutureWarning,
1175-
stacklevel=2,
1175+
stacklevel=find_stack_level(),
11761176
)
11771177
else:
11781178
inplace = False
@@ -1247,7 +1247,7 @@ def remove_categories(self, removals, inplace=no_default):
12471247
"a future version. Removing unused categories will always "
12481248
"return a new Categorical object.",
12491249
FutureWarning,
1250-
stacklevel=2,
1250+
stacklevel=find_stack_level(),
12511251
)
12521252
else:
12531253
inplace = False
@@ -1322,7 +1322,7 @@ def remove_unused_categories(self, inplace=no_default):
13221322
"remove_unused_categories is deprecated and "
13231323
"will be removed in a future version.",
13241324
FutureWarning,
1325-
stacklevel=2,
1325+
stacklevel=find_stack_level(),
13261326
)
13271327
else:
13281328
inplace = False
@@ -1879,7 +1879,7 @@ def to_dense(self) -> np.ndarray:
18791879
"Categorical.to_dense is deprecated and will be removed in "
18801880
"a future version. Use np.asarray(cat) instead.",
18811881
FutureWarning,
1882-
stacklevel=2,
1882+
stacklevel=find_stack_level(),
18831883
)
18841884
return np.asarray(self)
18851885

@@ -1896,7 +1896,7 @@ def _codes(self, value: np.ndarray):
18961896
"Setting the codes on a Categorical is deprecated and will raise in "
18971897
"a future version. Create a new Categorical object instead",
18981898
FutureWarning,
1899-
stacklevel=2,
1899+
stacklevel=find_stack_level(),
19001900
) # GH#40606
19011901
NDArrayBacked.__init__(self, value, self.dtype)
19021902

@@ -1919,7 +1919,7 @@ def take_nd(self, indexer, allow_fill: bool = False, fill_value=None):
19191919
warn(
19201920
"Categorical.take_nd is deprecated, use Categorical.take instead",
19211921
FutureWarning,
1922-
stacklevel=2,
1922+
stacklevel=find_stack_level(),
19231923
)
19241924
return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value)
19251925

@@ -2339,7 +2339,7 @@ def is_dtype_equal(self, other) -> bool:
23392339
"Categorical.is_dtype_equal is deprecated and will be removed "
23402340
"in a future version",
23412341
FutureWarning,
2342-
stacklevel=2,
2342+
stacklevel=find_stack_level(),
23432343
)
23442344
try:
23452345
return self._categories_match_up_to_permutation(other)

pandas/core/arrays/datetimes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1206,7 +1206,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray:
12061206
"Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.",
12071207
FutureWarning,
12081208
# stacklevel chosen to be correct for when called from DatetimeIndex
1209-
stacklevel=3,
1209+
stacklevel=find_stack_level(),
12101210
)
12111211
from pandas.core.arrays.timedeltas import TimedeltaArray
12121212

@@ -1373,7 +1373,7 @@ def weekofyear(self):
13731373
"weekofyear and return an Index, you may call "
13741374
"pd.Int64Index(idx.isocalendar().week)",
13751375
FutureWarning,
1376-
stacklevel=3,
1376+
stacklevel=find_stack_level(),
13771377
)
13781378
week_series = self.isocalendar().week
13791379
if week_series.hasnans:

pandas/core/arrays/sparse/array.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def __init__(
467467
"loses timezone information. Cast to object before "
468468
"sparse to retain timezone information.",
469469
UserWarning,
470-
stacklevel=2,
470+
stacklevel=find_stack_level(),
471471
)
472472
data = np.asarray(data, dtype="datetime64[ns]")
473473
if fill_value is NaT:
@@ -1089,7 +1089,7 @@ def searchsorted(
10891089
) -> npt.NDArray[np.intp] | np.intp:
10901090

10911091
msg = "searchsorted requires high memory usage."
1092-
warnings.warn(msg, PerformanceWarning, stacklevel=2)
1092+
warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level())
10931093
if not is_scalar(v):
10941094
v = np.asarray(v)
10951095
v = np.asarray(v)

pandas/core/arrays/sparse/dtype.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
type_t,
1717
)
1818
from pandas.errors import PerformanceWarning
19+
from pandas.util._exceptions import find_stack_level
1920

2021
from pandas.core.dtypes.base import (
2122
ExtensionDtype,
@@ -389,7 +390,7 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
389390
f"values: '{fill_values}'. Picking the first and "
390391
"converting the rest.",
391392
PerformanceWarning,
392-
stacklevel=6,
393+
stacklevel=find_stack_level(),
393394
)
394395

395396
np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes]

pandas/core/common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
Scalar,
3737
T,
3838
)
39+
from pandas.util._exceptions import find_stack_level
3940

4041
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
4142
from pandas.core.dtypes.common import (
@@ -175,7 +176,7 @@ def cast_scalar_indexer(val, warn_float: bool = False):
175176
"Indexing with a float is deprecated, and will raise an IndexError "
176177
"in pandas 2.0. You can manually convert to an integer key instead.",
177178
FutureWarning,
178-
stacklevel=3,
179+
stacklevel=find_stack_level(),
179180
)
180181
return int(val)
181182
return val

pandas/core/computation/align.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import numpy as np
1717

1818
from pandas.errors import PerformanceWarning
19+
from pandas.util._exceptions import find_stack_level
1920

2021
from pandas.core.dtypes.generic import (
2122
ABCDataFrame,
@@ -126,7 +127,9 @@ def _align_core(terms):
126127
f"than an order of magnitude on term {repr(terms[i].name)}, "
127128
f"by more than {ordm:.4g}; performance may suffer."
128129
)
129-
warnings.warn(w, category=PerformanceWarning, stacklevel=6)
130+
warnings.warn(
131+
w, category=PerformanceWarning, stacklevel=find_stack_level()
132+
)
130133

131134
f = partial(ti.reindex, reindexer, axis=axis, copy=False)
132135

pandas/core/computation/eval.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import warnings
88

99
from pandas._libs.lib import no_default
10+
from pandas.util._exceptions import find_stack_level
1011
from pandas.util._validators import validate_bool_kwarg
1112

1213
from pandas.core.computation.engines import ENGINES
@@ -308,7 +309,7 @@ def eval(
308309
"will be removed in a future version."
309310
),
310311
FutureWarning,
311-
stacklevel=2,
312+
stacklevel=find_stack_level(),
312313
)
313314

314315
exprs: list[str | BinOp]

pandas/core/config_init.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
is_text,
2626
)
2727

28+
from pandas.util._exceptions import find_stack_level
29+
2830
# compute
2931

3032
use_bottleneck_doc = """
@@ -373,7 +375,7 @@ def _deprecate_negative_int_max_colwidth(key):
373375
"will not be supported in future version. Instead, use None "
374376
"to not limit the column width.",
375377
FutureWarning,
376-
stacklevel=4,
378+
stacklevel=find_stack_level(),
377379
)
378380

379381
cf.register_option(

pandas/core/construction.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
DtypeObj,
2626
)
2727
from pandas.errors import IntCastingNaNError
28+
from pandas.util._exceptions import find_stack_level
2829

2930
from pandas.core.dtypes.base import (
3031
ExtensionDtype,
@@ -538,7 +539,7 @@ def sanitize_array(
538539
"if they cannot be cast losslessly (matching Series behavior). "
539540
"To retain the old behavior, use DataFrame(data).astype(dtype)",
540541
FutureWarning,
541-
stacklevel=4,
542+
stacklevel=find_stack_level(),
542543
)
543544
# GH#40110 until the deprecation is enforced, we _dont_
544545
# ignore the dtype for DataFrame, and _do_ cast even though
@@ -777,7 +778,7 @@ def _try_cast(
777778
"passed to 'DataFrame', either all columns will be cast to that "
778779
"dtype, or a TypeError will be raised.",
779780
FutureWarning,
780-
stacklevel=7,
781+
stacklevel=find_stack_level(),
781782
)
782783
subarr = np.array(arr, dtype=object, copy=copy)
783784
return subarr

pandas/core/describe.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from pandas._libs.tslibs import Timestamp
2525
from pandas._typing import NDFrameT
26+
from pandas.util._exceptions import find_stack_level
2627
from pandas.util._validators import validate_percentile
2728

2829
from pandas.core.dtypes.common import (
@@ -377,7 +378,7 @@ def select_describe_func(
377378
"version of pandas. Specify `datetime_is_numeric=True` to "
378379
"silence this warning and adopt the future behavior now.",
379380
FutureWarning,
380-
stacklevel=5,
381+
stacklevel=find_stack_level(),
381382
)
382383
return describe_timestamp_as_categorical_1d
383384
elif is_timedelta64_dtype(data.dtype):

pandas/core/dtypes/cast.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -563,7 +563,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
563563
"dtype is deprecated. In a future version, this will be cast "
564564
"to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.",
565565
FutureWarning,
566-
stacklevel=8,
566+
stacklevel=find_stack_level(),
567567
)
568568
return dtype, fv
569569
elif isinstance(fill_value, str):
@@ -1133,7 +1133,7 @@ def astype_nansafe(
11331133
"Use .view(...) instead.",
11341134
FutureWarning,
11351135
# stacklevel chosen to be correct when reached via Series.astype
1136-
stacklevel=7,
1136+
stacklevel=find_stack_level(),
11371137
)
11381138
if isna(arr).any():
11391139
raise ValueError("Cannot convert NaT values to integer")
@@ -1155,7 +1155,7 @@ def astype_nansafe(
11551155
"Use .view(...) instead.",
11561156
FutureWarning,
11571157
# stacklevel chosen to be correct when reached via Series.astype
1158-
stacklevel=7,
1158+
stacklevel=find_stack_level(),
11591159
)
11601160
if isna(arr).any():
11611161
raise ValueError("Cannot convert NaT values to integer")
@@ -1651,7 +1651,7 @@ def maybe_cast_to_datetime(
16511651
"`pd.Series(values).dt.tz_localize(None)` "
16521652
"instead.",
16531653
FutureWarning,
1654-
stacklevel=8,
1654+
stacklevel=find_stack_level(),
16551655
)
16561656
# equiv: dta.view(dtype)
16571657
# Note: NOT equivalent to dta.astype(dtype)
@@ -1691,7 +1691,7 @@ def maybe_cast_to_datetime(
16911691
".tz_localize('UTC').tz_convert(dtype.tz) "
16921692
"or pd.Series(data.view('int64'), dtype=dtype)",
16931693
FutureWarning,
1694-
stacklevel=5,
1694+
stacklevel=find_stack_level(),
16951695
)
16961696

16971697
value = dta.tz_localize("UTC").tz_convert(dtype.tz)
@@ -1859,7 +1859,7 @@ def construct_2d_arraylike_from_scalar(
18591859
shape = (length, width)
18601860

18611861
if dtype.kind in ["m", "M"]:
1862-
value = maybe_unbox_datetimelike_tz_deprecation(value, dtype, stacklevel=4)
1862+
value = maybe_unbox_datetimelike_tz_deprecation(value, dtype)
18631863
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
18641864
# operand type: "Type[object]")
18651865
elif dtype == object: # type: ignore[comparison-overlap]
@@ -1932,9 +1932,7 @@ def construct_1d_arraylike_from_scalar(
19321932
return subarr
19331933

19341934

1935-
def maybe_unbox_datetimelike_tz_deprecation(
1936-
value: Scalar, dtype: DtypeObj, stacklevel: int = 5
1937-
):
1935+
def maybe_unbox_datetimelike_tz_deprecation(value: Scalar, dtype: DtypeObj):
19381936
"""
19391937
Wrap maybe_unbox_datetimelike with a check for a timezone-aware Timestamp
19401938
along with a timezone-naive datetime64 dtype, which is deprecated.
@@ -1963,7 +1961,7 @@ def maybe_unbox_datetimelike_tz_deprecation(
19631961
"`pd.Series(values).dt.tz_localize(None)` "
19641962
"instead.",
19651963
FutureWarning,
1966-
stacklevel=stacklevel,
1964+
stacklevel=find_stack_level(),
19671965
)
19681966
new_value = value.tz_localize(None)
19691967
return maybe_unbox_datetimelike(new_value, dtype)

pandas/core/dtypes/common.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
ArrayLike,
2323
DtypeObj,
2424
)
25+
from pandas.util._exceptions import find_stack_level
2526

2627
from pandas.core.dtypes.base import _registry as registry
2728
from pandas.core.dtypes.dtypes import (
@@ -304,7 +305,7 @@ def is_categorical(arr) -> bool:
304305
"is_categorical is deprecated and will be removed in a future version. "
305306
"Use is_categorical_dtype instead.",
306307
FutureWarning,
307-
stacklevel=2,
308+
stacklevel=find_stack_level(),
308309
)
309310
return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr)
310311

@@ -1378,7 +1379,7 @@ def is_extension_type(arr) -> bool:
13781379
"'is_extension_type' is deprecated and will be removed in a future "
13791380
"version. Use 'is_extension_array_dtype' instead.",
13801381
FutureWarning,
1381-
stacklevel=2,
1382+
stacklevel=find_stack_level(),
13821383
)
13831384

13841385
if is_categorical_dtype(arr):

0 commit comments

Comments
 (0)