Skip to content

STYLE: Add ruff check for multiple with statements #53466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions asv_bench/benchmarks/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,10 +526,11 @@ def setup(self, mode):
def time_chained_indexing(self, mode):
df = self.df
N = self.N
with warnings.catch_warnings(record=True):
with option_context("mode.chained_assignment", mode):
df2 = df[df.A > N // 2]
df2["C"] = 1.0
with warnings.catch_warnings(
record=True,
), option_context("mode.chained_assignment", mode):
df2 = df[df.A > N // 2]
df2["C"] = 1.0


class Block:
Expand Down
13 changes: 8 additions & 5 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1680,11 +1680,14 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
# result to the whole group. Compute func result
# and deal with possible broadcasting below.
# Temporarily set observed for dealing with categoricals.
with com.temp_setattr(self, "observed", True):
with com.temp_setattr(self, "as_index", True):
# GH#49834 - result needs groups in the index for
# _wrap_transform_fast_result
result = getattr(self, func)(*args, **kwargs)
with com.temp_setattr(
self,
"observed",
True,
), com.temp_setattr(self, "as_index", True):
# GH#49834 - result needs groups in the index for
# _wrap_transform_fast_result
result = getattr(self, func)(*args, **kwargs)

return self._wrap_transform_fast_result(result)

Expand Down
41 changes: 20 additions & 21 deletions pandas/io/clipboard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,32 +444,31 @@ def copy_windows(text):

text = _stringifyText(text) # Converts non-str values to str.

with window() as hwnd:
with window() as hwnd, clipboard(hwnd):
# http://msdn.com/ms649048
# If an application calls OpenClipboard with hwnd set to NULL,
# EmptyClipboard sets the clipboard owner to NULL;
# this causes SetClipboardData to fail.
# => We need a valid hwnd to copy something.
with clipboard(hwnd):
safeEmptyClipboard()

if text:
# http://msdn.com/ms649051
# If the hMem parameter identifies a memory object,
# the object must have been allocated using the
# function with the GMEM_MOVEABLE flag.
count = wcslen(text) + 1
handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar))
locked_handle = safeGlobalLock(handle)

ctypes.memmove(
c_wchar_p(locked_handle),
c_wchar_p(text),
count * sizeof(c_wchar),
)

safeGlobalUnlock(handle)
safeSetClipboardData(CF_UNICODETEXT, handle)
safeEmptyClipboard()

if text:
# http://msdn.com/ms649051
# If the hMem parameter identifies a memory object,
# the object must have been allocated using the
# function with the GMEM_MOVEABLE flag.
count = wcslen(text) + 1
handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar))
locked_handle = safeGlobalLock(handle)

ctypes.memmove(
c_wchar_p(locked_handle),
c_wchar_p(text),
count * sizeof(c_wchar),
)

safeGlobalUnlock(handle)
safeSetClipboardData(CF_UNICODETEXT, handle)

def paste_windows():
with clipboard(None):
Expand Down
22 changes: 13 additions & 9 deletions pandas/tests/apply/test_invalid_arg.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,8 @@ def test_apply_broadcast_error(int_frame_const_col, func):
def test_transform_and_agg_err_agg(axis, float_frame):
# cannot both transform and agg
msg = "cannot combine transform and aggregation operations"
with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
float_frame.agg(["max", "sqrt"], axis=axis)
with pytest.raises(ValueError, match=msg), np.errstate(all="ignore"):
float_frame.agg(["max", "sqrt"], axis=axis)


@pytest.mark.parametrize(
Expand All @@ -305,9 +304,8 @@ def test_transform_and_agg_err_agg(axis, float_frame):
)
def test_transform_and_agg_err_series(string_series, func, msg):
# we are trying to transform with an aggregator
with pytest.raises(ValueError, match=msg):
with np.errstate(all="ignore"):
string_series.agg(func)
with pytest.raises(ValueError, match=msg), np.errstate(all="ignore"):
string_series.agg(func)


@pytest.mark.parametrize("func", [["max", "min"], ["max", "sqrt"]])
Expand All @@ -327,9 +325,15 @@ def test_transform_wont_agg_series(string_series, func):

warn = RuntimeWarning if func[0] == "sqrt" else None
warn_msg = "invalid value encountered in sqrt"
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(warn, match=warn_msg, check_stacklevel=False):
string_series.transform(func)
with pytest.raises(
ValueError,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imo this read terrible and would prefer doing this with 2 context managers

match=msg,
), tm.assert_produces_warning(
warn,
match=warn_msg,
check_stacklevel=False,
):
string_series.transform(func)


