Skip to content

Commit 866b281

Browse files
authored
ENH: Move SettingWithCopyWarning to error/__init__.py per GH27656 (#47198)
* ENH: Move SettingWithCopyWarning to error/__init__.py per GH27656 * ENH: change links to sphinx ref
1 parent aae9234 commit 866b281

File tree

8 files changed

+50
-28
lines changed

8 files changed

+50
-28
lines changed

doc/source/reference/testing.rst

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Exceptions and warnings
4242
errors.ParserWarning
4343
errors.PerformanceWarning
4444
errors.SettingWithCopyError
45+
errors.SettingWithCopyWarning
4546
errors.SpecificationError
4647
errors.UnsortedIndexError
4748
errors.UnsupportedFunctionCall

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ Other enhancements
151151
- A :class:`errors.PerformanceWarning` is now thrown when using ``string[pyarrow]`` dtype with methods that don't dispatch to ``pyarrow.compute`` methods (:issue:`42613`)
152152
- Added ``numeric_only`` argument to :meth:`Resampler.sum`, :meth:`Resampler.prod`, :meth:`Resampler.min`, :meth:`Resampler.max`, :meth:`Resampler.first`, and :meth:`Resampler.last` (:issue:`46442`)
153153
- ``times`` argument in :class:`.ExponentialMovingWindow` now accepts ``np.timedelta64`` (:issue:`47003`)
154-
- :class:`DataError`, :class:`SpecificationError`, and :class:`SettingWithCopyError` are now exposed in ``pandas.errors`` (:issue:`27656`)
154+
- :class:`DataError`, :class:`SpecificationError`, :class:`SettingWithCopyError`, and :class:`SettingWithCopyWarning` are now exposed in ``pandas.errors`` (:issue:`27656`)
155155

156156
.. ---------------------------------------------------------------------------
157157
.. _whatsnew_150.notable_bug_fixes:

pandas/core/common.py

-4
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,6 @@
5858
from pandas import Index
5959

6060

61-
class SettingWithCopyWarning(Warning):
62-
pass
63-
64-
6561
def flatten(line):
6662
"""
6763
Flatten an arbitrarily nested sequence.

pandas/core/generic.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
AbstractMethodError,
7171
InvalidIndexError,
7272
SettingWithCopyError,
73+
SettingWithCopyWarning,
7374
)
7475
from pandas.util._decorators import (
7576
deprecate_kwarg,
@@ -3952,7 +3953,7 @@ def _check_setitem_copy(self, t="setting", force=False):
39523953
if value == "raise":
39533954
raise SettingWithCopyError(t)
39543955
elif value == "warn":
3955-
warnings.warn(t, com.SettingWithCopyWarning, stacklevel=find_stack_level())
3956+
warnings.warn(t, SettingWithCopyWarning, stacklevel=find_stack_level())
39563957

39573958
def __delitem__(self, key) -> None:
39583959
"""

pandas/errors/__init__.py

+24-4
Original file line numberDiff line numberDiff line change
@@ -275,11 +275,11 @@ class SettingWithCopyError(ValueError):
275275
the mode.chained_assignment is set to 'raise.' This can happen unintentionally
276276
when chained indexing.
277277
278-
For more information, see 'Evaluation order matters' on
279-
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
278+
For more information on eveluation order,
279+
see :ref:`the user guide<indexing.evaluation_order>`.
280280
281-
For more information, see 'Indexing view versus copy' on
282-
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
281+
For more information on view vs. copy,
282+
see :ref:`the user guide<indexing.view_versus_copy>`.
283283
284284
Examples
285285
--------
@@ -288,3 +288,23 @@ class SettingWithCopyError(ValueError):
288288
>>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
289289
... # SettingWithCopyError: A value is trying to be set on a copy of a...
290290
"""
291+
292+
293+
class SettingWithCopyWarning(Warning):
294+
"""
295+
Warning is raised when trying to set on a copied slice from a dataframe and
296+
the mode.chained_assignment is set to 'warn.' 'Warn' is the default option.
297+
This can happen unintentionally when chained indexing.
298+
299+
For more information on eveluation order,
300+
see :ref:`the user guide<indexing.evaluation_order>`.
301+
302+
For more information on view vs. copy,
303+
see :ref:`the user guide<indexing.view_versus_copy>`.
304+
305+
Examples
306+
--------
307+
>>> df = pd.DataFrame({'A': [1, 1, 1, 2, 2]}, columns=['A'])
308+
>>> df.loc[0:3]['A'] = 'a' # doctest: +SKIP
309+
... # SettingWithCopyWarning: A value is trying to be set on a copy of a...
310+
"""

pandas/tests/copy_view/test_indexing.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import numpy as np
22
import pytest
33

4+
from pandas.errors import SettingWithCopyWarning
5+
46
import pandas as pd
57
from pandas import (
68
DataFrame,
79
Series,
810
)
911
import pandas._testing as tm
10-
import pandas.core.common as com
1112
from pandas.tests.copy_view.util import get_array
1213

1314
# -----------------------------------------------------------------------------
@@ -31,7 +32,7 @@ def test_subset_column_selection(using_copy_on_write):
3132
assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
3233
# INFO this no longer raise warning since pandas 1.4
3334
# with pd.option_context("chained_assignment", "warn"):
34-
# with tm.assert_produces_warning(com.SettingWithCopyWarning):
35+
# with tm.assert_produces_warning(SettingWithCopyWarning):
3536
subset.iloc[0, 0] = 0
3637

3738
assert not np.shares_memory(get_array(subset, "a"), get_array(df, "a"))
@@ -80,7 +81,7 @@ def test_subset_row_slice(using_copy_on_write):
8081
else:
8182
# INFO this no longer raise warning since pandas 1.4
8283
# with pd.option_context("chained_assignment", "warn"):
83-
# with tm.assert_produces_warning(com.SettingWithCopyWarning):
84+
# with tm.assert_produces_warning(SettingWithCopyWarning):
8485
subset.iloc[0, 0] = 0
8586

8687
subset._mgr._verify_integrity()
@@ -119,7 +120,7 @@ def test_subset_column_slice(using_copy_on_write, using_array_manager, dtype):
119120

120121
else:
121122
# we only get a warning in case of a single block
122-
warn = com.SettingWithCopyWarning if single_block else None
123+
warn = SettingWithCopyWarning if single_block else None
123124
with pd.option_context("chained_assignment", "warn"):
124125
with tm.assert_produces_warning(warn):
125126
subset.iloc[0, 0] = 0
@@ -252,7 +253,7 @@ def test_subset_set_with_row_indexer(indexer_si, indexer, using_copy_on_write):
252253
indexer_si(subset)[indexer] = 0
253254
else:
254255
# INFO iloc no longer raises warning since pandas 1.4
255-
warn = com.SettingWithCopyWarning if indexer_si is tm.setitem else None
256+
warn = SettingWithCopyWarning if indexer_si is tm.setitem else None
256257
with pd.option_context("chained_assignment", "warn"):
257258
with tm.assert_produces_warning(warn):
258259
indexer_si(subset)[indexer] = 0
@@ -282,7 +283,7 @@ def test_subset_set_with_mask(using_copy_on_write):
282283
subset[mask] = 0
283284
else:
284285
with pd.option_context("chained_assignment", "warn"):
285-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
286+
with tm.assert_produces_warning(SettingWithCopyWarning):
286287
subset[mask] = 0
287288

288289
expected = DataFrame(
@@ -309,7 +310,7 @@ def test_subset_set_column(using_copy_on_write):
309310
subset["a"] = np.array([10, 11], dtype="int64")
310311
else:
311312
with pd.option_context("chained_assignment", "warn"):
312-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
313+
with tm.assert_produces_warning(SettingWithCopyWarning):
313314
subset["a"] = np.array([10, 11], dtype="int64")
314315

315316
subset._mgr._verify_integrity()
@@ -340,7 +341,7 @@ def test_subset_set_column_with_loc(using_copy_on_write, using_array_manager, dt
340341
# warnings and only assert the SettingWithCopyWarning
341342
raise_on_extra_warnings = False if using_array_manager else True
342343
with tm.assert_produces_warning(
343-
com.SettingWithCopyWarning,
344+
SettingWithCopyWarning,
344345
raise_on_extra_warnings=raise_on_extra_warnings,
345346
):
346347
subset.loc[:, "a"] = np.array([10, 11], dtype="int64")
@@ -377,7 +378,7 @@ def test_subset_set_column_with_loc2(using_copy_on_write, using_array_manager):
377378
# warnings and only assert the SettingWithCopyWarning
378379
raise_on_extra_warnings = False if using_array_manager else True
379380
with tm.assert_produces_warning(
380-
com.SettingWithCopyWarning,
381+
SettingWithCopyWarning,
381382
raise_on_extra_warnings=raise_on_extra_warnings,
382383
):
383384
subset.loc[:, "a"] = 0
@@ -410,7 +411,7 @@ def test_subset_set_columns(using_copy_on_write, dtype):
410411
subset[["a", "c"]] = 0
411412
else:
412413
with pd.option_context("chained_assignment", "warn"):
413-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
414+
with tm.assert_produces_warning(SettingWithCopyWarning):
414415
subset[["a", "c"]] = 0
415416

416417
subset._mgr._verify_integrity()
@@ -443,7 +444,7 @@ def test_subset_set_with_column_indexer(
443444
# The (i)loc[:, col] inplace deprecation gets triggered here, ignore those
444445
# warnings and only assert the SettingWithCopyWarning
445446
with tm.assert_produces_warning(
446-
com.SettingWithCopyWarning, raise_on_extra_warnings=False
447+
SettingWithCopyWarning, raise_on_extra_warnings=False
447448
):
448449
subset.loc[:, indexer] = 0
449450

@@ -580,7 +581,7 @@ def test_column_as_series(using_copy_on_write, using_array_manager):
580581
s[0] = 0
581582
else:
582583
with pd.option_context("chained_assignment", "warn"):
583-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
584+
with tm.assert_produces_warning(SettingWithCopyWarning):
584585
s[0] = 0
585586

586587
expected = Series([0, 2, 3], name="a")
@@ -607,7 +608,7 @@ def test_column_as_series_set_with_upcast(using_copy_on_write, using_array_manag
607608
s[0] = "foo"
608609
else:
609610
with pd.option_context("chained_assignment", "warn"):
610-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
611+
with tm.assert_produces_warning(SettingWithCopyWarning):
611612
s[0] = "foo"
612613

613614
expected = Series(["foo", 2, 3], dtype=object, name="a")

pandas/tests/indexing/test_chaining_and_caching.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
import numpy as np
44
import pytest
55

6-
from pandas.errors import SettingWithCopyError
6+
from pandas.errors import (
7+
SettingWithCopyError,
8+
SettingWithCopyWarning,
9+
)
710
import pandas.util._test_decorators as td
811

912
import pandas as pd
@@ -15,7 +18,6 @@
1518
option_context,
1619
)
1720
import pandas._testing as tm
18-
import pandas.core.common as com
1921

2022
msg = "A value is trying to be set on a copy of a slice from a DataFrame"
2123

@@ -415,7 +417,7 @@ def test_setting_with_copy_bug_no_warning(self):
415417
def test_detect_chained_assignment_warnings_errors(self):
416418
df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]})
417419
with option_context("chained_assignment", "warn"):
418-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
420+
with tm.assert_produces_warning(SettingWithCopyWarning):
419421
df.loc[0]["A"] = 111
420422

421423
with option_context("chained_assignment", "raise"):
@@ -427,7 +429,7 @@ def test_detect_chained_assignment_warnings_filter_and_dupe_cols(self):
427429
with option_context("chained_assignment", "warn"):
428430
df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, -9]], columns=["a", "a", "c"])
429431

430-
with tm.assert_produces_warning(com.SettingWithCopyWarning):
432+
with tm.assert_produces_warning(SettingWithCopyWarning):
431433
df.c.loc[df.c > 0] = None
432434

433435
expected = DataFrame(
@@ -441,7 +443,7 @@ def test_detect_chained_assignment_warning_stacklevel(self, rhs):
441443
df = DataFrame(np.arange(25).reshape(5, 5))
442444
chained = df.loc[:3]
443445
with option_context("chained_assignment", "warn"):
444-
with tm.assert_produces_warning(com.SettingWithCopyWarning) as t:
446+
with tm.assert_produces_warning(SettingWithCopyWarning) as t:
445447
chained[2] = rhs
446448
assert t[0].filename == __file__
447449

pandas/tests/test_errors.py

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"DataError",
2323
"SpecificationError",
2424
"SettingWithCopyError",
25+
"SettingWithCopyWarning",
2526
],
2627
)
2728
def test_exception_importable(exc):

0 commit comments

Comments
 (0)