Skip to content

Commit aa40dd0

Browse files
Merge pull request #10676 from jorisvandenbossche/stacklevel
DEPR: add stacklevel to FutureWarnings (GH9584)
2 parents 4b9606b + 2c2d4e7 commit aa40dd0

34 files changed

+138
-111
lines changed

pandas/computation/align.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ def _align_core(terms):
101101
'than an order of magnitude on term {1!r}, '
102102
'by more than {2:.4g}; performance may '
103103
'suffer'.format(axis, terms[i].name, ordm),
104-
category=pd.io.common.PerformanceWarning)
104+
category=pd.io.common.PerformanceWarning,
105+
stacklevel=6)
105106

106107
if transpose:
107108
f = partial(ti.reindex, index=reindexer, copy=False)

pandas/computation/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ def parse_back_compat(self, w, op=None, value=None):
535535
w, op, value = w
536536
warnings.warn("passing a tuple into Expr is deprecated, "
537537
"pass the where as a single string",
538-
DeprecationWarning)
538+
DeprecationWarning, stacklevel=10)
539539

540540
if op is not None:
541541
if not isinstance(w, string_types):

pandas/core/algorithms.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,8 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None):
125125
note: an array of Periods will ignore sort as it returns an always sorted PeriodIndex
126126
"""
127127
if order is not None:
128-
warn("order is deprecated."
129-
"See https://github.com/pydata/pandas/issues/6926", FutureWarning)
128+
msg = "order is deprecated. See https://github.com/pydata/pandas/issues/6926"
129+
warn(msg, FutureWarning, stacklevel=2)
130130

131131
from pandas.core.index import Index
132132
from pandas.core.series import Series

pandas/core/categorical.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ def _get_labels(self):
414414
415415
Deprecated, use .codes!
416416
"""
417-
warn("'labels' is deprecated. Use 'codes' instead", FutureWarning, stacklevel=3)
417+
warn("'labels' is deprecated. Use 'codes' instead", FutureWarning, stacklevel=2)
418418
return self.codes
419419

420420
labels = property(fget=_get_labels, fset=_set_codes)
@@ -456,7 +456,7 @@ def _validate_categories(cls, categories, fastpath=False):
456456
# NaNs in cats deprecated in 0.17, remove in 0.18 or 0.19 GH 10748
457457
msg = ('\nSetting NaNs in `categories` is deprecated and '
458458
'will be removed in a future version of pandas.')
459-
warn(msg, FutureWarning, stacklevel=5)
459+
warn(msg, FutureWarning, stacklevel=3)
460460

461461
# categories must be unique
462462

@@ -491,12 +491,12 @@ def _get_categories(self):
491491