@pytest.mark.parametrize(
Expand Down
32 changes: 20 additions & 12 deletions pandas/tests/arithmetic/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,12 +852,16 @@ def test_pi_add_offset_array(self, box):
# addition/subtraction ops with incompatible offsets should issue
# a PerformanceWarning and _then_ raise a TypeError.
msg = r"Input cannot be converted to Period\(freq=Q-DEC\)"
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
pi + unanchored
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
unanchored + pi
with pytest.raises(
IncompatibleFrequency,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
pi + unanchored
with pytest.raises(
IncompatibleFrequency,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
unanchored + pi

@pytest.mark.parametrize("box", [np.array, pd.Index])
def test_pi_sub_offset_array(self, box):
Expand All @@ -882,12 +886,16 @@ def test_pi_sub_offset_array(self, box):
# addition/subtraction ops with anchored offsets should issue
# a PerformanceWarning and _then_ raise a TypeError.
msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)"
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
pi - anchored
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
anchored - pi
with pytest.raises(
IncompatibleFrequency,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
pi - anchored
with pytest.raises(
IncompatibleFrequency,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
anchored - pi

def test_pi_add_iadd_int(self, one):
# Variants of `one` for #19012
Expand Down
40 changes: 25 additions & 15 deletions pandas/tests/arithmetic/test_timedelta64.py
Original file line number Diff line number Diff line change
Expand Up @@ -1387,18 +1387,26 @@ def test_td64arr_addsub_anchored_offset_arraylike(self, obox, box_with_array):
# addition/subtraction ops with anchored offsets should issue
# a PerformanceWarning and _then_ raise a TypeError.
msg = "has incorrect type|cannot add the type MonthEnd"
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
tdi + anchored
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
anchored + tdi
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
tdi - anchored
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
anchored - tdi
with pytest.raises(
TypeError,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
tdi + anchored
with pytest.raises(
TypeError,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
anchored + tdi
with pytest.raises(
TypeError,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
tdi - anchored
with pytest.raises(
TypeError,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
anchored - tdi

# ------------------------------------------------------------------
# Unsorted
Expand All @@ -1422,9 +1430,11 @@ def test_td64arr_add_sub_object_array(self, box_with_array):
tm.assert_equal(result, expected)

msg = "unsupported operand type|cannot subtract a datelike"
with pytest.raises(TypeError, match=msg):
with tm.assert_produces_warning(PerformanceWarning):
tdarr - other
with pytest.raises(
TypeError,
match=msg,
), tm.assert_produces_warning(PerformanceWarning):
tdarr - other

with tm.assert_produces_warning(PerformanceWarning):
result = other - tdarr
Expand Down
5 changes: 2 additions & 3 deletions pandas/tests/arrays/categorical/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,5 @@ async def test_tab_complete_warning(self, ip):

# GH 31324 newer jedi version raises Deprecation warning;
# appears resolved 2021-02-02
with tm.assert_produces_warning(None):
with provisionalcompleter("ignore"):
list(ip.Completer.completions("c.", 1))
with tm.assert_produces_warning(None), provisionalcompleter("ignore"):
list(ip.Completer.completions("c.", 1))
16 changes: 10 additions & 6 deletions pandas/tests/arrays/string_/test_string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,11 @@ def test_from_sequence_wrong_dtype_raises():

ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]")

with pytest.raises(AssertionError, match=None):
with pd.option_context("string_storage", "python"):
ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype())
with pytest.raises(
AssertionError,
match=None,
), pd.option_context("string_storage", "python"):
ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype())

with pd.option_context("string_storage", "pyarrow"):
ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype())
Expand All @@ -108,9 +110,11 @@ def test_from_sequence_wrong_dtype_raises():
with pd.option_context("string_storage", "python"):
StringArray._from_sequence(["a", None, "c"], dtype=StringDtype())

with pytest.raises(AssertionError, match=None):
with pd.option_context("string_storage", "pyarrow"):
StringArray._from_sequence(["a", None, "c"], dtype=StringDtype())
with pytest.raises(
AssertionError,
match=None,
), pd.option_context("string_storage", "pyarrow"):
StringArray._from_sequence(["a", None, "c"], dtype=StringDtype())

StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("python"))

Expand Down
17 changes: 8 additions & 9 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,15 +319,14 @@ def test_searchsorted_castable_strings(self, arr1d, box, string_storage):

arr_type = "StringArray" if string_storage == "python" else "ArrowStringArray"

with pd.option_context("string_storage", string_storage):
with pytest.raises(
TypeError,
match=re.escape(
f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
f"or array of those. Got '{arr_type}' instead."
),
):
arr.searchsorted([str(arr[1]), "baz"])
with pd.option_context("string_storage", string_storage), pytest.raises(
TypeError,
match=re.escape(
f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', "
f"or array of those. Got '{arr_type}' instead."
),
):
arr.searchsorted([str(arr[1]), "baz"])

def test_getitem_near_implementation_bounds(self):
# We only check tz-naive for DTA bc the bounds are slightly different
Expand Down
5 changes: 2 additions & 3 deletions pandas/tests/config/test_localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,8 @@ def test_set_locale(lang, enc):
if not can_set_locale(new_locale):
msg = "unsupported locale setting"

with pytest.raises(locale.Error, match=msg):
with set_locale(new_locale):
pass
with pytest.raises(locale.Error, match=msg), set_locale(new_locale):
pass
else:
with set_locale(new_locale) as normalized_locale:
new_lang, new_enc = normalized_locale.split(".")
Expand Down
Loading