Skip to content

Commit 0f386e4

Browse files
authored
ENH: Use find_stack_level (#44416)
1 parent 14bfd6b commit 0f386e4

File tree

14 files changed

+47
-28
lines changed

14 files changed

+47
-28
lines changed

pandas/_testing/asserters.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
)
1212
from pandas._libs.missing import is_matching_na
1313
import pandas._libs.testing as _testing
14+
from pandas.util._exceptions import find_stack_level
1415

1516
from pandas.core.dtypes.common import (
1617
is_bool,
@@ -106,7 +107,7 @@ def assert_almost_equal(
106107
"is deprecated and will be removed in a future version. "
107108
"You can stop passing 'check_less_precise' to silence this warning.",
108109
FutureWarning,
109-
stacklevel=2,
110+
stacklevel=find_stack_level(),
110111
)
111112
# https://github.com/python/mypy/issues/7642
112113
# error: Argument 1 to "_get_tol_from_less_precise" has incompatible
@@ -340,7 +341,7 @@ def _get_ilevel_values(index, level):
340341
"is deprecated and will be removed in a future version. "
341342
"You can stop passing 'check_less_precise' to silence this warning.",
342343
FutureWarning,
343-
stacklevel=2,
344+
stacklevel=find_stack_level(),
344345
)
345346
# https://github.com/python/mypy/issues/7642
346347
# error: Argument 1 to "_get_tol_from_less_precise" has incompatible
@@ -818,7 +819,7 @@ def assert_extension_array_equal(
818819
"is deprecated and will be removed in a future version. "
819820
"You can stop passing 'check_less_precise' to silence this warning.",
820821
FutureWarning,
821-
stacklevel=2,
822+
stacklevel=find_stack_level(),
822823
)
823824
rtol = atol = _get_tol_from_less_precise(check_less_precise)
824825

@@ -964,7 +965,7 @@ def assert_series_equal(
964965
"is deprecated and will be removed in a future version. "
965966
"You can stop passing 'check_less_precise' to silence this warning.",
966967
FutureWarning,
967-
stacklevel=2,
968+
stacklevel=find_stack_level(),
968969
)
969970
rtol = atol = _get_tol_from_less_precise(check_less_precise)
970971

@@ -1247,7 +1248,7 @@ def assert_frame_equal(
12471248
"is deprecated and will be removed in a future version. "
12481249
"You can stop passing 'check_less_precise' to silence this warning.",
12491250
FutureWarning,
1250-
stacklevel=2,
1251+
stacklevel=find_stack_level(),
12511252
)
12521253
rtol = atol = _get_tol_from_less_precise(check_less_precise)
12531254

pandas/io/common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
import_lzma,
5050
)
5151
from pandas.compat._optional import import_optional_dependency
52+
from pandas.util._exceptions import find_stack_level
5253

5354
from pandas.core.dtypes.common import is_file_like
5455

@@ -270,7 +271,7 @@ def _get_filepath_or_buffer(
270271
warnings.warn(
271272
"compression has no effect when passing a non-binary object as input.",
272273
RuntimeWarning,
273-
stacklevel=2,
274+
stacklevel=find_stack_level(),
274275
)
275276
compression_method = None
276277

pandas/io/date_converters.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import numpy as np
55

66
from pandas._libs.tslibs import parsing
7+
from pandas.util._exceptions import find_stack_level
78

89

910
def parse_date_time(date_col, time_col):
@@ -18,7 +19,7 @@ def parse_date_time(date_col, time_col):
1819
Use pd.to_datetime(date_col + " " + time_col).to_pydatetime() instead to get a Numpy array.
1920
""", # noqa: E501
2021
FutureWarning,
21-
stacklevel=2,
22+
stacklevel=find_stack_level(),
2223
)
2324
date_col = _maybe_cast(date_col)
2425
time_col = _maybe_cast(time_col)
@@ -38,7 +39,7 @@ def parse_date_fields(year_col, month_col, day_col):
3839
np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array.
3940
""", # noqa: E501
4041
FutureWarning,
41-
stacklevel=2,
42+
stacklevel=find_stack_level(),
4243
)
4344

4445
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_
6364
np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array.
6465
""", # noqa: E501
6566
FutureWarning,
66-
stacklevel=2,
67+
stacklevel=find_stack_level(),
6768
)
6869

6970
year_col = _maybe_cast(year_col)
@@ -89,7 +90,7 @@ def generic_parser(parse_func, *cols):
8990
Use pd.to_datetime instead.
9091
""",
9192
FutureWarning,
92-
stacklevel=2,
93+
stacklevel=find_stack_level(),
9394
)
9495

