From c677ae408a087a0434127778bade90a2d0ea039e Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli <33491632+MarcoGorelli@users.noreply.github.com> Date: Fri, 14 Oct 2022 08:43:38 +0100 Subject: [PATCH] REVERT caching in find_stack_level (#49053) Revert "PERF cache find_stack_level (#48023)" This reverts commit 2f8d0a36703e81e4dca52ca9fe4f58c910c1b304. Co-authored-by: MarcoGorelli <> (cherry picked from commit 0106c26529900bad0561efb9c9180f7f016365b0) --- .../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 | 4 +- 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 | 23 ++++--- 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 | 11 ++-- 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, 330 insertions(+), 478 deletions(-) diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 15931a1a3eb83..95803b5be76c3 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -134,7 +134,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 fc35b95bba7dd..b4b06c819431f 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 e8b7160af9b2c..c391a82d30c4a 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -961,7 +961,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 = {} @@ -1012,7 +1012,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 3ba49d9ee3e48..a24a07b423eda 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -1,4 +1,3 @@ -import inspect import warnings cimport cython @@ -848,7 +847,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 b25095ead790b..519bc656488c0 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1,5 +1,3 @@ -import inspect - cimport cython import warnings @@ -291,7 +289,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 909541d24121e..0a5f86ba63569 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 @@ -138,7 +137,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 @@ -382,7 +381,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 d799770a57be2..678ecf103b3d6 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1,4 +1,3 @@ -import inspect import operator import re import time @@ -502,7 +501,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) @@ -512,7 +511,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) @@ -823,7 +822,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) @@ -831,7 +830,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 b442e32071011..074cc5504d6da 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 @@ -217,7 +216,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( @@ -225,7 +224,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 d2d4838bfafc0..a9d607ca9fd30 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 4fc0b49e6f5a3..b0200990809cc 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 @@ -684,7 +683,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': @@ -1062,7 +1061,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 @@ -1078,7 +1077,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 @@ -1285,7 +1284,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 2655c25ed0893..a574b648278fb 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 @@ -257,7 +256,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 @@ -369,7 +368,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: @@ -670,7 +669,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 @@ -1176,7 +1175,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, @@ -1255,7 +1254,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: @@ -1264,7 +1263,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) @@ -1456,7 +1455,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)) @@ -1692,7 +1691,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) @@ -1709,7 +1708,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) @@ -2045,7 +2044,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 f6af1c72dfb2f..6c3b8960d6697 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) @@ -819,7 +818,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) @@ -974,7 +973,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) @@ -1267,7 +1266,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 b66a91826b689..07fa5799fe371 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 fc2050dcc7f4d..0da9defcf2468 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -891,9 +891,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 @@ -1093,7 +1091,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) @@ -1718,7 +1716,7 @@ def diff(arr, n: int, axis: int = 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 7c2cb1455995b..4c535abe585d4 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -291,7 +291,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) @@ -423,7 +423,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 4e8e4ea7e8d87..280a599de84ed 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 @@ -349,9 +348,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 4b87194a2f1f1..be44c7e4b562e 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -476,7 +476,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 fff7772c2cf7d..7219573ac1521 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 ( @@ -395,7 +394,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] @@ -750,7 +749,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) @@ -874,7 +873,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 @@ -1011,7 +1010,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 @@ -1126,7 +1125,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 @@ -1190,7 +1189,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 @@ -1274,7 +1273,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 @@ -1350,7 +1349,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 @@ -1438,7 +1437,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 @@ -2047,7 +2046,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) @@ -2064,7 +2063,7 @@ def _codes(self, value: np.ndarray): "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) @@ -2089,7 +2088,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) @@ -2382,7 +2381,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) @@ -2525,7 +2524,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) @@ -2649,7 +2648,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 253b582eddf2c..471ecc5950dd9 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 @@ -1373,7 +1372,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 6b1f0bfac8f7a..f1ddba0cefe35 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, Literal, @@ -474,7 +473,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}'") @@ -641,7 +640,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) @@ -718,7 +717,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) @@ -1116,7 +1115,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: @@ -1158,7 +1157,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 @@ -1360,7 +1359,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: @@ -2257,7 +2256,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 5831aafa6a293..a389f1f282ee0 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 ( @@ -415,7 +414,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): @@ -494,7 +493,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: @@ -781,7 +780,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 @@ -1191,9 +1190,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) @@ -1333,7 +1330,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 1323ecaa7f1e2..b04d4348cb9f6 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, @@ -1070,7 +1069,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 41ed68e73a4c0..980e7a79414ba 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 0a9bb6a4bb6fa..f833b59a2484d 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 a4b83fc557413..afb4d0d549c45 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): 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 2579f736a9703..e6beab0b34038 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): "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): "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 e1a69086609e9..4b63d492ec1dd 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, @@ -569,7 +568,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: @@ -581,7 +580,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 @@ -853,7 +852,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 6d04dd755dbfd..7fb58468746a8 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -371,7 +371,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 @@ -387,7 +387,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) @@ -407,7 +407,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 ceb3d16949f91..f7df0b8a3d035 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, @@ -631,7 +630,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): @@ -1284,7 +1283,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 @@ -1343,7 +1342,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) @@ -1383,7 +1382,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) @@ -1752,7 +1751,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) @@ -1870,7 +1869,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 @@ -1881,7 +1880,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 aeb9bc7a31674..9355e81f41cda 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) @@ -1389,7 +1388,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 28e1498c5906c..5fb63e09ae1fb 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, @@ -158,7 +157,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 1f3f68c6d409b..9c38267cbe033 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 @@ -679,7 +678,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 @@ -1358,7 +1357,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() @@ -1964,7 +1963,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) @@ -1988,7 +1987,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"): @@ -2832,7 +2831,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") @@ -3446,7 +3445,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( @@ -3837,7 +3836,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( @@ -4947,9 +4946,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): @@ -8380,7 +8377,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: squeeze = False @@ -9752,7 +9749,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) @@ -10717,7 +10714,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") @@ -10819,7 +10816,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) @@ -10920,7 +10917,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 e3153487cbf81..958bba2da54ce 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 @@ -496,7 +495,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} @@ -793,7 +792,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 @@ -2097,7 +2096,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): @@ -3435,9 +3434,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: @@ -3866,7 +3863,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) @@ -4022,7 +4019,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: @@ -4213,11 +4210,7 @@ def _check_setitem_copy(self, t="setting", force=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: """ @@ -5945,7 +5938,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) @@ -8412,7 +8405,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 @@ -9128,7 +9121,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: @@ -9184,7 +9177,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: @@ -9195,7 +9188,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: @@ -9969,7 +9962,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) @@ -10047,7 +10040,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 @@ -10246,9 +10239,7 @@ def slice_shift(self: NDFrameT, periods: int = 1, 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 @@ -10300,7 +10291,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: @@ -11133,7 +11124,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( @@ -11267,7 +11258,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 @@ -11341,7 +11332,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 @@ -11354,7 +11345,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 @@ -11478,7 +11469,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, @@ -11566,9 +11557,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( @@ -11576,7 +11565,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: @@ -11587,7 +11576,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) @@ -12034,7 +12023,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 16a7e537544c3..97d332394e045 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, @@ -1241,7 +1240,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 @@ -1411,7 +1410,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 46ab1f6a86329..66c459b90a999 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -833,7 +833,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) @@ -1366,7 +1366,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" @@ -1628,9 +1628,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. @@ -2963,7 +2961,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) @@ -3013,7 +3011,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) @@ -4397,7 +4395,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( @@ -4407,5 +4405,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 e1df2d5d2f91b..52377f4bf967c 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, @@ -983,7 +982,7 @@ def _check_deprecated_resample_kwargs(kwargs, origin): "\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( @@ -994,5 +993,5 @@ def _check_deprecated_resample_kwargs(kwargs, origin): '\n>>> df = df.resample(freq="3s").mean()' '\n>>> df.index = df.index.to_timestamp() + to_offset("8H")\n', FutureWarning, - stacklevel=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 67db8c41e7d5e..5abd04c29e5d4 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 ( @@ -439,7 +438,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 @@ -617,7 +616,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) @@ -685,7 +684,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 @@ -799,7 +798,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} @@ -1010,7 +1009,7 @@ def ravel(self, order="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]]" @@ -1310,7 +1309,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] @@ -1325,7 +1324,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 @@ -1517,7 +1516,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: @@ -1718,7 +1717,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 @@ -2308,7 +2307,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 @@ -2733,7 +2732,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"] @@ -2778,7 +2777,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 @@ -3159,7 +3158,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) @@ -3170,7 +3169,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) @@ -3181,7 +3180,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) @@ -3237,7 +3236,7 @@ def _deprecate_dti_setop(self, other: Index, setop: str_t): "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 @@ -3817,7 +3816,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: @@ -4287,7 +4286,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 @@ -4321,7 +4320,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: @@ -4472,7 +4471,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) @@ -5289,7 +5288,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 @@ -5936,7 +5935,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) @@ -6004,7 +6003,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): @@ -7272,7 +7271,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(), ) @@ -7470,7 +7469,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 @@ -7526,6 +7525,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 d1bdedee5caa0..a39a8105bed71 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 6867ef936d45e..1a13cddd99b95 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, @@ -399,7 +398,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 80138c25b0c27..33cc39cc26060 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, @@ -441,7 +440,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 @@ -565,7 +564,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( @@ -575,7 +574,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 @@ -678,9 +677,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): """ @@ -829,7 +826,7 @@ def check_str_or_none(point): "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): @@ -1109,7 +1106,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 63c78b7002786..493d03ed1a86c 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, @@ -924,7 +923,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 @@ -1085,7 +1084,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 @@ -1198,7 +1197,7 @@ def copy( "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: @@ -1206,7 +1205,7 @@ def copy( "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 @@ -1238,7 +1237,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 @@ -1801,7 +1800,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 @@ -1870,7 +1869,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() @@ -1914,7 +1913,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 @@ -2280,7 +2279,7 @@ def drop(self, codes, level=None, errors="raise"): "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) @@ -2956,7 +2955,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) @@ -3395,7 +3394,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: diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index d114fe47fa0f1..a597bea0eb724 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, @@ -361,7 +360,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 fedcba7aa9644..c034d9416eae7 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 @@ -367,7 +366,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 9f49c7456d9ce..376c98b6e176f 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 464cb3f07df33..913aa2e5b0e18 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, @@ -1501,7 +1500,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): @@ -2028,7 +2027,7 @@ def _setitem_single_column(self, loc: int, value, plane_indexer): "`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? @@ -2511,7 +2510,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): @@ -2665,7 +2664,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) @@ -2676,5 +2675,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 eab463a03d27f..9c6b3e506b1d4 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, @@ -182,7 +181,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) @@ -253,7 +252,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 @@ -1572,7 +1571,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 9f4c799941afd..881cea45bdb34 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, @@ -1010,7 +1009,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 @@ -1418,7 +1417,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: @@ -1882,7 +1881,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 dde4d07b7915c..e9fefd9268870 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 @@ -302,7 +301,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 56c04b8a6d6e3..0ac43b773bbf9 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, @@ -565,7 +564,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) @@ -752,7 +751,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 3d9e4f0c69c62..5328c7995ea6f 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, @@ -553,7 +552,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 73f6aff82f330..5de9c8e2f4108 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 import warnings @@ -60,7 +59,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 95a607c68110e..ec3dfa0b5f87e 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, @@ -681,9 +680,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) @@ -1289,7 +1286,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 @@ -1302,7 +1299,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 @@ -2448,7 +2445,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) @@ -2498,7 +2495,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 0270a5dd75952..1a99bf0d62e72 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 0e6f40564c003..8f0faae338e6a 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, @@ -391,7 +390,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) @@ -923,7 +922,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) @@ -1054,9 +1053,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): @@ -1120,7 +1117,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 @@ -1846,7 +1843,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() @@ -1929,7 +1926,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 @@ -2067,7 +2064,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) else: squeeze = False @@ -2126,7 +2123,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") @@ -3137,7 +3134,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) @@ -4810,7 +4807,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}." @@ -5648,7 +5645,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 0ee9f15c3630c..7f50381d10efd 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, @@ -244,7 +243,7 @@ def __iter__(self): 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) @@ -1255,7 +1254,7 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True): "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) @@ -1467,11 +1466,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 203a5711b7a59..4739fb49e0d07 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, @@ -1289,7 +1288,7 @@ def to_time(arg, format=None, infer_time_format=False, errors="raise"): "`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 29b7558f40353..e31b5c60a37ee 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 32559d0d88bcf..020ca71050015 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, @@ -392,7 +391,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]) @@ -684,7 +683,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 3fc48b121419a..c92c448304de2 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -171,7 +171,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 @@ -181,7 +181,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 @@ -189,7 +189,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() @@ -549,7 +549,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) @@ -1967,7 +1967,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 03599497f8d03..635fce37f1a0f 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 2fae19df13f8b..f31de63aa42a7 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 5885a3b9d14d7..85e92da8c2a54 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) @@ -96,7 +95,7 @@ def generic_parser(parse_func, *cols) -> np.ndarray: 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 f6a66307e2191..4b7cd1a99ed20 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 @@ -727,7 +726,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) @@ -1130,7 +1129,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) @@ -1164,7 +1163,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 @@ -1346,7 +1345,7 @@ def _deprecate(self, attr: str): 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: @@ -1358,7 +1357,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 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 a2a9079642344..9c3e4f0bb02fb 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 ( Any, @@ -443,7 +442,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") @@ -2123,7 +2122,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: @@ -2155,7 +2154,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) @@ -2667,7 +2666,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) @@ -2721,7 +2720,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) @@ -2774,7 +2773,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) @@ -3380,7 +3379,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 89bf903fea8dd..0e40e47bf7cb1 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, @@ -560,7 +559,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: @@ -858,7 +857,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 6e4ea85548230..874eaee184d28 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, @@ -410,11 +409,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 ff8c21ab89f30..7c03a81dbc0e6 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 72661dd8fe56c..356c357f2f967 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 typing import ( @@ -1618,7 +1617,7 @@ def _clean_options( "engine='python'." ), ParserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) index_col = options["index_col"] @@ -1637,11 +1636,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 @@ -2226,9 +2221,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 8d063e470dafd..6b0cfc51dbdd4 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 @@ -688,7 +687,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() @@ -2197,9 +2196,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 @@ -3097,11 +3094,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) @@ -3549,7 +3542,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 648c58dee6600..c188e8d1b03c3 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 b5b963f1c31e0..b5036e113f8c6 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, @@ -762,7 +761,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) @@ -1195,7 +1194,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": @@ -1659,7 +1658,7 @@ def check_case_sensitive( warnings.warn( msg, UserWarning, - stacklevel=find_stack_level(inspect.currentframe()), + stacklevel=find_stack_level(), ) def to_sql( @@ -1968,7 +1967,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 a0b9a0d247533..fd4d2c2354398 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 @@ -355,7 +354,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: @@ -472,7 +471,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"]: @@ -656,7 +655,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 @@ -712,7 +711,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) @@ -1525,7 +1524,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") @@ -1924,7 +1923,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( @@ -2508,7 +2507,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 @@ -2676,7 +2675,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 1fcefe884dec4..9c418ea7cf30b 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 ( @@ -889,7 +888,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 d85495b70e6c3..6789485f2b9eb 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, Literal, @@ -93,7 +92,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 f93dbb4256323..1302413916d58 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, @@ -400,7 +399,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 d8823c7ec8d3d..d462fdb515251 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, @@ -128,7 +127,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 8f0ea70ab4124..1925dd8c4023c 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 3edabc7c089e1..9f553686ca829 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) @@ -235,7 +234,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 757d12f3f026e..aa4b7cccf823c 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 fcd191e25ced5..c718451fbf621 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 Iterator @@ -26,16 +25,10 @@ def rewrite_exception(old_name: str, new_name: str) -> Iterator[None]: 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 2b5be2d48f382..3ac391cb87b52 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