diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8a05f7be0cc2e..8b82021375a28 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3745,7 +3745,7 @@ def _set_item_mgr(self, key, value: ArrayLike) -> None: # try to set first as we want an invalid # value exception to occur first if len(self): - self._check_setitem_copy(stacklevel=5) + self._check_setitem_copy() def _iset_item(self, loc: int, value) -> None: arraylike = self._sanitize_column(value) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7865cdb0455b2..bf79e58077179 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -67,6 +67,7 @@ doc, rewrite_axis_style_signature, ) +from pandas.util._exceptions import find_stack_level from pandas.util._validators import ( validate_ascending, validate_bool_kwarg, @@ -3506,7 +3507,7 @@ def _maybe_update_cacher( """ if verify_is_copy: - self._check_setitem_copy(stacklevel=5, t="referent") + self._check_setitem_copy(t="referent") if clear: self._clear_item_cache() @@ -3853,26 +3854,21 @@ def _check_is_chained_assignment_possible(self) -> bool_t: setting. """ if self._is_copy: - self._check_setitem_copy(stacklevel=4, t="referent") + self._check_setitem_copy(t="referent") return False @final - def _check_setitem_copy(self, stacklevel=4, t="setting", force=False): + def _check_setitem_copy(self, t="setting", force=False): """ Parameters ---------- - stacklevel : int, default 4 - the level to show of the stack when the error is output t : str, the type of setting error force : bool, default False If True, then force showing an error. validate if we are doing a setitem on a chained copy. - If you call this function, be sure to set the stacklevel such that the - user will see the error *at the level of setting* - It is technically possible to figure out that we are setting on a copy even WITH a multi-dtyped pandas object. In other words, some blocks may be views while other are not. Currently _is_view will ALWAYS @@ -3931,7 +3927,7 @@ def _check_setitem_copy(self, stacklevel=4, t="setting", force=False): if value == "raise": raise com.SettingWithCopyError(t) elif value == "warn": - warnings.warn(t, com.SettingWithCopyWarning, stacklevel=stacklevel) + warnings.warn(t, com.SettingWithCopyWarning, stacklevel=find_stack_level()) def __delitem__(self, key) -> None: """ diff --git a/pandas/core/series.py b/pandas/core/series.py index e61ce8e74629b..e1b8fc1287cba 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1214,7 +1214,7 @@ def _check_is_chained_assignment_possible(self) -> bool: if self._is_view and self._is_cached: ref = self._get_cacher() if ref is not None and ref._is_mixed_type: - self._check_setitem_copy(stacklevel=4, t="referent", force=True) + self._check_setitem_copy(t="referent", force=True) return True return super()._check_is_chained_assignment_possible()