9596
N = _check_columns(cols)

pandas/io/excel/_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -833,7 +833,7 @@ def __new__(
833833
warnings.warn(
834834
"Use of **kwargs is deprecated, use engine_kwargs instead.",
835835
FutureWarning,
836-
stacklevel=2,
836+
stacklevel=find_stack_level(),
837837
)
838838

839839
# only switch class if generic(ExcelWriter)
@@ -868,7 +868,7 @@ def __new__(
868868
"deprecated and will also raise a warning, it can "
869869
"be globally set and the warning suppressed.",
870870
FutureWarning,
871-
stacklevel=4,
871+
stacklevel=find_stack_level(),
872872
)
873873

874874
cls = get_writer(engine)

pandas/io/parsers/base_parser.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
ParserError,
3333
ParserWarning,
3434
)
35+
from pandas.util._exceptions import find_stack_level
3536

3637
from pandas.core.dtypes.cast import astype_nansafe
3738
from pandas.core.dtypes.common import (
@@ -558,7 +559,7 @@ def _convert_to_ndarrays(
558559
f"for column {c} - only the converter will be used."
559560
),
560561
ParserWarning,
561-
stacklevel=7,
562+
stacklevel=find_stack_level(),
562563
)
563564

564565
try:
@@ -830,7 +831,7 @@ def _check_data_length(self, columns: list[str], data: list[ArrayLike]) -> None:
830831
"Length of header or names does not match length of data. This leads "
831832
"to a loss of data with index_col=False.",
832833
ParserWarning,
833-
stacklevel=6,
834+
stacklevel=find_stack_level(),
834835
)
835836

836837
def _evaluate_usecols(self, usecols, names):

pandas/io/parsers/c_parser_wrapper.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
FilePathOrBuffer,
1111
)
1212
from pandas.errors import DtypeWarning
13+
from pandas.util._exceptions import find_stack_level
1314

1415
from pandas.core.dtypes.common import (
1516
is_categorical_dtype,
@@ -387,7 +388,7 @@ def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict:
387388
f"Specify dtype option on import or set low_memory=False."
388389
]
389390
)
390-
warnings.warn(warning_message, DtypeWarning, stacklevel=8)
391+
warnings.warn(warning_message, DtypeWarning, stacklevel=find_stack_level())
391392
return result
392393

393394

pandas/io/parsers/python_parser.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
EmptyDataError,
2525
ParserError,
2626
)
27+
from pandas.util._exceptions import find_stack_level
2728

2829
from pandas.core.dtypes.common import is_integer
2930
from pandas.core.dtypes.inference import is_dict_like
@@ -555,7 +556,7 @@ def _handle_usecols(
555556
"Defining usecols with out of bounds indices is deprecated "
556557
"and will raise a ParserError in a future version.",
557558
FutureWarning,
558-
stacklevel=8,
559+
stacklevel=find_stack_level(),
559560
)
560561
col_indices = self.usecols
561562

pandas/io/parsers/readers.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1041,7 +1041,7 @@ def _clean_options(self, options, engine):
10411041
"engine='python'."
10421042
),
10431043
ParserWarning,
1044-
stacklevel=5,
1044+
stacklevel=find_stack_level(),
10451045
)
10461046

