From 07a99e6836923067996f36c3150b30ab45c855ec Mon Sep 17 00:00:00 2001 From: MarcoGorelli <> Date: Thu, 13 Oct 2022 18:42:09 +0100 Subject: [PATCH] Revert "PERF cache find_stack_level (#48023)" This reverts commit 2f8d0a36703e81e4dca52ca9fe4f58c910c1b304. --- .../development/contributing_codebase.rst | 2 +- pandas/_config/config.py | 7 +-- pandas/_libs/parsers.pyx | 4 +- pandas/_libs/tslib.pyx | 3 +- pandas/_libs/tslibs/conversion.pyx | 3 +- pandas/_libs/tslibs/nattype.pyx | 5 +- pandas/_libs/tslibs/offsets.pyx | 9 ++- pandas/_libs/tslibs/parsing.pyx | 5 +- pandas/_libs/tslibs/period.pyx | 3 +- pandas/_libs/tslibs/timedeltas.pyx | 9 ++- pandas/_libs/tslibs/timestamps.pyx | 21 +++---- pandas/_testing/asserters.py | 11 ++-- pandas/compat/_optional.py | 3 +- pandas/core/accessor.py | 3 +- pandas/core/algorithms.py | 8 +-- pandas/core/apply.py | 4 +- pandas/core/arraylike.py | 7 +-- pandas/core/arrays/arrow/_arrow_utils.py | 5 +- pandas/core/arrays/base.py | 2 +- pandas/core/arrays/categorical.py | 31 +++++----- pandas/core/arrays/datetimelike.py | 11 ++-- pandas/core/arrays/datetimes.py | 15 +++-- pandas/core/arrays/sparse/array.py | 13 ++-- pandas/core/arrays/sparse/dtype.py | 3 +- pandas/core/base.py | 3 +- pandas/core/common.py | 6 +- pandas/core/computation/align.py | 5 +- pandas/core/computation/eval.py | 3 +- pandas/core/computation/expressions.py | 3 +- pandas/core/config_init.py | 5 +- pandas/core/construction.py | 7 +-- pandas/core/describe.py | 3 +- pandas/core/dtypes/astype.py | 6 +- pandas/core/dtypes/cast.py | 15 +++-- pandas/core/dtypes/common.py | 5 +- pandas/core/dtypes/concat.py | 3 +- pandas/core/dtypes/inference.py | 3 +- pandas/core/frame.py | 29 ++++----- pandas/core/generic.py | 61 ++++++++----------- pandas/core/groupby/generic.py | 5 +- pandas/core/groupby/groupby.py | 16 +++-- pandas/core/groupby/grouper.py | 5 +- pandas/core/index.py | 3 +- pandas/core/indexers/utils.py | 5 +- pandas/core/indexes/accessors.py | 3 +- pandas/core/indexes/base.py | 53 ++++++++-------- pandas/core/indexes/category.py | 7 +-- pandas/core/indexes/datetimelike.py | 3 +- pandas/core/indexes/datetimes.py | 15 ++--- pandas/core/indexes/multi.py | 25 ++++---- pandas/core/indexes/numeric.py | 3 +- pandas/core/indexes/period.py | 3 +- pandas/core/indexes/range.py | 9 ++- pandas/core/indexing.py | 11 ++-- pandas/core/internals/__init__.py | 3 +- pandas/core/internals/blocks.py | 7 +-- pandas/core/internals/construction.py | 3 +- pandas/core/internals/managers.py | 7 +-- pandas/core/ops/__init__.py | 3 +- pandas/core/resample.py | 5 +- pandas/core/reshape/concat.py | 3 +- pandas/core/reshape/melt.py | 3 +- pandas/core/reshape/merge.py | 13 ++-- pandas/core/reshape/reshape.py | 3 +- pandas/core/series.py | 25 ++++---- pandas/core/strings/accessor.py | 11 +--- pandas/core/tools/datetimes.py | 3 +- pandas/core/window/common.py | 3 +- pandas/core/window/ewm.py | 5 +- pandas/core/window/rolling.py | 10 +-- pandas/io/clipboard/__init__.py | 7 +-- pandas/io/clipboards.py | 7 +-- pandas/io/common.py | 5 +- pandas/io/date_converters.py | 9 ++- pandas/io/excel/_base.py | 13 ++-- pandas/io/formats/css.py | 9 ++- pandas/io/formats/excel.py | 3 +- pandas/io/formats/style.py | 15 +++-- pandas/io/json/_table_schema.py | 5 +- pandas/io/parsers/base_parser.py | 5 +- pandas/io/parsers/c_parser_wrapper.py | 7 +-- pandas/io/parsers/python_parser.py | 3 +- pandas/io/parsers/readers.py | 13 +--- pandas/io/pytables.py | 15 ++--- pandas/io/sas/sas_xport.py | 3 +- pandas/io/sql.py | 9 ++- pandas/io/stata.py | 17 +++--- pandas/plotting/_core.py | 3 +- pandas/plotting/_matplotlib/boxplot.py | 3 +- pandas/plotting/_matplotlib/core.py | 3 +- pandas/plotting/_matplotlib/style.py | 3 +- pandas/plotting/_matplotlib/tools.py | 7 +-- pandas/tseries/frequencies.py | 5 +- pandas/util/_decorators.py | 2 +- pandas/util/_exceptions.py | 13 ++-- pandas/util/_validators.py | 5 +- pandas/util/testing.py | 3 +- scripts/list_future_warnings.sh | 2 +- 98 files changed, 332 insertions(+), 479 deletions(-) diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 82d29f33ac6d6..43e0f2cded397 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -139,7 +139,7 @@ Otherwise, you need to do it manually: warnings.warn( 'Use new_func instead.', FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_func() diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 3b17d6953d61a..a942da663889b 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -54,7 +54,6 @@ ContextDecorator, contextmanager, ) -import inspect import re from typing import ( Any, @@ -662,7 +661,7 @@ def _warn_if_deprecated(key: str) -> bool: warnings.warn( d.msg, FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: msg = f"'{key}' is deprecated" @@ -673,9 +672,7 @@ def _warn_if_deprecated(key: str) -> bool: else: msg += ", please refrain from using it." - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) return True return False diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index b77c141f39502..00e53b7c7cdad 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -972,7 +972,7 @@ cdef class TextReader: "Defining usecols with out of bounds indices is deprecated " "and will raise a ParserError in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) results = {} @@ -1023,7 +1023,7 @@ cdef class TextReader: warnings.warn((f"Both a converter and dtype were specified " f"for column {name} - only the converter will " f"be used."), ParserWarning, - stacklevel=find_stack_level(inspect.currentframe())) + stacklevel=find_stack_level()) results[i] = _apply_converter(conv, self.parser, i, start, end) continue diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c47fca79afb45..a1271ef0d897e 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -1,4 +1,3 @@ -import inspect import warnings cimport cython @@ -847,7 +846,7 @@ cdef inline bint _parse_today_now(str val, int64_t* iresult, bint utc): "deprecated. In a future version, this will match Timestamp('now') " "and Timestamp.now()", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return True diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 733385dc8d6ba..d75d6e5fc1f27 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1,4 +1,3 @@ -import inspect import warnings import numpy as np @@ -286,7 +285,7 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, "Conversion of non-round float with unit={unit} is ambiguous " "and will raise in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) ts = cast_from_unit(ts, unit) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 55c5e478868cb..79299ec38e19c 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -1,4 +1,3 @@ -import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -134,7 +133,7 @@ cdef class _NaT(datetime): "order to match the standard library behavior. " "In a future version these will be considered non-comparable.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return False @@ -378,7 +377,7 @@ class NaTType(_NaT): warnings.warn( "NaT.freq is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return None diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 7be7381bcb4d1..e268a5d74908e 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1,4 +1,3 @@ -import inspect import re import time import warnings @@ -501,7 +500,7 @@ cdef class BaseOffset: "DateOffset.__call__ is deprecated and will be removed in a future " "version. Use `offset + other` instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._apply(other) @@ -511,7 +510,7 @@ cdef class BaseOffset: f"{type(self).__name__}.apply is deprecated and will be removed " "in a future version. Use `offset + other` instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._apply(other) @@ -825,7 +824,7 @@ cdef class BaseOffset: warnings.warn( "onOffset is a deprecated, use is_on_offset instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.is_on_offset(dt) @@ -833,7 +832,7 @@ cdef class BaseOffset: warnings.warn( "isAnchored is a deprecated, use is_anchored instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.is_anchored() diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 9bd6eb91af8ef..e0fcc829ad326 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -1,7 +1,6 @@ """ Parsing functions for datetime and datetime-like strings. """ -import inspect import re import time import warnings @@ -218,7 +217,7 @@ cdef inline object _parse_delimited_date(str date_string, bint dayfirst): format='MM/DD/YYYY', dayfirst='True', ), - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif not dayfirst and swapped_day_and_month: warnings.warn( @@ -226,7 +225,7 @@ cdef inline object _parse_delimited_date(str date_string, bint dayfirst): format='DD/MM/YYYY', dayfirst='False (the default)', ), - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # In Python <= 3.6.0 there is no range checking for invalid dates # in C api, thus we call faster C version for 3.6.1 or newer diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 1e99152b2b4de..55a3741b9cdff 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,4 +1,3 @@ -import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -1830,7 +1829,7 @@ cdef class _Period(PeriodMixin): "be removed in a future version. Use " "`per.to_timestamp(...).tz_localize(tz)` instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) how = validate_end_alias(how) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index dd19306bd49c6..fe2e927443021 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1,5 +1,4 @@ import collections -import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -687,7 +686,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): "Units 'M', 'Y' and 'y' do not represent unambiguous " "timedelta values and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if unit == 'M': @@ -1066,7 +1065,7 @@ cdef class _Timedelta(timedelta): warnings.warn( "Timedelta.freq is deprecated and will be removed in a future version", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return None @@ -1082,7 +1081,7 @@ cdef class _Timedelta(timedelta): warnings.warn( "Timedelta.is_populated is deprecated and will be removed in a future version", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._is_populated @@ -1289,7 +1288,7 @@ cdef class _Timedelta(timedelta): warnings.warn( "Timedelta.delta is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.value diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ccba037c57d7e..c166edf35946c 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -6,7 +6,6 @@ construction requirements, we need to do object instantiation in python (see Timestamp class below). This will serve as a C extension type that shadows the python class, where we do any heavy lifting. """ -import inspect import warnings cimport cython @@ -251,7 +250,7 @@ cdef class _Timestamp(ABCTimestamp): warnings.warn( "Timestamp.freq is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._freq @@ -371,7 +370,7 @@ cdef class _Timestamp(ABCTimestamp): "In a future version these will be considered non-comparable. " "Use 'ts == pd.Timestamp(date)' or 'ts.date() == date' instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return NotImplemented else: @@ -626,7 +625,7 @@ cdef class _Timestamp(ABCTimestamp): "version. When you have a freq, use " f"freq.{field}(timestamp) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @property @@ -1132,7 +1131,7 @@ cdef class _Timestamp(ABCTimestamp): """ if self.nanosecond != 0 and warn: warnings.warn("Discarding nonzero nanoseconds in conversion.", - UserWarning, stacklevel=find_stack_level(inspect.currentframe())) + UserWarning, stacklevel=find_stack_level()) return datetime(self.year, self.month, self.day, self.hour, self.minute, self.second, @@ -1211,7 +1210,7 @@ cdef class _Timestamp(ABCTimestamp): warnings.warn( "Converting to Period representation will drop timezone information.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if freq is None: @@ -1220,7 +1219,7 @@ cdef class _Timestamp(ABCTimestamp): "In a future version, calling 'Timestamp.to_period()' without " "passing a 'freq' will raise an exception.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return Period(self, freq=freq) @@ -1412,7 +1411,7 @@ class Timestamp(_Timestamp): "Timestamp.utcfromtimestamp(ts).tz_localize(None). " "To get the future behavior, use Timestamp.fromtimestamp(ts, 'UTC')", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return cls(datetime.utcfromtimestamp(ts)) @@ -1648,7 +1647,7 @@ class Timestamp(_Timestamp): "as a wall time, not a UTC time. To interpret as a UTC time, " "use `Timestamp(dt64).tz_localize('UTC').tz_convert(tz)`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # Once this deprecation is enforced, we can do # return Timestamp(ts_input).tz_localize(tzobj) @@ -1671,7 +1670,7 @@ class Timestamp(_Timestamp): "The 'freq' argument in Timestamp is deprecated and will be " "removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if not is_offset_object(freq): freq = to_offset(freq) @@ -2007,7 +2006,7 @@ timedelta}, default 'raise' warnings.warn( "Timestamp.freqstr is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._freqstr diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 9b8e171413b57..1f690b39e6fb8 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect from typing import ( Literal, cast, @@ -113,7 +112,7 @@ def assert_almost_equal( "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -340,7 +339,7 @@ def _get_ilevel_values(index, level): "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -830,7 +829,7 @@ def assert_extension_array_equal( "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -985,7 +984,7 @@ def assert_series_equal( "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -1278,7 +1277,7 @@ def assert_frame_equal( "is deprecated and will be removed in a future version. " "You can stop passing 'check_less_precise' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 4f4291c338dd5..3caa92758dd52 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -1,7 +1,6 @@ from __future__ import annotations import importlib -import inspect import sys import types import warnings @@ -165,7 +164,7 @@ def import_optional_dependency( warnings.warn( msg, UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return None elif errors == "raise": diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index c1495a8e6ce69..87d9c39b0407c 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -6,7 +6,6 @@ """ from __future__ import annotations -import inspect import warnings from pandas.util._decorators import doc @@ -269,7 +268,7 @@ def decorator(accessor): f"{repr(name)} for type {repr(cls)} is overriding a preexisting " f"attribute with the same name.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index b0d7bf5d4109e..0edb711e8824e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -861,9 +861,7 @@ def resolve_na_sentinel( "Specify `use_na_sentinel=True` to use the sentinel value -1, and " "`use_na_sentinel=False` to encode NaN values." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) result = na_sentinel return result @@ -1067,7 +1065,7 @@ def mode( except TypeError as err: warnings.warn( f"Unable to sort modes: {err}", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) result = _reconstruct_data(npresult, original.dtype, original) @@ -1692,7 +1690,7 @@ def diff(arr, n: int, axis: AxisInt = 0): "dtype lost in 'diff()'. In the future this will raise a " "TypeError. Convert to a suitable dtype prior to calling 'diff'.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) arr = np.asarray(arr) dtype = arr.dtype diff --git a/pandas/core/apply.py b/pandas/core/apply.py index cc965c27c741b..bbb954c1a4e80 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -292,7 +292,7 @@ def transform_dict_like(self, func): f"raised, this will raise in a future version of pandas. " f"Drop these columns/ops to avoid this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return concat(results, axis=1) @@ -424,7 +424,7 @@ def agg_list_like(self) -> DataFrame | Series: warnings.warn( depr_nuisance_columns_msg.format(failed_names), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) try: diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index ca9fee3cf8896..383ee2c53f0ae 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -6,7 +6,6 @@ """ from __future__ import annotations -import inspect import operator from typing import Any import warnings @@ -221,7 +220,7 @@ def _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any): "or align manually (eg 'df1, df2 = df1.align(df2)') before passing to " "the ufunc to obtain the future behaviour and silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # keep the first dataframe of the inputs, other DataFrame/Series is @@ -353,9 +352,7 @@ def _reconstruct(result): "to an array with '.to_numpy()' first." ) warnings.warn( - msg.format(ufunc), - FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + msg.format(ufunc), FutureWarning, stacklevel=find_stack_level() ) return result raise NotImplementedError diff --git a/pandas/core/arrays/arrow/_arrow_utils.py b/pandas/core/arrays/arrow/_arrow_utils.py index e4b934023d701..6e6ef6a2c20a8 100644 --- a/pandas/core/arrays/arrow/_arrow_utils.py +++ b/pandas/core/arrays/arrow/_arrow_utils.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import warnings import numpy as np @@ -18,9 +17,7 @@ def fallback_performancewarning(version: str | None = None) -> None: msg = "Falling back on a non-pyarrow code path which may decrease performance." if version is not None: msg += f" Upgrade to pyarrow >={version} to possibly suppress this warning." - warnings.warn( - msg, PerformanceWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) def pyarrow_array_to_numpy_and_mask( diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index df80f30e3b956..9758ca84d236b 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -470,7 +470,7 @@ def __init_subclass__(cls, **kwargs) -> None: f"instead. Add this argument to `{name}.factorize` to be compatible " f"with future versions of pandas and silence this warning.", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def to_numpy( diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 80a789828506d..c69c8ae0d6bec 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2,7 +2,6 @@ from csv import QUOTE_NONNUMERIC from functools import partial -import inspect import operator from shutil import get_terminal_size from typing import ( @@ -401,7 +400,7 @@ def __init__( "Allowing scalars in the Categorical constructor is deprecated " "and will raise in a future version. Use `[value]` instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) values = [values] @@ -758,7 +757,7 @@ def categories(self, categories) -> None: "Setting categories in-place is deprecated and will raise in a " "future version. Use rename_categories instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self._set_categories(categories) @@ -882,7 +881,7 @@ def set_ordered( "a future version. setting ordered-ness on categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1019,7 +1018,7 @@ def set_categories( "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1134,7 +1133,7 @@ def rename_categories( "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1198,7 +1197,7 @@ def reorder_categories(self, new_categories, ordered=None, inplace=no_default): "a future version. Reordering categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1282,7 +1281,7 @@ def add_categories( "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1370,7 +1369,7 @@ def remove_categories(self, removals, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1458,7 +1457,7 @@ def remove_unused_categories( "remove_unused_categories is deprecated and " "will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -2070,7 +2069,7 @@ def to_dense(self) -> np.ndarray: "Categorical.to_dense is deprecated and will be removed in " "a future version. Use np.asarray(cat) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return np.asarray(self) @@ -2087,7 +2086,7 @@ def _codes(self, value: np.ndarray) -> None: "Setting the codes on a Categorical is deprecated and will raise in " "a future version. Create a new Categorical object instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # GH#40606 NDArrayBacked.__init__(self, value, self.dtype) @@ -2112,7 +2111,7 @@ def take_nd( warn( "Categorical.take_nd is deprecated, use Categorical.take instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value) @@ -2407,7 +2406,7 @@ def mode(self, dropna: bool = True) -> Categorical: "Categorical.mode is deprecated and will be removed in a future version. " "Use Series.mode instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._mode(dropna=dropna) @@ -2550,7 +2549,7 @@ def is_dtype_equal(self, other) -> bool: "Categorical.is_dtype_equal is deprecated and will be removed " "in a future version", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) try: return self._categories_match_up_to_permutation(other) @@ -2674,7 +2673,7 @@ def replace(self, to_replace, value, inplace: bool = False) -> Categorical | Non "Categorical.replace is deprecated and will be removed in a future " "version. Use Series.replace directly instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._replace(to_replace=to_replace, value=value, inplace=inplace) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 7e4ce970d1b9c..ebd440d4b0d24 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -4,7 +4,6 @@ datetime, timedelta, ) -import inspect import operator from typing import ( TYPE_CHECKING, @@ -470,7 +469,7 @@ def astype(self, dtype, copy: bool = True): "exactly the specified dtype instead of uint64, and will " "raise if that conversion overflows.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif (self.asi8 < 0).any(): # GH#45034 @@ -480,7 +479,7 @@ def astype(self, dtype, copy: bool = True): "raise if the conversion overflows, as it did in this " "case with negative int64 values.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif dtype != np.int64: # GH#45034 @@ -490,7 +489,7 @@ def astype(self, dtype, copy: bool = True): "exactly the specified dtype instead of int64, and will " "raise if that conversion overflows.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if copy: @@ -629,7 +628,7 @@ def _validate_shift_value(self, fill_value): FutureWarning, # There is no way to hard-code the level since this might be # reached directly or called from the Index or Block method - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) fill_value = new_fill @@ -1398,7 +1397,7 @@ def _addsub_object_array(self, other: np.ndarray, op): "Adding/subtracting object-dtype array to " f"{type(self).__name__} not vectorized.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # Caller is responsible for broadcasting if necessary diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 79e8d2d90ab1e..f7843ce8697f2 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -6,7 +6,6 @@ timedelta, tzinfo, ) -import inspect from typing import ( TYPE_CHECKING, Iterator, @@ -501,7 +500,7 @@ def _check_compatible_with(self, other, setitem: bool = False): "timezone. To retain the old behavior, explicitly cast to " "object dtype before the operation.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) raise ValueError(f"Timezones don't match. '{self.tz}' != '{other.tz}'") @@ -668,7 +667,7 @@ def astype(self, dtype, copy: bool = True): "Passing unit-less datetime64 dtype to .astype is deprecated " "and will raise in a future version. Pass 'datetime64[ns]' instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # unit conversion e.g. datetime64[s] return self._ndarray.astype(dtype) @@ -745,7 +744,7 @@ def _add_offset(self, offset) -> DatetimeArray: warnings.warn( "Non-vectorized DateOffset being applied to Series or DatetimeIndex.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) result = self.astype("O") + offset result = type(self)._from_sequence(result) @@ -1148,7 +1147,7 @@ def to_period(self, freq=None) -> PeriodArray: "Converting to PeriodArray/Index representation " "will drop timezone information.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if freq is None: @@ -1190,7 +1189,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray: "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.", FutureWarning, # stacklevel chosen to be correct for when called from DatetimeIndex - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) from pandas.core.arrays.timedeltas import TimedeltaArray @@ -1392,7 +1391,7 @@ def weekofyear(self): "weekofyear and return an Index, you may call " "pd.Int64Index(idx.isocalendar().week)", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week if week_series.hasnans: @@ -2272,7 +2271,7 @@ def maybe_convert_dtype(data, copy: bool, tz: tzinfo | None = None): "before passing the data to pandas. To get the future behavior, " "first cast to 'int64'.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif is_timedelta64_dtype(data.dtype) or is_bool_dtype(data.dtype): diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index f28aefd63546b..239ad66e3336c 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -4,7 +4,6 @@ from __future__ import annotations from collections import abc -import inspect import numbers import operator from typing import ( @@ -417,7 +416,7 @@ def __init__( "to construct an array with the desired repeats of the " "scalar value instead.\n\n", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if index is not None and not is_scalar(data): @@ -496,7 +495,7 @@ def __init__( "loses timezone information. Cast to object before " "sparse to retain timezone information.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) data = np.asarray(data, dtype="datetime64[ns]") if fill_value is NaT: @@ -783,7 +782,7 @@ def fillna( warnings.warn( msg, PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_values = np.asarray(self) # interpolate_2d modifies new_values inplace @@ -1193,9 +1192,7 @@ def searchsorted( ) -> npt.NDArray[np.intp] | np.intp: msg = "searchsorted requires high memory usage." - warnings.warn( - msg, PerformanceWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) if not is_scalar(v): v = np.asarray(v) v = np.asarray(v) @@ -1335,7 +1332,7 @@ def astype(self, dtype: AstypeArg | None = None, copy: bool = True): "array with the requested dtype. To retain the old behavior, use " "`obj.astype(SparseDtype(dtype))`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) dtype = self.dtype.update_dtype(dtype) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index cbe283b50b4f7..eaed6257736ba 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -1,7 +1,6 @@ """Sparse Dtype""" from __future__ import annotations -import inspect import re from typing import ( TYPE_CHECKING, @@ -410,7 +409,7 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: f"values: '{fill_values}'. Picking the first and " "converting the rest.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes] diff --git a/pandas/core/base.py b/pandas/core/base.py index 927a3ed6a601c..d85f41eb84f8d 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -4,7 +4,6 @@ from __future__ import annotations -import inspect import textwrap from typing import ( TYPE_CHECKING, @@ -1078,7 +1077,7 @@ def is_monotonic(self) -> bool: "is_monotonic is deprecated and will be removed in a future version. " "Use is_monotonic_increasing instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.is_monotonic_increasing diff --git a/pandas/core/common.py b/pandas/core/common.py index e276e2d37d86c..817b889623d99 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -169,7 +169,7 @@ def cast_scalar_indexer(val, warn_float: bool = False): "Indexing with a float is deprecated, and will raise an IndexError " "in pandas 2.0. You can manually convert to an integer key instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return int(val) return val @@ -697,6 +697,4 @@ def deprecate_numeric_only_default( "this warning." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 958e605727f27..2e7a0f842ee6d 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -7,7 +7,6 @@ partial, wraps, ) -import inspect from typing import ( TYPE_CHECKING, Callable, @@ -132,9 +131,7 @@ def _align_core(terms): f"by more than {ordm:.4g}; performance may suffer." ) warnings.warn( - w, - category=PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + w, category=PerformanceWarning, stacklevel=find_stack_level() ) f = partial(ti.reindex, reindexer, axis=axis, copy=False) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 2ed3ece05ebba..baf8c837d7f78 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect import tokenize from typing import TYPE_CHECKING import warnings @@ -313,7 +312,7 @@ def eval( "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) exprs: list[str | BinOp] diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 5c7f5fc521e19..8cd4fa1240dc3 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -7,7 +7,6 @@ """ from __future__ import annotations -import inspect import operator import warnings @@ -217,7 +216,7 @@ def _bool_arith_fallback(op_str, a, b) -> bool: f"evaluating in Python space because the {repr(op_str)} " "operator is not supported by numexpr for the bool dtype, " f"use {repr(_BOOL_OP_UNSUPPORTED[op_str])} instead.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return True return False diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 5456e2f35778c..4bd6fb4b59caf 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -11,7 +11,6 @@ """ from __future__ import annotations -import inspect import os from typing import Callable import warnings @@ -371,7 +370,7 @@ def _deprecate_column_space(key) -> None: "in a future version. Use df.to_string(col_space=...) " "instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) cf.register_option("column_space", 12, validator=is_int, cb=_deprecate_column_space) @@ -398,7 +397,7 @@ def _deprecate_negative_int_max_colwidth(key) -> None: "will not be supported in future version. Instead, use None " "to not limit the column width.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) cf.register_option( diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 989ce0335a476..b7db95269439c 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -6,7 +6,6 @@ """ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, Any, @@ -577,7 +576,7 @@ def sanitize_array( "passed dtype. To retain the old behavior, call Series(arr) or " "DataFrame(arr) without passing a dtype.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) subarr = np.array(data, copy=copy) except ValueError: @@ -589,7 +588,7 @@ def sanitize_array( "if they cannot be cast losslessly (matching Series behavior). " "To retain the old behavior, use DataFrame(data).astype(dtype)", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # GH#40110 until the deprecation is enforced, we _dont_ # ignore the dtype for DataFrame, and _do_ cast even though @@ -863,7 +862,7 @@ def _try_cast( "passed to 'DataFrame', either all columns will be cast to that " "dtype, or a TypeError will be raised.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) subarr = np.array(arr, dtype=object, copy=copy) return subarr diff --git a/pandas/core/describe.py b/pandas/core/describe.py index e6f567b123b59..ce2fa950e6e62 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -9,7 +9,6 @@ ABC, abstractmethod, ) -import inspect from typing import ( TYPE_CHECKING, Any, @@ -386,7 +385,7 @@ def select_describe_func( "version of pandas. Specify `datetime_is_numeric=True` to " "silence this warning and adopt the future behavior now.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return describe_timestamp_as_categorical_1d elif is_timedelta64_dtype(data.dtype): diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index d495a0614b227..ad3dc0a876e00 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -383,7 +383,7 @@ def astype_dt64_to_dt64tz( "timezone-aware dtype is deprecated and will raise in a " "future version. Use ser.dt.tz_localize instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # GH#33401 this doesn't match DatetimeArray.astype, which @@ -399,7 +399,7 @@ def astype_dt64_to_dt64tz( "timezone-aware dtype is deprecated and will raise in a " "future version. Use obj.tz_localize instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return values.tz_localize(dtype.tz) @@ -419,7 +419,7 @@ def astype_dt64_to_dt64tz( "future version. Use obj.tz_localize(None) or " "obj.tz_convert('UTC').tz_localize(None) instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) result = values.tz_convert("UTC").tz_localize(None) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 6b890f98e8cac..489691b3fd76a 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -10,7 +10,6 @@ timedelta, ) import functools -import inspect from typing import ( TYPE_CHECKING, Any, @@ -634,7 +633,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan): "dtype is deprecated. In a future version, this will be cast " "to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return dtype, fv elif isinstance(fill_value, str): @@ -1305,7 +1304,7 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: "and will be removed in a future version. To retain the old behavior " f"explicitly pass Series(data, dtype={value.dtype})", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return value @@ -1364,7 +1363,7 @@ def maybe_cast_to_datetime( "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # equiv: dta.view(dtype) # Note: NOT equivalent to dta.astype(dtype) @@ -1404,7 +1403,7 @@ def maybe_cast_to_datetime( ".tz_localize('UTC').tz_convert(dtype.tz) " "or pd.Series(data.view('int64'), dtype=dtype)", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) value = dta.tz_localize("UTC").tz_convert(dtype.tz) @@ -1768,7 +1767,7 @@ def _maybe_unbox_datetimelike_tz_deprecation(value: Scalar, dtype: DtypeObj): "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_value = value.tz_localize(None) return _maybe_unbox_datetimelike(new_value, dtype) @@ -1893,7 +1892,7 @@ def maybe_cast_to_integer_array( "In a future version this will raise OverflowError. To retain the " f"old behavior, use pd.Series(values).astype({dtype})", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return casted @@ -1904,7 +1903,7 @@ def maybe_cast_to_integer_array( f"dtype={dtype} is deprecated and will raise in a future version. " "Use values.view(dtype) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return casted diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index f8752e1c16c38..deaa53f642e4f 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect from typing import ( Any, Callable, @@ -312,7 +311,7 @@ def is_categorical(arr) -> bool: "is_categorical is deprecated and will be removed in a future version. " "Use is_categorical_dtype instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr) @@ -1390,7 +1389,7 @@ def is_extension_type(arr) -> bool: "'is_extension_type' is deprecated and will be removed in a future " "version. Use 'is_extension_array_dtype' instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if is_categorical_dtype(arr): diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 004b1751b917f..5b11945a8589e 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, cast, @@ -159,7 +158,7 @@ def is_nonempty(x) -> bool: "(instead of coercing bools to numeric values). To retain the old " "behavior, explicitly cast bool-dtype arrays to numeric dtype.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return result diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index 78cf76e747d1d..893e4a9be58ef 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -3,7 +3,6 @@ from __future__ import annotations from collections import abc -import inspect from numbers import Number import re from typing import Pattern @@ -460,7 +459,7 @@ def is_inferred_bool_dtype(arr: ArrayLike) -> bool: "will not be included in reductions with bool_only=True. " "Explicitly cast to bool dtype instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return result diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 592b0f0ba62b8..8b6235374bed0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -14,7 +14,6 @@ from collections import abc import datetime import functools -import inspect from io import StringIO import itertools from textwrap import dedent @@ -684,7 +683,7 @@ def __init__( "removed in a future version. Pass " "{name: data[name] for name in data.dtype.names} instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # a masked array @@ -1363,7 +1362,7 @@ def iteritems(self) -> Iterable[tuple[Hashable, Series]]: "iteritems is deprecated and will be removed in a future version. " "Use .items instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) yield from self.items() @@ -1977,7 +1976,7 @@ def to_dict( warnings.warn( "DataFrame columns are not unique, some columns will be omitted.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # GH16122 into_c = com.standardize_mapping(into) @@ -2001,7 +2000,7 @@ def to_dict( "will be used in a future version. Use one of the above " "to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if orient.startswith("d"): @@ -2850,7 +2849,7 @@ def to_markdown( "'showindex' is deprecated. Only 'index' will be used " "in a future version. Use 'index' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) kwargs.setdefault("headers", "keys") @@ -3464,7 +3463,7 @@ def info( warnings.warn( "null_counts is deprecated. Use show_counts instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) show_counts = null_counts info = DataFrameInfo( @@ -3855,7 +3854,7 @@ def _getitem_bool_array(self, key): warnings.warn( "Boolean Series key will be reindexed to match DataFrame index.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif len(key) != len(self.index): raise ValueError( @@ -4965,9 +4964,7 @@ def lookup( "You can use DataFrame.melt and DataFrame.loc " "as a substitute." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) n = len(row_labels) if n != len(col_labels): @@ -8400,7 +8397,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: squeeze = False @@ -9783,7 +9780,7 @@ def append( "and will be removed from pandas in a future version. " "Use pandas.concat instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._append(other, ignore_index, verify_integrity, sort) @@ -10749,7 +10746,7 @@ def count(self, axis: Axis = 0, level: Level = None, numeric_only: bool = False) "deprecated and will be removed in a future version. Use groupby " "instead. df.count(level=1) should use df.groupby(level=1).count().", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) res = self._count_level(level, axis=axis, numeric_only=numeric_only) return res.__finalize__(self, method="count") @@ -10851,7 +10848,7 @@ def _reduce( "will include datetime64 and datetime64tz columns in a " "future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # Non-copy equivalent to # dt64_cols = self.dtypes.apply(is_datetime64_any_dtype) @@ -10952,7 +10949,7 @@ def _get_data() -> DataFrame: "version this will raise TypeError. Select only valid " "columns before calling the reduction.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if hasattr(result, "dtype"): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ce828ba4a0af4..e052c77471c8d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5,7 +5,6 @@ from datetime import timedelta import functools import gc -import inspect import json import operator import pickle @@ -501,7 +500,7 @@ def _AXIS_NUMBERS(self) -> dict[str, int]: warnings.warn( "_AXIS_NUMBERS has been deprecated.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return {"index": 0} @@ -800,7 +799,7 @@ def set_axis( "and will be removed in a future version. Use " "`obj = obj.set_axis(..., copy=False)` instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -2104,7 +2103,7 @@ def __array_wrap__( "The __array_wrap__ method of DataFrame and Series will be removed in " "a future version", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) res = lib.item_from_zerodim(result) if is_scalar(res): @@ -3442,9 +3441,7 @@ def to_latex( "to use `DataFrame.style.to_latex` which also contains additional " "functionality." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) # Get defaults from the pandas config if self.ndim == 1: @@ -3873,7 +3870,7 @@ class max_speed "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -4029,7 +4026,7 @@ class animal locomotion "Passing lists as key for xs is deprecated and will be removed in a " "future version. Pass key as a tuple instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if level is not None: @@ -4220,11 +4217,7 @@ def _check_setitem_copy(self, t: str = "setting", force: bool_t = False): if value == "raise": raise SettingWithCopyError(t) elif value == "warn": - warnings.warn( - t, - SettingWithCopyWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) + warnings.warn(t, SettingWithCopyWarning, stacklevel=find_stack_level()) def __delitem__(self, key) -> None: """ @@ -5987,7 +5980,7 @@ def __setattr__(self, name: str, value) -> None: "created via a new attribute name - see " "https://pandas.pydata.org/pandas-docs/" "stable/indexing.html#attribute-access", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) object.__setattr__(self, name, value) @@ -8452,7 +8445,7 @@ def between_time( "`include_start` and `include_end` are deprecated in " "favour of `inclusive`.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) left = True if include_start is lib.no_default else include_start right = True if include_end is lib.no_default else include_end @@ -9169,7 +9162,7 @@ def rank( "and will raise in a future version. Pass either 'True' or " "'False'. 'False' will be the default.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) warned = True elif numeric_only is lib.no_default: @@ -9225,7 +9218,7 @@ def ranker(data): "is deprecated; in a future version this will raise TypeError. " "Select only valid columns before calling rank.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if numeric_only: @@ -9236,7 +9229,7 @@ def ranker(data): f"{self.dtype} is deprecated and will raise a TypeError in a " "future version of pandas", category=FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) data = self._get_numeric_data() else: @@ -10010,7 +10003,7 @@ def where( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._where(cond, other, inplace, axis, level) @@ -10088,7 +10081,7 @@ def mask( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # see gh-21891 @@ -10287,9 +10280,7 @@ def slice_shift(self: NDFrameT, periods: int = 1, axis: Axis = 0) -> NDFrameT: "and will be removed in a future version. " "You can use DataFrame/Series.shift instead." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) if periods == 0: return self @@ -10341,7 +10332,7 @@ def tshift(self: NDFrameT, periods: int = 1, freq=None, axis: Axis = 0) -> NDFra "Please use shift instead." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if freq is None: @@ -11178,7 +11169,7 @@ def _logical_func( "deprecated and will be removed in a future version. Use groupby " "instead. df.any(level=1) should use df.groupby(level=1).any()", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if bool_only is not None: raise NotImplementedError( @@ -11312,7 +11303,7 @@ def _stat_function_ddof( "deprecated and will be removed in a future version. Use groupby " "instead. df.var(level=1) should use df.groupby(level=1).var().", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, ddof=ddof @@ -11386,7 +11377,7 @@ def _stat_function( f"scalar {name} over the entire DataFrame. To retain the old " f"behavior, use 'frame.{name}(axis=0)' or just 'frame.{name}()'", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if axis is lib.no_default: axis = None @@ -11399,7 +11390,7 @@ def _stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.median(level=1) should use df.groupby(level=1).median().", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, numeric_only=numeric_only @@ -11523,7 +11514,7 @@ def _min_count_stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.sum(level=1) should use df.groupby(level=1).sum().", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._agg_by_level( name, @@ -11611,9 +11602,7 @@ def mad( "The 'mad' method is deprecated and will be removed in a future version. " "To compute the same result, you may do `(df - df.mean()).abs().mean()`." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) if not is_bool(skipna): warnings.warn( @@ -11621,7 +11610,7 @@ def mad( "version. Pass True instead. Only boolean values will be allowed " "in the future.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) skipna = True if axis is None: @@ -11632,7 +11621,7 @@ def mad( "deprecated and will be removed in a future version. Use groupby " "instead. df.mad(level=1) should use df.groupby(level=1).mad()", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._agg_by_level("mad", axis=axis, level=level, skipna=skipna) @@ -12100,7 +12089,7 @@ def expanding( warnings.warn( "The `center` argument on `expanding` will be removed in the future.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: center = False diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index d978773c2e524..6296a79d13da9 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -9,7 +9,6 @@ from collections import abc from functools import partial -import inspect from textwrap import dedent from typing import ( TYPE_CHECKING, @@ -1472,7 +1471,7 @@ def _transform_general(self, func, *args, **kwargs): "`.to_numpy()` to the result in the transform function to keep " "the current behavior and silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) concat_index = obj.columns if self.axis == 0 else obj.index @@ -1643,7 +1642,7 @@ def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return super().__getitem__(key) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 734521822df8b..e79753f215769 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -836,7 +836,7 @@ def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: "to avoid this warning." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.grouper.get_iterator(self._selected_obj, axis=self.axis) @@ -1360,7 +1360,7 @@ def _resolve_numeric_only( f"numeric_only={numeric_only} and dtype {self.obj.dtype}. This will " "raise a TypeError in a future version of pandas", category=FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) raise NotImplementedError( f"{type(self).__name__}.{how} does not implement numeric_only" @@ -1622,9 +1622,7 @@ def _python_apply_general( "To adopt the future behavior and silence this warning, use " "\n\n\t>>> .groupby(..., group_keys=True)" ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) # We want to behave as if `self.group_keys=False` when reconstructing # the object. However, we don't want to mutate the stateful GroupBy # object, so we just override it. @@ -2959,7 +2957,7 @@ def pad(self, limit=None): "pad is deprecated and will be removed in a future version. " "Use ffill instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.ffill(limit=limit) @@ -3009,7 +3007,7 @@ def backfill(self, limit=None): "backfill is deprecated and will be removed in a future version. " "Use bfill instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.bfill(limit=limit) @@ -4454,7 +4452,7 @@ def warn_dropping_nuisance_columns_deprecated(cls, how: str, numeric_only) -> No f"Before calling .{how}, select only columns which " "should be valid for the function.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif numeric_only is lib.no_default: warnings.warn( @@ -4464,5 +4462,5 @@ def warn_dropping_nuisance_columns_deprecated(cls, how: str, numeric_only) -> No f"Either specify numeric_only or select only columns which " "should be valid for the function.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 948f911232143..dc7679a1744ea 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -4,7 +4,6 @@ """ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, Any, @@ -986,7 +985,7 @@ def _check_deprecated_resample_kwargs(kwargs, origin) -> None: "\nbecomes:\n" '\n>>> df.resample(freq="3s", offset="2s")\n', FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if kwargs.get("loffset", None) is not None: warnings.warn( @@ -997,5 +996,5 @@ def _check_deprecated_resample_kwargs(kwargs, origin) -> None: '\n>>> df = df.resample(freq="3s").mean()' '\n>>> df.index = df.index.to_timestamp() + to_offset("8H")\n', FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/pandas/core/index.py b/pandas/core/index.py index 519a82d680426..19e9c6b27e4e7 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,7 +1,6 @@ # pyright: reportUnusedImport = false from __future__ import annotations -import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -32,7 +31,7 @@ "pandas.core.index is deprecated and will be removed in a future version. " "The public classes are available in the top-level namespace.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) __all__: list[str] = [] diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index 70e6ff8ab7783..0f3cdc4195c85 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, Any, @@ -349,7 +348,7 @@ def deprecate_ndim_indexing(result, stacklevel: int = 3) -> None: "is deprecated and will be removed in a future " "version. Convert to a numpy array before indexing instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @@ -373,7 +372,7 @@ def unpack_1tuple(tup): "slice is deprecated and will raise in a future " "version. Pass a tuple instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return tup[0] diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index dea38e2ed2907..46959aa5cd3e2 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect from typing import TYPE_CHECKING import warnings @@ -292,7 +291,7 @@ def weekofyear(self): "Series.dt.weekofyear and Series.dt.week have been deprecated. " "Please use Series.dt.isocalendar().week instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week week_series.name = self.name diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 51217bcfc18e6..cde221c77fe9b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2,7 +2,6 @@ from datetime import datetime import functools -import inspect from itertools import zip_longest import operator from typing import ( @@ -449,7 +448,7 @@ def __new__( "'tupleize_cols' is deprecated and will raise TypeError in a " "future version. Use the specific Index subclass directly instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) from pandas.core.arrays import PandasArray @@ -627,7 +626,7 @@ def _dtype_to_subclass(cls, dtype: DtypeObj): "dense numpy ndarray. To retain the old behavior, use " "pd.Index(arr.to_numpy()) instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return cls._dtype_to_subclass(dtype.subtype) @@ -695,7 +694,7 @@ def asi8(self): warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return None @@ -809,7 +808,7 @@ def _get_attributes_dict(self) -> dict[str_t, Any]: "The Index._get_attributes_dict method is deprecated, and will be " "removed in a future version", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return {k: getattr(self, k, None) for k in self._attributes} @@ -1027,7 +1026,7 @@ def ravel(self, order: str_t = "C"): "Index.ravel returning ndarray is deprecated; in a future version " "this will return a view on self.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if needs_i8_conversion(self.dtype): # Item "ndarray[Any, Any]" of "Union[ExtensionArray, ndarray[Any, Any]]" @@ -1332,7 +1331,7 @@ def copy( "parameter names is deprecated and will be removed in a future " "version. Use the name parameter instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) name = self._validate_names(name=name, names=names, deep=deep)[0] @@ -1347,7 +1346,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1539,7 +1538,7 @@ def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) values = self if slicer is not None: @@ -1740,7 +1739,7 @@ def to_frame( "the future `None` will be used as the name of the resulting " "DataFrame column.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) name = lib.no_default @@ -2351,7 +2350,7 @@ def is_monotonic(self) -> bool: "is_monotonic is deprecated and will be removed in a future version. " "Use is_monotonic_increasing instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.is_monotonic_increasing @@ -2776,7 +2775,7 @@ def is_mixed(self) -> bool: "Index.is_mixed is deprecated and will be removed in a future version. " "Check index.inferred_type directly instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.inferred_type in ["mixed"] @@ -2821,7 +2820,7 @@ def is_all_dates(self) -> bool: "Index.is_all_dates is deprecated, will be removed in a future version. " "check index.inferred_type instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._is_all_dates @@ -3200,7 +3199,7 @@ def __and__(self, other): "in the future this will be a logical operation matching " "Series.__and__. Use index.intersection(other) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.intersection(other) @@ -3211,7 +3210,7 @@ def __or__(self, other): "in the future this will be a logical operation matching " "Series.__or__. Use index.union(other) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.union(other) @@ -3222,7 +3221,7 @@ def __xor__(self, other): "in the future this will be a logical operation matching " "Series.__xor__. Use index.symmetric_difference(other) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.symmetric_difference(other) @@ -3278,7 +3277,7 @@ def _deprecate_dti_setop(self, other: Index, setop: str_t) -> None: "object dtype. To retain the old behavior, " f"use `index.astype(object).{setop}(other)`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @final @@ -3873,7 +3872,7 @@ def get_loc(self, key, method=None, tolerance=None): "and will raise in a future version. Use " "index.get_indexer([item], method=...) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if is_scalar(key) and isna(key) and not self.hasnans: @@ -4343,7 +4342,7 @@ def is_int(v): "lookups. To retain the old behavior, use `series.iloc[i:j]`. " "To get the future behavior, use `series.loc[i:j]`.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if self.is_integer() or is_index_slice: # Note: these checks are redundant if we know is_index_slice @@ -4377,7 +4376,7 @@ def is_int(v): "and will raise TypeError in a future version. " "Use .loc with labels or .iloc with positions instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) indexer = key else: @@ -4537,7 +4536,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and " "will raise in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) target = self._wrap_reindex_result(target, indexer, preserve_names) @@ -5350,7 +5349,7 @@ def is_type_compatible(self, kind: str_t) -> bool: "Index.is_type_compatible is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return kind == self.inferred_type @@ -5997,7 +5996,7 @@ def get_value(self, series: Series, key): "get_value is deprecated and will be removed in a future version. " "Use Series[key] instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self._check_indexing_error(key) @@ -6065,7 +6064,7 @@ def set_value(self, arr, key, value) -> None: "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) loc = self._engine.get_loc(key) if not can_hold_element(arr, value): @@ -7333,7 +7332,7 @@ def _deprecated_arg(self, value, name: str_t, methodname: str_t) -> None: f"'{name}' argument in {methodname} is deprecated " "and will be removed in a future version. Do not pass it.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @@ -7531,7 +7530,7 @@ def _maybe_cast_data_without_dtype( "In a future version, the Index constructor will not infer numeric " "dtypes when passed object-dtype sequences (matching Series behavior)", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) result = ensure_wrapped_if_datetimelike(result) return result @@ -7587,6 +7586,6 @@ def _maybe_try_sort(result, sort): warnings.warn( f"{err}, sort order is undefined for incomparable objects.", RuntimeWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return result diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 92c9cc1500962..baa938a6f7646 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect from typing import ( Any, Hashable, @@ -225,7 +224,7 @@ def __new__( "deprecated and will raise in a future version. " "Use CategoricalIndex([], ...) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) data = [] @@ -420,7 +419,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and will " "raise in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_target: Index @@ -496,7 +495,7 @@ def take_nd(self, *args, **kwargs) -> CategoricalIndex: "CategoricalIndex.take_nd is deprecated, use CategoricalIndex.take " "instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.take(*args, **kwargs) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index a5c677bbd72fa..dafa5e9680eec 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -4,7 +4,6 @@ from __future__ import annotations from datetime import datetime -import inspect from typing import ( TYPE_CHECKING, Any, @@ -400,7 +399,7 @@ def is_type_compatible(self, kind: str) -> bool: f"{type(self).__name__}.is_type_compatible is deprecated and will be " "removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return kind in self._data._infer_matches diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index c0e3507dbab0b..bb9d9f69ed38c 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -7,7 +7,6 @@ timedelta, tzinfo, ) -import inspect import operator from typing import ( TYPE_CHECKING, @@ -448,7 +447,7 @@ def union_many(self, others): "DatetimeIndex.union_many is deprecated and will be removed in " "a future version. Use obj.union instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) this = self @@ -572,7 +571,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "is deprecated and will be removed in a future version. " "You can stop passing 'keep_tz' to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: warnings.warn( @@ -582,7 +581,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "can do 'idx.tz_convert(None)' before calling " "'to_series'.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: keep_tz = True @@ -685,9 +684,7 @@ def _deprecate_mismatched_indexing(self, key, one_way: bool = False) -> None: "raise KeyError in a future version. " "Use a timezone-aware object instead." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) def get_loc(self, key, method=None, tolerance=None): """ @@ -836,7 +833,7 @@ def check_str_or_none(point) -> bool: "with non-existing keys is deprecated and will raise a " "KeyError in a future Version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) indexer = mask.nonzero()[0][::step] if len(indexer) == len(self): @@ -1116,7 +1113,7 @@ def date_range( warnings.warn( "Argument `closed` is deprecated in favor of `inclusive`.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if closed is None: inclusive = "both" diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 048c8f0ba5e69..646020d5af9bf 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1,7 +1,6 @@ from __future__ import annotations from functools import wraps -import inspect from sys import getsizeof from typing import ( TYPE_CHECKING, @@ -943,7 +942,7 @@ def set_levels( warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1104,7 +1103,7 @@ def set_codes(self, codes, level=None, inplace=None, verify_integrity: bool = Tr warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: inplace = False @@ -1218,7 +1217,7 @@ def copy( # type: ignore[override] "parameter levels is deprecated and will be removed in a future " "version. Use the set_levels method instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) keep_id = False if codes is not None: @@ -1226,7 +1225,7 @@ def copy( # type: ignore[override] "parameter codes is deprecated and will be removed in a future " "version. Use the set_codes method instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) keep_id = False @@ -1258,7 +1257,7 @@ def copy( # type: ignore[override] "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1821,7 +1820,7 @@ def to_frame( "the future `None` will be used as the name of the resulting " "DataFrame column.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) name = lib.no_default @@ -1890,7 +1889,7 @@ def is_lexsorted(self) -> bool: "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._is_lexsorted() @@ -1934,7 +1933,7 @@ def lexsort_depth(self) -> int: "MultiIndex.lexsort_depth is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._lexsort_depth @@ -2315,7 +2314,7 @@ def drop( # type: ignore[override] "dropping on a non-lexsorted multi-index " "without a level parameter may impact performance.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) loc = loc.nonzero()[0] inds.extend(loc) @@ -3000,7 +2999,7 @@ def _maybe_to_slice(loc): warnings.warn( "indexing past lexsort depth may impact performance.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) loc = np.arange(start, stop, dtype=np.intp) @@ -3439,7 +3438,7 @@ def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]: # TODO: how to handle IntervalIndex level? # (no test cases) FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) continue else: @@ -3714,7 +3713,7 @@ def _union(self, other, sort) -> MultiIndex: "The values in the array are unorderable. " "Pass `sort=False` to suppress this warning.", RuntimeWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) pass return result diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 186e45e6f4932..f0f6dfe4eb147 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect from typing import ( Callable, Hashable, @@ -366,7 +365,7 @@ def asi8(self) -> npt.NDArray[np.int64]: warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._values.view(self._default_dtype) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 41a9fc8fa8e21..a5408f19456dd 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -4,7 +4,6 @@ datetime, timedelta, ) -import inspect from typing import Hashable import warnings @@ -361,7 +360,7 @@ def astype(self, dtype, copy: bool = True, how=lib.no_default): "will be removed in a future version. " "Use index.to_timestamp(how=how) instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: how = "start" diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 0948c5a3825d0..3846f565e96f8 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,7 +1,6 @@ from __future__ import annotations from datetime import timedelta -import inspect import operator from sys import getsizeof from typing import ( @@ -264,7 +263,7 @@ def _start(self) -> int: warnings.warn( self._deprecation_message.format("_start", "start"), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.start @@ -287,7 +286,7 @@ def _stop(self) -> int: warnings.warn( self._deprecation_message.format("_stop", "stop"), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.stop @@ -311,7 +310,7 @@ def _step(self) -> int: warnings.warn( self._deprecation_message.format("_step", "step"), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.step @@ -472,7 +471,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index b77288aaa1553..54cf8e12cfcf8 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1,7 +1,6 @@ from __future__ import annotations from contextlib import suppress -import inspect from typing import ( TYPE_CHECKING, Hashable, @@ -1505,7 +1504,7 @@ def _has_valid_setitem_indexer(self, indexer) -> bool: "a future version.\n" "consider using .loc with a DataFrame indexer for automatic alignment.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if not isinstance(indexer, tuple): @@ -2032,7 +2031,7 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None: "`df[df.columns[i]] = newvals` or, if columns are non-unique, " "`df.isetitem(i, newvals)`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # TODO: how to get future behavior? # TODO: what if we got here indirectly via loc? @@ -2515,7 +2514,7 @@ def convert_to_index_sliceable(obj: DataFrame, key): "and will be removed in a future version. Use `frame.loc[string]` " "instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return res except (KeyError, ValueError, NotImplementedError): @@ -2669,7 +2668,7 @@ def check_deprecated_indexers(key) -> None: "Passing a set as an indexer is deprecated and will raise in " "a future version. Use a list instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if ( isinstance(key, dict) @@ -2680,5 +2679,5 @@ def check_deprecated_indexers(key) -> None: "Passing a dict as an indexer is deprecated and will raise in " "a future version. Use a list instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index 8c62576c2f2ca..ea69b567611e4 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -41,7 +41,6 @@ def __getattr__(name: str): - import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -51,7 +50,7 @@ def __getattr__(name: str): "CategoricalBlock is deprecated and will be removed in a future version. " "Use ExtensionBlock instead.", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) from pandas.core.internals.blocks import CategoricalBlock diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 31f9a5199f666..f1c69ba705580 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1,7 +1,6 @@ from __future__ import annotations from functools import wraps -import inspect import re from typing import ( TYPE_CHECKING, @@ -185,7 +184,7 @@ def is_categorical(self) -> bool: "future version. Use isinstance(block.values, Categorical) " "instead. See https://github.com/pandas-dev/pandas/issues/40226", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return isinstance(self.values, Categorical) @@ -256,7 +255,7 @@ def make_block_same_class( "already been cast to DatetimeArray and TimedeltaArray, " "respectively.", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) values = new_values @@ -1586,7 +1585,7 @@ def fillna( "(usually object) instead of raising, matching the " "behavior of other dtypes.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) raise else: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 6aad8dbd940d4..c1d0ab730fe7e 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -5,7 +5,6 @@ from __future__ import annotations from collections import abc -import inspect from typing import ( TYPE_CHECKING, Any, @@ -845,7 +844,7 @@ def to_arrays( "To retain the old behavior, pass as a dictionary " "DataFrame({col: categorical, ..})", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if columns is None: columns = default_index(len(data)) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index f3b7af0ea819d..f21c02a7823ae 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import itertools from typing import ( Any, @@ -1016,7 +1015,7 @@ def __init__( "will assume that a DatetimeTZBlock with block.ndim==2 " "has block.values.ndim == 2.", DeprecationWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # error: Incompatible types in assignment (expression has type @@ -1424,7 +1423,7 @@ def insert(self, loc: int, item: Hashable, value: ArrayLike) -> None: "Consider joining all columns at once using pd.concat(axis=1) " "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def _insert_update_mgr_locs(self, loc) -> None: @@ -1888,7 +1887,7 @@ def __init__( "The `fastpath` keyword is deprecated and will be removed " "in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.axes = [axis] diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 0dcccdbd3bb8b..d08bc1b6756c4 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -5,7 +5,6 @@ """ from __future__ import annotations -import inspect import operator from typing import TYPE_CHECKING import warnings @@ -306,7 +305,7 @@ def to_series(right): "Do `left, right = left.align(right, axis=1, copy=False)` " "before e.g. `left == right`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) left, right = left.align( diff --git a/pandas/core/resample.py b/pandas/core/resample.py index cf8c8b7db800b..f821f8c7b6bd5 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -2,7 +2,6 @@ import copy from datetime import timedelta -import inspect from textwrap import dedent from typing import ( TYPE_CHECKING, @@ -583,7 +582,7 @@ def pad(self, limit=None): "pad is deprecated and will be removed in a future version. " "Use ffill instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.ffill(limit=limit) @@ -770,7 +769,7 @@ def backfill(self, limit=None): "backfill is deprecated and will be removed in a future version. " "Use bfill instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.bfill(limit=limit) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 168e20fdc20ea..e8fd8ed737fd6 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -4,7 +4,6 @@ from __future__ import annotations from collections import abc -import inspect from typing import ( TYPE_CHECKING, Callable, @@ -554,7 +553,7 @@ def __init__( "Passing non boolean values for sort is deprecated and " "will error in a future version!", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.sort = sort diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index f35430e37e964..539e585e01acc 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import re from typing import ( TYPE_CHECKING, @@ -63,7 +62,7 @@ def melt( "In the future this will raise an error, please set the 'value_name' " "parameter of DataFrame.melt to a unique name.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if id_vars is not None: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index d138b4f54b113..422cb98572668 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -6,7 +6,6 @@ import copy import datetime from functools import partial -import inspect import string from typing import ( TYPE_CHECKING, @@ -686,9 +685,7 @@ def __init__( ) # stacklevel chosen to be correct when this is reached via pd.merge # (and not DataFrame.join) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) self.left_on, self.right_on = self._validate_left_right_on(left_on, right_on) @@ -1313,7 +1310,7 @@ def _maybe_coerce_merge_keys(self) -> None: "columns where the float values " "are not equal to their int representation.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) continue @@ -1335,7 +1332,7 @@ def _maybe_coerce_merge_keys(self) -> None: "columns where the float values " "are not equal to their int representation.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) continue @@ -2484,7 +2481,7 @@ def _items_overlap_with_suffix( "unexpected results. Provide 'suffixes' as a tuple instead. In the " "future a 'TypeError' will be raised.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) to_rename = left.intersection(right) @@ -2534,7 +2531,7 @@ def renamer(x, suffix): f"Passing 'suffixes' which cause duplicate columns {set(dups)} in the " f"result is deprecated and will raise a MergeError in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return llabels, rlabels diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 4496225a7df6f..a79332ab3ee55 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import itertools from typing import ( TYPE_CHECKING, @@ -132,7 +131,7 @@ def __init__(self, index: MultiIndex, level=-1, constructor=None) -> None: f"The following operation may generate {num_cells} cells " f"in the resulting pandas object.", PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self._make_selectors() diff --git a/pandas/core/series.py b/pandas/core/series.py index f0327dfd39134..f4b59266e2b91 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect from textwrap import dedent from typing import ( IO, @@ -399,7 +398,7 @@ def __init__( "of 'float64' in a future version. Specify a dtype explicitly " "to silence this warning.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # uncomment the line below when removing the FutureWarning # dtype = np.dtype(object) @@ -931,7 +930,7 @@ def take( "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -1062,9 +1061,7 @@ def _get_values_tuple(self, key: tuple): # see tests.series.timeseries.test_mpl_compat_hack # the asarray is needed to avoid returning a 2D DatetimeArray result = np.asarray(self._values[key]) - deprecate_ndim_indexing( - result, stacklevel=find_stack_level(inspect.currentframe()) - ) + deprecate_ndim_indexing(result, stacklevel=find_stack_level()) return result if not isinstance(self.index, MultiIndex): @@ -1128,7 +1125,7 @@ def __setitem__(self, key, value) -> None: "Series. Use `series.iloc[an_int] = val` to treat the " "key as positional.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # can't use _mgr.setitem_inplace yet bc could have *both* # KeyError and then ValueError, xref GH#45070 @@ -1854,7 +1851,7 @@ def iteritems(self) -> Iterable[tuple[Hashable, Any]]: "iteritems is deprecated and will be removed in a future version. " "Use .items instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.items() @@ -1937,7 +1934,7 @@ def to_frame(self, name: Hashable = lib.no_default) -> DataFrame: "the future `None` will be used as the name of the resulting " "DataFrame column.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) name = lib.no_default @@ -2075,7 +2072,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: squeeze = False @@ -2134,7 +2131,7 @@ def count(self, level: Level = None): "deprecated and will be removed in a future version. Use groupby " "instead. ser.count(level=1) should use ser.groupby(level=1).count().", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if not isinstance(self.index, MultiIndex): raise ValueError("Series.count level is only valid with a MultiIndex") @@ -3143,7 +3140,7 @@ def append( "and will be removed from pandas in a future version. " "Use pandas.concat instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._append(to_append, ignore_index, verify_integrity) @@ -4816,7 +4813,7 @@ def _reduce( f"Calling Series.{name} with {kwd_name}={numeric_only} and " f"dtype {self.dtype} will raise a TypeError in the future", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) raise NotImplementedError( f"Series.{name} does not implement {kwd_name}." @@ -5654,7 +5651,7 @@ def between( "Boolean inputs to the `inclusive` argument are deprecated in " "favour of `both` or `neither`.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if inclusive: inclusive = "both" diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index acefb8c76c0d4..67eb4932a6a5c 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -2,7 +2,6 @@ import codecs from functools import wraps -import inspect import re from typing import ( TYPE_CHECKING, @@ -247,7 +246,7 @@ def __iter__(self) -> Iterator: warnings.warn( "Columnar iteration over characters will be deprecated in future releases.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) i = 0 g = self.get(i) @@ -1264,7 +1263,7 @@ def contains( "This pattern is interpreted as a regular expression, and has " "match groups. To actually get the groups, use str.extract.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) result = self._data.array._str_contains(pat, case, flags, na, regex) @@ -1476,11 +1475,7 @@ def replace( " In addition, single character regular expressions will " "*not* be treated as literal strings when regex=True." ) - warnings.warn( - msg, - FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) + 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)): diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 18e926c7039b0..8566468d4e23f 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -3,7 +3,6 @@ from collections import abc from datetime import datetime from functools import partial -import inspect from itertools import islice from typing import ( TYPE_CHECKING, @@ -1322,7 +1321,7 @@ def to_time( "`to_time` has been moved, should be imported from pandas.core.tools.times. " "This alias will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) from pandas.core.tools.times import to_time diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index e67cf45cec8a1..d6cb3d79c81e4 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -2,7 +2,6 @@ from __future__ import annotations from collections import defaultdict -import inspect from typing import cast import warnings @@ -204,5 +203,5 @@ def maybe_warn_args_and_kwargs(cls, kernel: str, args, kwargs) -> None: "no impact on the result and is deprecated. This will " "raise a TypeError in a future version of pandas.", category=FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 704c285197456..95a6689cec941 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -2,7 +2,6 @@ import datetime from functools import partial -import inspect from textwrap import dedent from typing import ( TYPE_CHECKING, @@ -393,7 +392,7 @@ def __init__( "into times instead." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # self.times cannot be str anymore self.times = cast("Series", self._selected_obj[self.times]) @@ -685,7 +684,7 @@ def vol(self, bias: bool = False, *args, **kwargs): "Use std instead." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.std(bias, *args, **kwargs) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 3225b9c0d2174..3e44a5af02178 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -172,7 +172,7 @@ def win_type(self): "win_type will no longer return 'freq' in a future version. " "Check the type of self.window instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return "freq" return self._win_type @@ -182,7 +182,7 @@ def is_datetimelike(self) -> bool: warnings.warn( "is_datetimelike is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._win_freq_i8 is not None @@ -190,7 +190,7 @@ def validate(self) -> None: warnings.warn( "validate is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._validate() @@ -550,7 +550,7 @@ def hfunc(values: ArrayLike) -> ArrayLike: "Select only valid columns before calling the operation. " f"Dropped columns were {dropped}", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self._resolve_output(df, obj) @@ -1968,7 +1968,7 @@ def count(self, numeric_only: bool = False): "Specify min_periods=0 instead." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.min_periods = 0 result = super().count() diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 8974c7f42bb3c..2867f1b067b2d 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -40,7 +40,6 @@ Pyperclip into running them with whatever permissions the Python process has. """ -import inspect __version__ = "1.7.0" @@ -275,12 +274,12 @@ def copy_dev_clipboard(text): warnings.warn( "Pyperclip cannot copy a blank string to the clipboard on Cygwin. " "This is effectively a no-op.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if "\r" in text: warnings.warn( "Pyperclip cannot handle \\r characters on Cygwin.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) with open("/dev/clipboard", "wt") as fd: @@ -526,7 +525,7 @@ def determine_clipboard(): warnings.warn( "Pyperclip's support for Cygwin is not perfect, " "see https://github.com/asweigart/pyperclip/issues/55", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return init_dev_clipboard_clipboard() diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 7cf01affd5a19..a3e778e552439 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -1,7 +1,6 @@ """ io on the clipboard """ from __future__ import annotations -import inspect from io import StringIO import warnings @@ -83,7 +82,7 @@ def read_clipboard(sep: str = r"\s+", **kwargs): # pragma: no cover elif len(sep) > 1 and kwargs.get("engine") == "c": warnings.warn( "read_clipboard with regex separator does not work properly with c engine.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return read_csv(StringIO(text), sep=sep, **kwargs) @@ -140,12 +139,12 @@ def to_clipboard( except TypeError: warnings.warn( "to_clipboard in excel mode requires a single character separator.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif sep is not None: warnings.warn( "to_clipboard with excel=False ignores the sep argument.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if isinstance(obj, ABCDataFrame): diff --git a/pandas/io/common.py b/pandas/io/common.py index 4d324b009d1e3..88311c64f5761 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -10,7 +10,6 @@ import dataclasses import functools import gzip -import inspect from io import ( BufferedIOBase, BytesIO, @@ -323,7 +322,7 @@ def _get_filepath_or_buffer( warnings.warn( "compression has no effect when passing a non-binary object as input.", RuntimeWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) compression_method = None @@ -339,7 +338,7 @@ def _get_filepath_or_buffer( warnings.warn( f"{compression} will not write the byte order mark for {encoding}", UnicodeWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # Use binary mode when converting path-like objects to file-like objects (fsspec) diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py index 99a838c61b996..34bba213593be 100644 --- a/pandas/io/date_converters.py +++ b/pandas/io/date_converters.py @@ -1,7 +1,6 @@ """This module is designed for community supported date conversion functions""" from __future__ import annotations -import inspect import warnings import numpy as np @@ -23,7 +22,7 @@ def parse_date_time(date_col, time_col) -> npt.NDArray[np.object_]: Use pd.to_datetime(date_col + " " + time_col).to_pydatetime() instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) date_col = _maybe_cast(date_col) time_col = _maybe_cast(time_col) @@ -43,7 +42,7 @@ def parse_date_fields(year_col, month_col, day_col) -> npt.NDArray[np.object_]: np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) year_col = _maybe_cast(year_col) @@ -70,7 +69,7 @@ def parse_all_fields( np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) year_col = _maybe_cast(year_col) @@ -94,7 +93,7 @@ def generic_parser(parse_func, *cols) -> np.ndarray: warnings.warn( "Use pd.to_datetime instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) N = _check_columns(cols) diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 47353ce1c402e..f555e7c5f5d95 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -3,7 +3,6 @@ import abc import datetime from functools import partial -import inspect from io import BytesIO import os from textwrap import fill @@ -728,7 +727,7 @@ def parse( warnings.warn( "convert_float is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) validate_header_arg(header) @@ -1131,7 +1130,7 @@ def __new__( warnings.warn( "Use of **kwargs is deprecated, use engine_kwargs instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # only switch class if generic(ExcelWriter) @@ -1165,7 +1164,7 @@ def __new__( "deprecated and will also raise a warning, it can " "be globally set and the warning suppressed.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # for mypy @@ -1343,7 +1342,7 @@ def _deprecate(self, attr: str) -> None: f"{attr} is not part of the public API, usage can give unexpected " "results and will be removed in a future version", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def _deprecate_set_book(self) -> None: @@ -1355,7 +1354,7 @@ def _deprecate_set_book(self) -> None: "usage can give unexpected or corrupted results and will be " "removed in a future version", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @property @@ -1682,7 +1681,7 @@ def __init__( f"only the xls format is supported. Install openpyxl instead." ) elif ext and ext != "xls": - stacklevel = find_stack_level(inspect.currentframe()) + stacklevel = find_stack_level() warnings.warn( f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, " f"only the xls format is supported. Install " diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index e86a1b0bcd635..cfc95bc9d9569 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -3,7 +3,6 @@ """ from __future__ import annotations -import inspect import re from typing import ( Callable, @@ -51,7 +50,7 @@ def expand(self, prop, value: str) -> Generator[tuple[str, str], None, None]: warnings.warn( f'Could not expand "{prop}: {value}"', CSSWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return for key, idx in zip(self.SIDES, mapping): @@ -96,7 +95,7 @@ def expand(self, prop, value: str) -> Generator[tuple[str, str], None, None]: warnings.warn( f'Too many tokens provided to "{prop}" (expected 1-3)', CSSWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) # TODO: Can we use current color as initial value to comply with CSS standards? @@ -335,7 +334,7 @@ def _error(): warnings.warn( f"Unhandled size: {repr(in_val)}", CSSWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.size_to_pt("1!!default", conversions=conversions) @@ -408,5 +407,5 @@ def parse(self, declarations_str: str) -> Iterator[tuple[str, str]]: warnings.warn( f"Ill-formatted attribute: expected a colon in {repr(decl)}", CSSWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index c4ddac088d901..ce7f663dd5703 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -7,7 +7,6 @@ lru_cache, reduce, ) -import inspect import itertools import re from typing import ( @@ -432,7 +431,7 @@ def color_to_excel(self, val: str | None) -> str | None: warnings.warn( f"Unhandled color format: {repr(val)}", CSSWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return None diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 471e77b56608d..db3c86b734cf4 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -6,7 +6,6 @@ from contextlib import contextmanager import copy from functools import partial -import inspect import operator from typing import ( TYPE_CHECKING, @@ -449,7 +448,7 @@ def render( warnings.warn( "this method is deprecated in favour of `Styler.to_html()`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if sparse_index is None: sparse_index = get_option("styler.sparse.index") @@ -2129,7 +2128,7 @@ def where( warnings.warn( "this method is deprecated in favour of `Styler.applymap()`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if other is None: @@ -2161,7 +2160,7 @@ def set_precision(self, precision: int) -> StylerRenderer: warnings.warn( "this method is deprecated in favour of `Styler.format(precision=..)`", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.precision = precision return self.format(precision=precision, na_rep=self.na_rep) @@ -2673,7 +2672,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=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.na_rep = na_rep return self.format(na_rep=na_rep, precision=self.precision) @@ -2727,7 +2726,7 @@ def hide_index( warnings.warn( 'this method is deprecated in favour of `Styler.hide(axis="index")`', FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.hide(axis="index", level=level, subset=subset, names=names) @@ -2780,7 +2779,7 @@ def hide_columns( warnings.warn( 'this method is deprecated in favour of `Styler.hide(axis="columns")`', FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return self.hide(axis="columns", level=level, subset=subset, names=names) @@ -3386,7 +3385,7 @@ def f(data: DataFrame, props: str) -> np.ndarray: warnings.warn( "`null_color` is deprecated: use `color` instead", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if color is None and null_color == lib.no_default: diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py index 7c323992d11a0..0d6cab20f2a59 100644 --- a/pandas/io/json/_table_schema.py +++ b/pandas/io/json/_table_schema.py @@ -5,7 +5,6 @@ """ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, Any, @@ -104,12 +103,12 @@ def set_default_names(data): if len(nms) == 1 and data.index.name == "index": warnings.warn( "Index name of 'index' is not round-trippable.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) elif len(nms) > 1 and any(x.startswith("level_") for x in nms): warnings.warn( "Index names beginning with 'level_' are not round-trippable.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return data diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index ae9a66eeaf353..45f6469a31f4f 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -5,7 +5,6 @@ import csv import datetime from enum import Enum -import inspect import itertools from typing import ( TYPE_CHECKING, @@ -569,7 +568,7 @@ def _convert_to_ndarrays( f"for column {c} - only the converter will be used." ), ParserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) try: @@ -907,7 +906,7 @@ def _check_data_length( "Length of header or names does not match length of data. This leads " "to a loss of data with index_col=False.", ParserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) @overload diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index dc104b3020f14..106f4df4370b3 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -1,7 +1,6 @@ from __future__ import annotations from collections import defaultdict -import inspect from typing import ( TYPE_CHECKING, Hashable, @@ -418,11 +417,7 @@ def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict: f"Specify dtype option on import or set low_memory=False." ] ) - warnings.warn( - warning_message, - DtypeWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) + warnings.warn(warning_message, DtypeWarning, stacklevel=find_stack_level()) return result diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 5d5b497a04c04..c3b196f538463 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -5,7 +5,6 @@ defaultdict, ) import csv -import inspect from io import StringIO import re import sys @@ -600,7 +599,7 @@ def _handle_usecols( "Defining usecols with out of bounds indices is deprecated " "and will raise a ParserError in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) col_indices = self.usecols diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index d638042eaf482..c1698c68ce465 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -5,7 +5,6 @@ from collections import abc import csv -import inspect import sys from textwrap import fill from types import TracebackType @@ -1636,7 +1635,7 @@ def _clean_options( "engine='python'." ), ParserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) index_col = options["index_col"] @@ -1655,11 +1654,7 @@ def _clean_options( f"The {arg} argument has been deprecated and will be " f"removed in a future version. {depr_default.msg}\n\n" ) - warnings.warn( - msg, - FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) else: result[arg] = parser_default @@ -2249,9 +2244,7 @@ def _merge_with_dialect_properties( if conflict_msgs: warnings.warn( - "\n\n".join(conflict_msgs), - ParserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + "\n\n".join(conflict_msgs), ParserWarning, stacklevel=find_stack_level() ) kwds[param] = dialect_val return kwds diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d93590e750c85..edd6c3bd9d1e5 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -10,7 +10,6 @@ date, tzinfo, ) -import inspect import itertools import os import re @@ -693,7 +692,7 @@ def iteritems(self): "iteritems is deprecated and will be removed in a future version. " "Use .items instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) yield from self.items() @@ -2198,9 +2197,7 @@ def update_info(self, info) -> None: if key in ["freq", "index_name"]: ws = attribute_conflict_doc % (key, existing_value, value) warnings.warn( - ws, - AttributeConflictWarning, - stacklevel=find_stack_level(inspect.currentframe()), + ws, AttributeConflictWarning, stacklevel=find_stack_level() ) # reset @@ -3095,11 +3092,7 @@ def write_array( pass else: ws = performance_doc % (inferred_type, key, items) - warnings.warn( - ws, - PerformanceWarning, - stacklevel=find_stack_level(inspect.currentframe()), - ) + warnings.warn(ws, PerformanceWarning, stacklevel=find_stack_level()) vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom()) vlarr.append(value) @@ -3540,7 +3533,7 @@ def validate_version(self, where=None) -> None: warnings.warn( ws, IncompatibilityWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def validate_min_itemsize(self, min_itemsize) -> None: diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index a5df2bde38096..a66910392d788 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -11,7 +11,6 @@ from collections import abc from datetime import datetime -import inspect import struct import warnings @@ -416,7 +415,7 @@ def _record_count(self) -> int: if total_records_length % 80 != 0: warnings.warn( "xport file may be corrupted.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if self.record_length > 80: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index f5ad0787ff8df..305fc8ba4b040 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -12,7 +12,6 @@ time, ) from functools import partial -import inspect import re from typing import ( TYPE_CHECKING, @@ -763,7 +762,7 @@ def pandasSQL_builder(con, schema: str | None = None) -> SQLDatabase | SQLiteDat "database string URI or sqlite3 DBAPI2 connection. " "Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return SQLiteDatabase(con) @@ -1196,7 +1195,7 @@ def _sqlalchemy_type(self, col): "the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the database.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return BigInteger elif col_type == "floating": @@ -1660,7 +1659,7 @@ def check_case_sensitive( warnings.warn( msg, UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def to_sql( @@ -1969,7 +1968,7 @@ def _sql_type_name(self, col): "the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the database.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) col_type = "integer" diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 6baf5f0da8612..06cba7388b294 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -13,7 +13,6 @@ from collections import abc import datetime -import inspect from io import BytesIO import os import struct @@ -356,7 +355,7 @@ def convert_delta_safe(base, deltas, unit) -> Series: warnings.warn( "Encountered %tC format. Leaving in Stata Internal Format.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) conv_dates = Series(dates, dtype=object) if has_bad_values: @@ -475,7 +474,7 @@ def g(x: datetime.datetime) -> int: elif fmt in ["%tC", "tC"]: warnings.warn( "Stata Internal Format tC not supported.", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) conv_dates = dates elif fmt in ["%td", "td"]: @@ -659,7 +658,7 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame: warnings.warn( ws, PossiblePrecisionLoss, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return data @@ -715,7 +714,7 @@ def _prepare_value_labels(self): warnings.warn( value_label_mismatch_doc.format(self.labname), ValueLabelTypeMismatch, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) category = category.encode(self._encoding) offsets.append(self.text_len) @@ -1533,7 +1532,7 @@ def _decode(self, s: bytes) -> str: warnings.warn( msg, UnicodeWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return s.decode("latin-1") @@ -1932,7 +1931,7 @@ def _do_convert_categoricals( warnings.warn( categorical_conversion_warning, CategoricalConversionWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) initial_categories = None cat_data = Categorical( @@ -2516,7 +2515,7 @@ def _check_column_names(self, data: DataFrame) -> DataFrame: warnings.warn( ws, InvalidColumnName, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self._converted_names = converted_names @@ -2684,7 +2683,7 @@ def write_file(self) -> None: f"This save was not successful but {self._fname} could not " "be deleted. This file is not valid.", ResourceWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) raise exc diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 3c9d82bf46d11..5bfc8c6b5b371 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1,7 +1,6 @@ from __future__ import annotations import importlib -import inspect import itertools import types from typing import ( @@ -890,7 +889,7 @@ def _get_call_args(backend_name, data, args, kwargs): "`sort_columns` is deprecated and will be removed in a future " "version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if args and isinstance(data, ABCSeries): diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 6067f7e7fca84..dca477f388bbb 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect from typing import ( TYPE_CHECKING, Collection, @@ -98,7 +97,7 @@ def _validate_color_args(self): warnings.warn( "'color' and 'colormap' cannot be used " "simultaneously. Using 'color'", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.color = self.kwds.pop("color") diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 201fdff249d67..5c3a79927ec2f 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -4,7 +4,6 @@ ABC, abstractmethod, ) -import inspect from typing import ( TYPE_CHECKING, Hashable, @@ -401,7 +400,7 @@ def _validate_color_args(self): ) and self.colormap is not None: warnings.warn( "'color' and 'colormap' cannot be used simultaneously. Using 'color'", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if "color" in self.kwds and self.style is not None: diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index c1b37eca2a76c..2878f4dbf279c 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import itertools from typing import ( TYPE_CHECKING, @@ -124,7 +123,7 @@ def _derive_colors( if colormap is not None: warnings.warn( "'color' and 'colormap' cannot be used simultaneously. Using 'color'", - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return _get_colors_from_color(color) else: diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 5daf1683b28e3..d3c16a6d53916 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -1,7 +1,6 @@ # being a bit too dynamic from __future__ import annotations -import inspect from math import ceil from typing import ( TYPE_CHECKING, @@ -234,14 +233,14 @@ def create_subplots( warnings.warn( "When passing multiple axes, layout keyword is ignored.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if sharex or sharey: warnings.warn( "When passing multiple axes, sharex and sharey " "are ignored. These settings must be specified when creating axes.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) if ax.size == naxes: fig = ax.flat[0].get_figure() @@ -264,7 +263,7 @@ def create_subplots( "To output multiple subplots, the figure containing " "the passed axes is being cleared.", UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) fig.clear() diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index ce62a15eda367..e74ab61d3881d 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -1,6 +1,5 @@ from __future__ import annotations -import inspect import warnings import numpy as np @@ -117,7 +116,7 @@ def get_offset(name: str) -> BaseOffset: "get_offset is deprecated and will be removed in a future version, " "use to_offset instead.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return _get_offset(name) @@ -236,7 +235,7 @@ def __init__(self, index, warn: bool = True) -> None: "warn is deprecated (and never implemented) and " "will be removed in a future version.", FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) self.warn = warn diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index e95025371a204..5d62f57126ef3 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -326,7 +326,7 @@ def wrapper(*args, **kwargs): warnings.warn( msg.format(arguments=_format_argument_list(allow_args)), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) return func(*args, **kwargs) diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index ebd92e8366e18..f3a640feb46fc 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -import functools import inspect import os from typing import Generator @@ -26,16 +25,10 @@ def rewrite_exception(old_name: str, new_name: str) -> Generator[None, None, Non raise -@functools.lru_cache -def find_stack_level(frame) -> int: +def find_stack_level() -> int: """ Find the first place in the stack that is not inside pandas (tests notwithstanding). - - ``frame`` should be passed as ``inspect.currentframe()`` by the - calling function. - - https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow """ import pandas as pd @@ -43,7 +36,9 @@ def find_stack_level(frame) -> int: pkg_dir = os.path.dirname(pd.__file__) test_dir = os.path.join(pkg_dir, "tests") - n = 1 + # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow + frame = inspect.currentframe() + n = 0 while frame: fname = inspect.getfile(frame) if fname.startswith(pkg_dir) and not fname.startswith(test_dir): diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index 30314bf2529c5..4594c0cb057df 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -4,7 +4,6 @@ """ from __future__ import annotations -import inspect from typing import ( Any, Iterable, @@ -355,9 +354,7 @@ def validate_axis_style_args( "positional arguments for 'index' or 'columns' will raise " "a 'TypeError'." ) - warnings.warn( - msg, FutureWarning, stacklevel=find_stack_level(inspect.currentframe()) - ) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) out[data._get_axis_name(0)] = args[0] out[data._get_axis_name(1)] = args[1] else: diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 5585ea0b58628..db9bfc274cd78 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1,4 +1,3 @@ -import inspect import warnings from pandas.util._exceptions import find_stack_level @@ -11,5 +10,5 @@ "public API at pandas.testing instead." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) diff --git a/scripts/list_future_warnings.sh b/scripts/list_future_warnings.sh index dc3d0b59b618b..a75aea905a4c8 100755 --- a/scripts/list_future_warnings.sh +++ b/scripts/list_future_warnings.sh @@ -6,7 +6,7 @@ # This is useful to detect features that have been deprecated, and should be # removed from the code. For example, if a line of code contains: # -# warning.warn('Method deprecated', FutureWarning, stacklevel=find_stack_level(inspect.currentframe())) +# warning.warn('Method deprecated', FutureWarning, stacklevel=find_stack_level()) # # Which is released in Pandas 0.20.0, then it is expected that the method # is removed before releasing Pandas 0.24.0, including the warning. If it