From b78904f9370e57bce5958a468fe14caad5cb2551 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Fri, 12 Nov 2021 16:22:59 -0500 Subject: [PATCH] ENH: Use find_stack_level --- pandas/_testing/asserters.py | 11 ++++++----- pandas/io/common.py | 3 ++- pandas/io/date_converters.py | 9 +++++---- pandas/io/excel/_base.py | 4 ++-- pandas/io/parsers/base_parser.py | 5 +++-- pandas/io/parsers/c_parser_wrapper.py | 3 ++- pandas/io/parsers/python_parser.py | 3 ++- pandas/io/parsers/readers.py | 6 ++++-- pandas/io/pytables.py | 7 +++++-- pandas/io/sql.py | 7 ++++--- pandas/plotting/_matplotlib/tools.py | 6 ++++-- pandas/tseries/frequencies.py | 3 ++- pandas/util/_validators.py | 4 +++- pandas/util/testing.py | 4 +++- 14 files changed, 47 insertions(+), 28 deletions(-) diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index c9f7fd43c1050..05cd3a3a72257 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -11,6 +11,7 @@ ) from pandas._libs.missing import is_matching_na import pandas._libs.testing as _testing +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_bool, @@ -106,7 +107,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=2, + stacklevel=find_stack_level(), ) # https://github.com/python/mypy/issues/7642 # error: Argument 1 to "_get_tol_from_less_precise" has incompatible @@ -340,7 +341,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=2, + stacklevel=find_stack_level(), ) # https://github.com/python/mypy/issues/7642 # error: Argument 1 to "_get_tol_from_less_precise" has incompatible @@ -818,7 +819,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=2, + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -964,7 +965,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=2, + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) @@ -1247,7 +1248,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=2, + stacklevel=find_stack_level(), ) rtol = atol = _get_tol_from_less_precise(check_less_precise) diff --git a/pandas/io/common.py b/pandas/io/common.py index be6577e646ac3..12c7afc8ee2e4 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -49,6 +49,7 @@ import_lzma, ) from pandas.compat._optional import import_optional_dependency +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_file_like @@ -270,7 +271,7 @@ def _get_filepath_or_buffer( warnings.warn( "compression has no effect when passing a non-binary object as input.", RuntimeWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) compression_method = None diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py index f079a25f69fec..ef60afa195234 100644 --- a/pandas/io/date_converters.py +++ b/pandas/io/date_converters.py @@ -4,6 +4,7 @@ import numpy as np from pandas._libs.tslibs import parsing +from pandas.util._exceptions import find_stack_level def parse_date_time(date_col, time_col): @@ -18,7 +19,7 @@ def parse_date_time(date_col, time_col): Use pd.to_datetime(date_col + " " + time_col).to_pydatetime() instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) date_col = _maybe_cast(date_col) time_col = _maybe_cast(time_col) @@ -38,7 +39,7 @@ def parse_date_fields(year_col, month_col, day_col): np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) year_col = _maybe_cast(year_col) @@ -63,7 +64,7 @@ def parse_all_fields(year_col, month_col, day_col, hour_col, minute_col, second_ np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array. """, # noqa: E501 FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) year_col = _maybe_cast(year_col) @@ -89,7 +90,7 @@ def generic_parser(parse_func, *cols): Use pd.to_datetime instead. """, FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) N = _check_columns(cols) diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index e543c9161a26e..1caf334f9607e 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -833,7 +833,7 @@ def __new__( warnings.warn( "Use of **kwargs is deprecated, use engine_kwargs instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # only switch class if generic(ExcelWriter) @@ -868,7 +868,7 @@ def __new__( "deprecated and will also raise a warning, it can " "be globally set and the warning suppressed.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) cls = get_writer(engine) diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 339585810bec1..6374f52f6964b 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -32,6 +32,7 @@ ParserError, ParserWarning, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( @@ -558,7 +559,7 @@ def _convert_to_ndarrays( f"for column {c} - only the converter will be used." ), ParserWarning, - stacklevel=7, + stacklevel=find_stack_level(), ) try: @@ -830,7 +831,7 @@ def _check_data_length(self, columns: list[str], data: list[ArrayLike]) -> None: "Length of header or names does not match length of data. This leads " "to a loss of data with index_col=False.", ParserWarning, - stacklevel=6, + stacklevel=find_stack_level(), ) def _evaluate_usecols(self, usecols, names): diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 352dd998dda0f..db750cded45e5 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -10,6 +10,7 @@ FilePathOrBuffer, ) from pandas.errors import DtypeWarning +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -387,7 +388,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=8) + 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 b0e868b260369..4d596aa2f3fa6 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -24,6 +24,7 @@ EmptyDataError, ParserError, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_integer from pandas.core.dtypes.inference import is_dict_like @@ -555,7 +556,7 @@ def _handle_usecols( "Defining usecols with out of bounds indices is deprecated " "and will raise a ParserError in a future version.", FutureWarning, - stacklevel=8, + stacklevel=find_stack_level(), ) col_indices = self.usecols diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index 6d3cc84a31d05..6fb9497dbc1d6 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -1041,7 +1041,7 @@ def _clean_options(self, options, engine): "engine='python'." ), ParserWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) index_col = options["index_col"] @@ -1573,7 +1573,9 @@ def _merge_with_dialect_properties( conflict_msgs.append(msg) if conflict_msgs: - warnings.warn("\n\n".join(conflict_msgs), ParserWarning, stacklevel=2) + warnings.warn( + "\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 8c8e9b9feeb80..0e886befb5f2f 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -45,6 +45,7 @@ from pandas.compat.pickle_compat import patch_pickle from pandas.errors import PerformanceWarning from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_object, @@ -2190,7 +2191,9 @@ def update_info(self, info): # frequency/name just warn if key in ["freq", "index_name"]: ws = attribute_conflict_doc % (key, existing_value, value) - warnings.warn(ws, AttributeConflictWarning, stacklevel=6) + warnings.warn( + ws, AttributeConflictWarning, stacklevel=find_stack_level() + ) # reset idx[key] = None @@ -3080,7 +3083,7 @@ def write_array( pass else: ws = performance_doc % (inferred_type, key, items) - warnings.warn(ws, PerformanceWarning, stacklevel=7) + warnings.warn(ws, PerformanceWarning, stacklevel=find_stack_level()) vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom()) vlarr.append(value) diff --git a/pandas/io/sql.py b/pandas/io/sql.py index ec5262ee3a04c..867ce52cbde6f 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -28,6 +28,7 @@ from pandas._typing import DtypeArg from pandas.compat._optional import import_optional_dependency from pandas.errors import AbstractMethodError +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_datetime64tz_dtype, @@ -1159,7 +1160,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=8, + stacklevel=find_stack_level(), ) return BigInteger elif col_type == "floating": @@ -1886,7 +1887,7 @@ def _create_table_setup(self): pat = re.compile(r"\s+") column_names = [col_name for col_name, _, _ in column_names_and_types] if any(map(pat.search, column_names)): - warnings.warn(_SAFE_NAMES_WARNING, stacklevel=6) + warnings.warn(_SAFE_NAMES_WARNING, stacklevel=find_stack_level()) escape = _get_valid_sqlite_name @@ -1948,7 +1949,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=8, + stacklevel=find_stack_level(), ) col_type = "integer" diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 9679e79d8c4ba..5314a61191d78 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -13,6 +13,8 @@ import matplotlib.ticker as ticker import numpy as np +from pandas.util._exceptions import find_stack_level + from pandas.core.dtypes.common import is_list_like from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -233,7 +235,7 @@ def create_subplots( "When passing multiple axes, sharex and sharey " "are ignored. These settings must be specified when creating axes.", UserWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) if ax.size == naxes: fig = ax.flat[0].get_figure() @@ -256,7 +258,7 @@ def create_subplots( "To output multiple subplots, the figure containing " "the passed axes is being cleared.", UserWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) fig.clear() diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index c2d7f7b3f716c..fc01771507888 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -29,6 +29,7 @@ from pandas._libs.tslibs.parsing import get_rule_month from pandas._typing import npt from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_datetime64_dtype, @@ -116,7 +117,7 @@ def get_offset(name: str) -> DateOffset: "get_offset is deprecated and will be removed in a future version, " "use to_offset instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return _get_offset(name) diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index f8bd1ec7bc96a..ee54b1b2074cb 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -12,6 +12,8 @@ import numpy as np +from pandas.util._exceptions import find_stack_level + from pandas.core.dtypes.common import ( is_bool, is_integer, @@ -339,7 +341,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name): "positional arguments for 'index' or 'columns' will raise " "a 'TypeError'." ) - warnings.warn(msg, FutureWarning, stacklevel=4) + 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 af9fe4846b27d..0ab59a202149d 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1,5 +1,7 @@ import warnings +from pandas.util._exceptions import find_stack_level + from pandas._testing import * # noqa warnings.warn( @@ -8,5 +10,5 @@ "public API at pandas.testing instead." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), )