Skip to content

ENH: Use stacklevel in warnings #44439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
npt,
)
from pandas.util._decorators import doc
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.cast import (
construct_1d_object_array_from_listlike,
Expand Down Expand Up @@ -1550,7 +1551,7 @@ def searchsorted(
_diff_special = {"float64", "float32", "int64", "int32", "int16", "int8"}


def diff(arr, n: int, axis: int = 0, stacklevel: int = 3):
def diff(arr, n: int, axis: int = 0):
"""
difference of n between self,
analogous to s-s.shift(n)
Expand Down Expand Up @@ -1596,7 +1597,7 @@ def diff(arr, n: int, axis: int = 0, stacklevel: int = 3):
"dtype lost in 'diff()'. In the future this will raise a "
"TypeError. Convert to a suitable dtype prior to calling 'diff'.",
FutureWarning,
stacklevel=stacklevel,
stacklevel=find_stack_level(),
)
arr = np.asarray(arr)
dtype = arr.dtype
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/arraylike.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,9 @@ def reconstruct(result):
"Consider explicitly converting the DataFrame "
"to an array with '.to_numpy()' first."
)
warnings.warn(msg.format(ufunc), FutureWarning, stacklevel=4)
warnings.warn(
msg.format(ufunc), FutureWarning, stacklevel=find_stack_level()
)
return result
raise NotImplementedError
return result
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,13 +416,12 @@ def astype(self, dtype, copy: bool = True):
elif is_integer_dtype(dtype):
# we deliberately ignore int32 vs. int64 here.
# See https://github.com/pandas-dev/pandas/issues/24381 for more.
level = find_stack_level()
warnings.warn(
f"casting {self.dtype} values to int64 with .astype(...) is "
"deprecated and will raise in a future version. "
"Use .view(...) instead.",
FutureWarning,
stacklevel=level,
stacklevel=find_stack_level(),
)

values = self.asi8
Expand Down
9 changes: 3 additions & 6 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -969,13 +969,12 @@ def astype_dt64_to_dt64tz(
# this should be the only copy
values = values.copy()

level = find_stack_level()
warnings.warn(
"Using .astype to convert from timezone-naive dtype to "
"timezone-aware dtype is deprecated and will raise in a "
"future version. Use ser.dt.tz_localize instead.",
FutureWarning,
stacklevel=level,
stacklevel=find_stack_level(),
)

# GH#33401 this doesn't match DatetimeArray.astype, which
Expand All @@ -986,13 +985,12 @@ def astype_dt64_to_dt64tz(
# DatetimeArray/DatetimeIndex.astype behavior
if values.tz is None and aware:
dtype = cast(DatetimeTZDtype, dtype)
level = find_stack_level()
warnings.warn(
"Using .astype to convert from timezone-naive dtype to "
"timezone-aware dtype is deprecated and will raise in a "
"future version. Use obj.tz_localize instead.",
FutureWarning,
stacklevel=level,
stacklevel=find_stack_level(),
)

return values.tz_localize(dtype.tz)
Expand All @@ -1006,14 +1004,13 @@ def astype_dt64_to_dt64tz(
return result

elif values.tz is not None:
level = find_stack_level()
warnings.warn(
"Using .astype to convert from timezone-aware dtype to "
"timezone-naive dtype is deprecated and will raise in a "
"future version. Use obj.tz_localize(None) or "
"obj.tz_convert('UTC').tz_localize(None) instead",
FutureWarning,
stacklevel=level,
stacklevel=find_stack_level(),
)

result = values.tz_convert("UTC").tz_localize(None)
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,9 +487,10 @@ def _data(self):
@property
def _AXIS_NUMBERS(self) -> dict[str, int]:
""".. deprecated:: 1.1.0"""
level = self.ndim + 1
warnings.warn(
"_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=level
"_AXIS_NUMBERS has been deprecated.",
FutureWarning,
stacklevel=find_stack_level(),
)
return {"index": 0}

Expand Down
12 changes: 3 additions & 9 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
)
from pandas.errors import InvalidIndexError
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.cast import sanitize_to_nanoseconds
from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -964,8 +965,6 @@ def _check_deprecated_resample_kwargs(kwargs, origin):
From where this function is being called; either Grouper or TimeGrouper. Used
to determine an approximate stacklevel.
"""
from pandas.core.resample import TimeGrouper

# Deprecation warning of `base` and `loffset` since v1.1.0:
# we are raising the warning here to be able to set the `stacklevel`
# properly since we need to raise the `base` and `loffset` deprecation
Expand All @@ -975,11 +974,6 @@ def _check_deprecated_resample_kwargs(kwargs, origin):
# core/groupby/grouper.py::Grouper
# raising these warnings from TimeGrouper directly would fail the test:
# tests/resample/test_deprecated.py::test_deprecating_on_loffset_and_base
# hacky way to set the stacklevel: if cls is TimeGrouper it means
# that the call comes from a pandas internal call of resample,
# otherwise it comes from pd.Grouper
stacklevel = (5 if origin is TimeGrouper else 2) + 1
# the + 1 is for this helper function, check_deprecated_resample_kwargs

if kwargs.get("base", None) is not None:
warnings.warn(
Expand All @@ -989,7 +983,7 @@ def _check_deprecated_resample_kwargs(kwargs, origin):
"\nbecomes:\n"
'\n>>> df.resample(freq="3s", offset="2s")\n',
FutureWarning,
stacklevel=stacklevel,
stacklevel=find_stack_level(),
)
if kwargs.get("loffset", None) is not None:
warnings.warn(
Expand All @@ -1000,5 +994,5 @@ def _check_deprecated_resample_kwargs(kwargs, origin):
'\n>>> df = df.resample(freq="3s").mean()'
'\n>>> df.index = df.index.to_timestamp() + to_offset("8H")\n',
FutureWarning,
stacklevel=stacklevel,
stacklevel=find_stack_level(),
)
2 changes: 1 addition & 1 deletion pandas/core/internals/array_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ def diff(self: T, n: int, axis: int) -> T:
# with axis=0 is equivalent
assert n == 0
axis = 0
return self.apply(algos.diff, n=n, axis=axis, stacklevel=5)
return self.apply(algos.diff, n=n, axis=axis)

def interpolate(self: T, **kwargs) -> T:
return self.apply_with_block("interpolate", swap_axis=False, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1122,7 +1122,7 @@ def take_nd(

def diff(self, n: int, axis: int = 1) -> list[Block]:
"""return block for the diff of the values"""
new_values = algos.diff(self.values, n, axis=axis, stacklevel=7)
new_values = algos.diff(self.values, n, axis=axis)
return [self.make_block(values=new_values)]

def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Block]:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1012,7 +1012,7 @@ def _get_values_tuple(self, key):
# mpl hackaround
if com.any_none(*key):
result = self._get_values(key)
deprecate_ndim_indexing(result, stacklevel=5)
deprecate_ndim_indexing(result, stacklevel=find_stack_level())
return result

if not isinstance(self.index, MultiIndex):
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1427,7 +1427,7 @@ def replace(
" In addition, single character regular expressions will "
"*not* be treated as literal strings when regex=True."
)
warnings.warn(msg, FutureWarning, stacklevel=3)
warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())

# Check whether repl is valid (GH 13438, GH 15055)
if not (isinstance(repl, str) or callable(repl)):
Expand Down
3 changes: 1 addition & 2 deletions pandas/io/excel/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,11 +519,10 @@ def parse(
if convert_float is None:
convert_float = True
else:
stacklevel = find_stack_level()
warnings.warn(
"convert_float is deprecated and will be removed in a future version.",
FutureWarning,
stacklevel=stacklevel,
stacklevel=find_stack_level(),
)

validate_header_arg(header)
Expand Down
13 changes: 7 additions & 6 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
from pandas.util._exceptions import find_stack_level

import pandas as pd
from pandas import (
Expand Down Expand Up @@ -310,7 +311,7 @@ def render(
warnings.warn(
"this method is deprecated in favour of `Styler.to_html()`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)
if sparse_index is None:
sparse_index = get_option("styler.sparse.index")
Expand Down Expand Up @@ -1675,7 +1676,7 @@ def where(
warnings.warn(
"this method is deprecated in favour of `Styler.applymap()`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)

if other is None:
Expand Down Expand Up @@ -1707,7 +1708,7 @@ def set_precision(self, precision: int) -> StylerRenderer:
warnings.warn(
"this method is deprecated in favour of `Styler.format(precision=..)`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)
self.precision = precision
return self.format(precision=precision, na_rep=self.na_rep)
Expand Down Expand Up @@ -2217,7 +2218,7 @@ def set_na_rep(self, na_rep: str) -> StylerRenderer:
warnings.warn(
"this method is deprecated in favour of `Styler.format(na_rep=..)`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)
self.na_rep = na_rep
return self.format(na_rep=na_rep, precision=self.precision)
Expand Down Expand Up @@ -2271,7 +2272,7 @@ def hide_index(
warnings.warn(
"this method is deprecated in favour of `Styler.hide(axis='index')`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)
return self.hide(axis=0, level=level, subset=subset, names=names)

Expand Down Expand Up @@ -2324,7 +2325,7 @@ def hide_columns(
warnings.warn(
"this method is deprecated in favour of `Styler.hide(axis='columns')`",
FutureWarning,
stacklevel=2,
stacklevel=find_stack_level(),
)
return self.hide(axis=1, level=level, subset=subset, names=names)

Expand Down