Skip to content

Commit

Permalink
Merge pull request #10676 from jorisvandenbossche/stacklevel
Browse files Browse the repository at this point in the history
DEPR: add stacklevel to FutureWarnings (GH9584)
  • Loading branch information
jorisvandenbossche committed Sep 4, 2015
2 parents 4b9606b + 2c2d4e7 commit aa40dd0
Show file tree
Hide file tree
Showing 34 changed files with 138 additions and 111 deletions.
3 changes: 2 additions & 1 deletion pandas/computation/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def _align_core(terms):
'than an order of magnitude on term {1!r}, '
'by more than {2:.4g}; performance may '
'suffer'.format(axis, terms[i].name, ordm),
category=pd.io.common.PerformanceWarning)
category=pd.io.common.PerformanceWarning,
stacklevel=6)

if transpose:
f = partial(ti.reindex, index=reindexer, copy=False)
Expand Down
2 changes: 1 addition & 1 deletion pandas/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ def parse_back_compat(self, w, op=None, value=None):
w, op, value = w
warnings.warn("passing a tuple into Expr is deprecated, "
"pass the where as a single string",
DeprecationWarning)
DeprecationWarning, stacklevel=10)

if op is not None:
if not isinstance(w, string_types):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None):
note: an array of Periods will ignore sort as it returns an always sorted PeriodIndex
"""
if order is not None:
warn("order is deprecated."
"See https://github.com/pydata/pandas/issues/6926", FutureWarning)
msg = "order is deprecated. See https://github.com/pydata/pandas/issues/6926"
warn(msg, FutureWarning, stacklevel=2)

from pandas.core.index import Index
from pandas.core.series import Series
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def _get_labels(self):
Deprecated, use .codes!
"""
warn("'labels' is deprecated. Use 'codes' instead", FutureWarning, stacklevel=3)
warn("'labels' is deprecated. Use 'codes' instead", FutureWarning, stacklevel=2)
return self.codes

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

# categories must be unique

Expand Down Expand Up @@ -491,12 +491,12 @@ def _get_categories(self):

def _set_levels(self, levels):
""" set new levels (deprecated, use "categories") """
warn("Assigning to 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=3)
warn("Assigning to 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=2)
self.categories = levels

def _get_levels(self):
""" Gets the levels (deprecated, use "categories") """
warn("Accessing 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=3)
warn("Accessing 'levels' is deprecated, use 'categories'", FutureWarning, stacklevel=2)
return self.categories

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

def set_ordered(self, value, inplace=False):
Expand Down Expand Up @@ -1200,7 +1200,7 @@ def order(self, inplace=False, ascending=True, na_position='last'):
Category.sort
"""
warn("order is deprecated, use sort_values(...)",
FutureWarning, stacklevel=3)
FutureWarning, stacklevel=2)
return self.sort_values(inplace=inplace, ascending=ascending, na_position=na_position)

def sort(self, inplace=True, ascending=True, na_position='last'):
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1468,7 +1468,7 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,

if colSpace is not None: # pragma: no cover
warnings.warn("colSpace is deprecated, use col_space",
FutureWarning)
FutureWarning, stacklevel=2)
col_space = colSpace

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

if colSpace is not None: # pragma: no cover
warnings.warn("colSpace is deprecated, use col_space",
FutureWarning)
FutureWarning, stacklevel=2)
col_space = colSpace

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

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

@deprecate_kwarg('take_last', 'keep', mapping={True: 'last', False: 'first'})
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset')
@deprecate_kwarg(old_arg_name='cols', new_arg_name='subset', stacklevel=3)
def duplicated(self, subset=None, keep='first'):
"""
Return boolean Series denoting duplicate rows, optionally only
Expand Down
18 changes: 9 additions & 9 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ def iterkv(self, *args, **kwargs):
"iteritems alias used to get around 2to3. Deprecated"
warnings.warn("iterkv is deprecated and will be removed in a future "
"release, use ``iteritems`` instead.",
FutureWarning)
FutureWarning, stacklevel=2)
return self.iteritems(*args, **kwargs)

def __len__(self):
Expand Down Expand Up @@ -3376,11 +3376,11 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
For frequencies that evenly subdivide 1 day, the "origin" of the
aggregated intervals. For example, for '5min' frequency, base could
range from 0 through 4. Defaults to 0
Examples
--------
Start by creating a series with 9 one minute timestamps.
>>> index = pd.date_range('1/1/2000', periods=9, freq='T')
Expand Down Expand Up @@ -3409,11 +3409,11 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
Downsample the series into 3 minute bins as above, but label each
bin using the right edge instead of the left. Please note that the
value in the bucket used as the label is not included in the bucket,
which it labels. For example, in the original series the
which it labels. For example, in the original series the
bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed
value in the resampled bucket with the label``2000-01-01 00:03:00``
value in the resampled bucket with the label``2000-01-01 00:03:00``
does not include 3 (if it did, the summed value would be 6, not 3).
To include this value close the right side of the bin interval as
To include this value close the right side of the bin interval as
illustrated in the example below this one.
>>> series.resample('3T', how='sum', label='right')
Expand All @@ -3424,7 +3424,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
Downsample the series into 3 minute bins as above, but close the right
side of the bin interval.
>>> series.resample('3T', how='sum', label='right', closed='right')
2000-01-01 00:00:00 0
2000-01-01 00:03:00 6
Expand Down Expand Up @@ -3453,7 +3453,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
2000-01-01 00:02:00 2
Freq: 30S, dtype: int64
Upsample the series into 30 second bins and fill the
Upsample the series into 30 second bins and fill the
``NaN`` values using the ``bfill`` method.
>>> series.resample('30S', fill_method='bfill')[0:5]
Expand All @@ -3468,7 +3468,7 @@ def resample(self, rule, how=None, axis=0, fill_method=None,
>>> def custom_resampler(array_like):
... return np.sum(array_like)+5
>>> series.resample('3T', how=custom_resampler)
2000-01-01 00:00:00 8
2000-01-01 00:03:00 17
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,14 +842,14 @@ def to_int():
elif is_float(key):
key = to_int()
warnings.warn("scalar indexers for index type {0} should be integers and not floating point".format(
type(self).__name__),FutureWarning, stacklevel=8)
type(self).__name__), FutureWarning, stacklevel=5)
return key
return self._invalid_indexer('label', key)

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

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

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

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

__iadd__ = __add__

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

def __and__(self, other):
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):

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

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

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