492492
def _set_levels(self, levels):
493493
""" set new levels (deprecated, use "categories") """
494-
warn("Assigning to 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=3)
494+
warn("Assigning to 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=2)
495495
self.categories = levels
496496

497497
def _get_levels(self):
498498
""" Gets the levels (deprecated, use "categories") """
499-
warn("Accessing 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=3)
499+
warn("Accessing 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=2)
500500
return self.categories
501501

502502
# TODO: Remove after deprecation period in 2017/ after 0.18
@@ -507,7 +507,7 @@ def _get_levels(self):
507507
def _set_ordered(self, value):
508508
""" Sets the ordered attribute to the boolean value """
509509
warn("Setting 'ordered' directly is deprecated, use 'set_ordered'", FutureWarning,
510-
stacklevel=3)
510+
stacklevel=2)
511511
self.set_ordered(value, inplace=True)
512512

513513
def set_ordered(self, value, inplace=False):
@@ -1200,7 +1200,7 @@ def order(self, inplace=False, ascending=True, na_position='last'):
12001200
Category.sort
12011201
"""
12021202
warn("order is deprecated, use sort_values(...)",
1203-
FutureWarning, stacklevel=3)
1203+
FutureWarning, stacklevel=2)
12041204
return self.sort_values(inplace=inplace, ascending=ascending, na_position=na_position)
12051205

12061206
def sort(self, inplace=True, ascending=True, na_position='last'):

pandas/core/frame.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1468,7 +1468,7 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
14681468

14691469
if colSpace is not None: # pragma: no cover
14701470
warnings.warn("colSpace is deprecated, use col_space",
1471-
FutureWarning)
1471+
FutureWarning, stacklevel=2)
14721472
col_space = colSpace
14731473

14741474
formatter = fmt.DataFrameFormatter(self, buf=buf, columns=columns,
@@ -1517,7 +1517,7 @@ def to_latex(self, buf=None, columns=None, col_space=None, colSpace=None,
15171517

15181518
if colSpace is not None: # pragma: no cover
15191519
warnings.warn("colSpace is deprecated, use col_space",
1520-
FutureWarning)
1520+
FutureWarning, stacklevel=2)
15211521
col_space = colSpace
15221522

15231523
formatter = fmt.DataFrameFormatter(self, buf=buf, columns=columns,
@@ -2919,7 +2919,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
29192919
return result
29202920

29212921
@deprecate_kwarg('take_last', 'keep', mapping={True: 'last', False: 'first'})
2922-
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset')
2922+
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset', stacklevel=3)
29232923
def drop_duplicates(self, subset=None, keep='first', inplace=False):
29242924
"""
29252925
Return DataFrame with duplicate rows removed, optionally only
@@ -2953,7 +2953,7 @@ def drop_duplicates(self, subset=None, keep='first', inplace=False):
29532953
return self[-duplicated]
29542954

29552955
@deprecate_kwarg('take_last', 'keep', mapping={True: 'last', False: 'first'})
2956-
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset')
2956+
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset', stacklevel=3)
29572957
def duplicated(self, subset=None, keep='first'):
29582958
"""
29592959
Return boolean Series denoting duplicate rows, optionally only

pandas/core/generic.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -706,7 +706,7 @@ def iterkv(self, *args, **kwargs):
706706
"iteritems alias used to get around 2to3. Deprecated"
707707
warnings.warn("iterkv is deprecated and will be removed in a future "
708708
"release, use ``iteritems`` instead.",
709-
FutureWarning)
709+
FutureWarning, stacklevel=2)
710710
return self.iteritems(*args, **kwargs)
711711

712712
def __len__(self):
@@ -3376,11 +3376,11 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
33763376
For frequencies that evenly subdivide 1 day, the "origin" of the
33773377
aggregated intervals. For example, for '5min' frequency, base could
33783378
range from 0 through 4. Defaults to 0
3379-
3379+
33803380
33813381
Examples
33823382
--------
3383-
3383+
33843384
Start by creating a series with 9 one minute timestamps.
33853385
33863386
>>> index = pd.date_range('1/1/2000', periods=9, freq='T')
@@ -3409,11 +3409,11 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
34093409
Downsample the series into 3 minute bins as above, but label each
34103410
bin using the right edge instead of the left. Please note that the
34113411
value in the bucket used as the label is not included in the bucket,
3412-
which it labels. For example, in the original series the
3412+
which it labels. For example, in the original series the
34133413
bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
3414-
value in the resampled bucket with the label``2000-01-01 00:03:00``
3414+
value in the resampled bucket with the label``2000-01-01 00:03:00``
34153415
does not include 3 (if it did, the summed value would be 6, not 3).
3416-
To include this value close the right side of the bin interval as
3416+
To include this value close the right side of the bin interval as
34173417
illustrated in the example below this one.
34183418
34193419
>>> series.resample('3T', how='sum', label='right')
@@ -3424,7 +3424,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
34243424
34253425
Downsample the series into 3 minute bins as above, but close the right
34263426
side of the bin interval.
3427-
3427+
34283428
>>> series.resample('3T', how='sum', label='right', closed='right')
34293429
2000-01-01 00:00:00 0
34303430
2000-01-01 00:03:00 6
@@ -3453,7 +3453,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
34533453
2000-01-01 00:02:00 2
34543454
Freq: 30S, dtype: int64
34553455
3456-
Upsample the series into 30 second bins and fill the
3456+
Upsample the series into 30 second bins and fill the
34573457
``NaN`` values using the ``bfill`` method.
34583458
34593459
>>> series.resample('30S', fill_method='bfill')[0:5]
@@ -3468,7 +3468,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
34683468
34693469
>>> def custom_resampler(array_like):
34703470
... return np.sum(array_like)+5
3471-
3471+
34723472
>>> series.resample('3T', how=custom_resampler)
34733473
2000-01-01 00:00:00 8
34743474
2000-01-01 00:03:00 17

pandas/core/index.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -842,14 +842,14 @@ def to_int():
842842
elif is_float(key):
843843
key = to_int()
844844
warnings.warn("scalar indexers for index type {0} should be integers and not floating point".format(
845-
type(self).__name__),FutureWarning, stacklevel=8)
845+
type(self).__name__), FutureWarning, stacklevel=5)
846846
return key
847847
return self._invalid_indexer('label', key)
848848

849849
if is_float(key):
850850
if not self.is_floating():
851851
warnings.warn("scalar indexers for index type {0} should be integers and not floating point".format(
852-
type(self).__name__),FutureWarning, stacklevel=8)
852+
type(self).__name__), FutureWarning, stacklevel=3)
853853
return to_int()
854854

855855
return key
@@ -887,7 +887,7 @@ def f(c):
887887
# warn if it's a convertible float
888888
if v == int(v):
889889
warnings.warn("slice indexers when using iloc should be integers "
890-
"and not floating point",FutureWarning)
890+
"and not floating point", FutureWarning, stacklevel=7)
891891
return int(v)
892892

893893
self._invalid_indexer('slice {0} value'.format(c), v)
@@ -1415,22 +1415,22 @@ def argsort(self, *args, **kwargs):
14151415
def __add__(self, other):
14161416
if com.is_list_like(other):
14171417
warnings.warn("using '+' to provide set union with Indexes is deprecated, "
1418-
"use '|' or .union()", FutureWarning)
1418+
"use '|' or .union()", FutureWarning, stacklevel=2)
14191419
if isinstance(other, Index):
14201420
return self.union(other)
14211421
return Index(np.array(self) + other)
14221422

14231423
def __radd__(self, other):
14241424
if com.is_list_like(other):
14251425
warnings.warn("using '+' to provide set union with Indexes is deprecated, "
1426-
"use '|' or .union()", FutureWarning)
1426+
"use '|' or .union()", FutureWarning, stacklevel=2)
14271427
return Index(other + np.array(self))
14281428

14291429
__iadd__ = __add__
14301430

14311431
def __sub__(self, other):
14321432
warnings.warn("using '-' to provide set differences with Indexes is deprecated, "
1433-
"use .difference()",FutureWarning)
1433+
"use .difference()",FutureWarning, stacklevel=2)
14341434
return self.difference(other)
14351435

14361436
def __and__(self, other):

pandas/core/strings.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
204204

205205
if regex.groups > 0:
206206
warnings.warn("This pattern has match groups. To actually get the"
207-
" groups, use str.extract.", UserWarning)
207+
" groups, use str.extract.", UserWarning, stacklevel=3)
208208

209209
f = lambda x: bool(regex.search(x))
210210
else:
@@ -377,11 +377,12 @@ def str_match(arr, pat, case=True, flags=0, na=np.nan, as_indexer=False):
377377
# Do this first, to make sure it happens even if the re.compile
378378
# raises below.
379379
warnings.warn("In future versions of pandas, match will change to"
380-
" always return a bool indexer.", UserWarning)
380+
" always return a bool indexer.", FutureWarning,
381+
stacklevel=3)
381382

382383
if as_indexer and regex.groups > 0:
383384
warnings.warn("This pattern has match groups. To actually get the"
384-
" groups, use str.extract.", UserWarning)
385+
" groups, use str.extract.", UserWarning, stacklevel=3)
385386

386387
# If not as_indexer and regex.groups == 0, this returns empty lists
387388
# and is basically useless, so we will not warn.

pandas/io/data.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@ def __init__(self, symbol, data_source=None):
608608
self.symbol = symbol.upper()
609609
if data_source is None:
610610
warnings.warn("Options(symbol) is deprecated, use Options(symbol,"
611-
" data_source) instead", FutureWarning)
611+
" data_source) instead", FutureWarning, stacklevel=2)
612612
data_source = "yahoo"
613613
if data_source != "yahoo":
614614
raise NotImplementedError("currently only yahoo supported")
@@ -1072,7 +1072,8 @@ def get_forward_data(self, months, call=True, put=False, near=False,
10721072
Note: Format of returned data frame is dependent on Yahoo and may change.
10731073
10741074
"""
1075-
warnings.warn("get_forward_data() is deprecated", FutureWarning)
1075+
warnings.warn("get_forward_data() is deprecated", FutureWarning,
1076+
stacklevel=2)
10761077
end_date = dt.date.today() + MonthEnd(months)
10771078
dates = (date for date in self.expiry_dates if date <= end_date.date())
10781079
data = self._get_data_in_date_range(dates, call=call, put=put)

pandas/io/parsers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,7 @@ def _clean_options(self, options, engine):
647647
warnings.warn(("Falling back to the 'python' engine because"
648648
" {0}; you can avoid this warning by specifying"
649649
" engine='python'.").format(fallback_reason),
650-
ParserWarning)
650+
ParserWarning, stacklevel=5)
651651

652652
index_col = options['index_col']
653653
names = options['names']

pandas/io/pytables.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1596,7 +1596,7 @@ def update_info(self, info):
15961596
# frequency/name just warn
15971597
if key in ['freq', 'index_name']:
15981598
ws = attribute_conflict_doc % (key, existing_value, value)
1599-
warnings.warn(ws, AttributeConflictWarning)
1599+
warnings.warn(ws, AttributeConflictWarning, stacklevel=6)
16001600

16011601
# reset
16021602
idx[key] = None
@@ -2581,7 +2581,7 @@ def write_array(self, key, value, items=None):
25812581
except:
25822582
pass
25832583
ws = performance_doc % (inferred_type, key, items)
2584-
warnings.warn(ws, PerformanceWarning)
2584+
warnings.warn(ws, PerformanceWarning, stacklevel=7)
25852585

25862586
vlarr = self._handle.create_vlarray(self.group, key,
25872587
_tables().ObjectAtom())
@@ -3716,7 +3716,7 @@ def read(self, where=None, columns=None, **kwargs):
37163716
objs.append(obj)
37173717

37183718
else:
3719-
warnings.warn(duplicate_doc, DuplicateWarning)
3719+
warnings.warn(duplicate_doc, DuplicateWarning, stacklevel=5)
37203720

37213721
# reconstruct
37223722
long_index = MultiIndex.from_arrays(

0 commit comments

Comments
 (0)