10471047
index_col = options["index_col"]
@@ -1573,7 +1573,9 @@ def _merge_with_dialect_properties(
15731573
conflict_msgs.append(msg)
15741574

15751575
if conflict_msgs:
1576-
warnings.warn("\n\n".join(conflict_msgs), ParserWarning, stacklevel=2)
1576+
warnings.warn(
1577+
"\n\n".join(conflict_msgs), ParserWarning, stacklevel=find_stack_level()
1578+
)
15771579
kwds[param] = dialect_val
15781580
return kwds
15791581

pandas/io/pytables.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
from pandas.compat.pickle_compat import patch_pickle
4646
from pandas.errors import PerformanceWarning
4747
from pandas.util._decorators import cache_readonly
48+
from pandas.util._exceptions import find_stack_level
4849

4950
from pandas.core.dtypes.common import (
5051
ensure_object,
@@ -2190,7 +2191,9 @@ def update_info(self, info):
21902191
# frequency/name just warn
21912192
if key in ["freq", "index_name"]:
21922193
ws = attribute_conflict_doc % (key, existing_value, value)
2193-
warnings.warn(ws, AttributeConflictWarning, stacklevel=6)
2194+
warnings.warn(
2195+
ws, AttributeConflictWarning, stacklevel=find_stack_level()
2196+
)
21942197

21952198
# reset
21962199
idx[key] = None
@@ -3080,7 +3083,7 @@ def write_array(
30803083
pass
30813084
else:
30823085
ws = performance_doc % (inferred_type, key, items)
3083-
warnings.warn(ws, PerformanceWarning, stacklevel=7)
3086+
warnings.warn(ws, PerformanceWarning, stacklevel=find_stack_level())
30843087

30853088
vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom())
30863089
vlarr.append(value)

pandas/io/sql.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from pandas._typing import DtypeArg
2929
from pandas.compat._optional import import_optional_dependency
3030
from pandas.errors import AbstractMethodError
31+
from pandas.util._exceptions import find_stack_level
3132

3233
from pandas.core.dtypes.common import (
3334
is_datetime64tz_dtype,
@@ -1159,7 +1160,7 @@ def _sqlalchemy_type(self, col):
11591160
"the 'timedelta' type is not supported, and will be "
11601161
"written as integer values (ns frequency) to the database.",
11611162
UserWarning,
1162-
stacklevel=8,
1163+
stacklevel=find_stack_level(),
11631164
)
11641165
return BigInteger
11651166
elif col_type == "floating":
@@ -1886,7 +1887,7 @@ def _create_table_setup(self):
18861887
pat = re.compile(r"\s+")
18871888
column_names = [col_name for col_name, _, _ in column_names_and_types]
18881889
if any(map(pat.search, column_names)):
1889-
warnings.warn(_SAFE_NAMES_WARNING, stacklevel=6)
1890+
warnings.warn(_SAFE_NAMES_WARNING, stacklevel=find_stack_level())
18901891

18911892
escape = _get_valid_sqlite_name
18921893

@@ -1948,7 +1949,7 @@ def _sql_type_name(self, col):
19481949
"the 'timedelta' type is not supported, and will be "
19491950
"written as integer values (ns frequency) to the database.",
19501951
UserWarning,
1951-
stacklevel=8,
1952+
stacklevel=find_stack_level(),
19521953
)
19531954
col_type = "integer"
19541955

pandas/plotting/_matplotlib/tools.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import matplotlib.ticker as ticker
1414
import numpy as np
1515

16+
from pandas.util._exceptions import find_stack_level
17+
1618
from pandas.core.dtypes.common import is_list_like
1719
from pandas.core.dtypes.generic import (
1820
ABCDataFrame,
@@ -233,7 +235,7 @@ def create_subplots(
233235
"When passing multiple axes, sharex and sharey "
234236
"are ignored. These settings must be specified when creating axes.",
235237
UserWarning,
236-
stacklevel=4,
238+
stacklevel=find_stack_level(),
237239
)
238240
if ax.size == naxes:
239241
fig = ax.flat[0].get_figure()
@@ -256,7 +258,7 @@ def create_subplots(
256258
"To output multiple subplots, the figure containing "
257259
"the passed axes is being cleared.",
258260
UserWarning,
259-
stacklevel=4,
261+
stacklevel=find_stack_level(),
260262
)
261263
fig.clear()
262264

pandas/tseries/frequencies.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from pandas._libs.tslibs.parsing import get_rule_month
3030
from pandas._typing import npt
3131
from pandas.util._decorators import cache_readonly
32+
from pandas.util._exceptions import find_stack_level
3233

3334
from pandas.core.dtypes.common import (
3435
is_datetime64_dtype,
@@ -116,7 +117,7 @@ def get_offset(name: str) -> DateOffset:
116117
"get_offset is deprecated and will be removed in a future version, "
117118
"use to_offset instead.",
118119
FutureWarning,
119-
stacklevel=2,
120+
stacklevel=find_stack_level(),
120121
)
121122
return _get_offset(name)
122123

pandas/util/_validators.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
import numpy as np
1414

15+
from pandas.util._exceptions import find_stack_level
16+
1517
from pandas.core.dtypes.common import (
1618
is_bool,
1719
is_integer,
@@ -339,7 +341,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
339341
"positional arguments for 'index' or 'columns' will raise "
340342
"a 'TypeError'."
341343
)
342-
warnings.warn(msg, FutureWarning, stacklevel=4)
344+
warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())
343345
out[data._get_axis_name(0)] = args[0]
344346
out[data._get_axis_name(1)] = args[1]
345347
else:

pandas/util/testing.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import warnings
22

3+
from pandas.util._exceptions import find_stack_level
4+
35
from pandas._testing import * # noqa
46

57
warnings.warn(
@@ -8,5 +10,5 @@
810
"public API at pandas.testing instead."
911
),
1012
FutureWarning,
11-
stacklevel=2,
13+
stacklevel=find_stack_level(),
1214
)

0 commit comments

Comments
 (0)