# If not as_indexer and regex.groups == 0, this returns empty lists
# and is basically useless, so we will not warn.
Expand Down
5 changes: 3 additions & 2 deletions pandas/io/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ def __init__(self, symbol, data_source=None):
self.symbol = symbol.upper()
if data_source is None:
warnings.warn("Options(symbol) is deprecated, use Options(symbol,"
" data_source) instead", FutureWarning)
" data_source) instead", FutureWarning, stacklevel=2)
data_source = "yahoo"
if data_source != "yahoo":
raise NotImplementedError("currently only yahoo supported")
Expand Down Expand Up @@ -1072,7 +1072,8 @@ def get_forward_data(self, months, call=True, put=False, near=False,
Note: Format of returned data frame is dependent on Yahoo and may change.
"""
warnings.warn("get_forward_data() is deprecated", FutureWarning)
warnings.warn("get_forward_data() is deprecated", FutureWarning,
stacklevel=2)
end_date = dt.date.today() + MonthEnd(months)
dates = (date for date in self.expiry_dates if date <= end_date.date())
data = self._get_data_in_date_range(dates, call=call, put=put)
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ def _clean_options(self, options, engine):
warnings.warn(("Falling back to the 'python' engine because"
" {0}; you can avoid this warning by specifying"
" engine='python'.").format(fallback_reason),
ParserWarning)
ParserWarning, stacklevel=5)

index_col = options['index_col']
names = options['names']
Expand Down
6 changes: 3 additions & 3 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1596,7 +1596,7 @@ 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)
warnings.warn(ws, AttributeConflictWarning, stacklevel=6)

# reset
idx[key] = None
Expand Down Expand Up @@ -2581,7 +2581,7 @@ def write_array(self, key, value, items=None):
except:
pass
ws = performance_doc % (inferred_type, key, items)
warnings.warn(ws, PerformanceWarning)
warnings.warn(ws, PerformanceWarning, stacklevel=7)

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

else:
warnings.warn(duplicate_doc, DuplicateWarning)
warnings.warn(duplicate_doc, DuplicateWarning, stacklevel=5)

# reconstruct
long_index = MultiIndex.from_arrays(
Expand Down
Loading

0 comments on commit aa40dd0

Please sign in to comment.