Skip to content
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

Enable ruff's flake8-return rule #3047

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 2 additions & 3 deletions notes-to-self/how-does-windows-so-reuseaddr-work.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,10 @@ def table_entry(mode1, bind_type1, mode2, bind_type2):
except OSError as exc:
if exc.winerror == errno.WSAEADDRINUSE:
return "INUSE"
elif exc.winerror == errno.WSAEACCES:
if exc.winerror == errno.WSAEACCES:
return "ACCESS"
raise
else:
return "Success"
return "Success"


print(
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ select = [
"PT", # flake8-pytest-style
"PYI", # flake8-pyi
"Q", # flake8-quotes
"RET", # flake8-return
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"TC", # flake8-type-checking
Expand Down
5 changes: 2 additions & 3 deletions src/trio/_core/_io_kqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,8 @@
events += batch
if len(batch) < max_events:
break
else:
timeout = 0
# and loop back to the start
timeout = 0

Check warning on line 84 in src/trio/_core/_io_kqueue.py

View check run for this annotation

Codecov / codecov/patch

src/trio/_core/_io_kqueue.py#L84

Added line #L84 was not covered by tests
# and loop back to the start
return events

def process_events(self, events: EventResult) -> None:
Expand Down
16 changes: 7 additions & 9 deletions src/trio/_core/_mock_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ def rate(self) -> float:
def rate(self, new_rate: float) -> None:
if new_rate < 0:
raise ValueError("rate must be >= 0")
else:
real = self._real_clock()
virtual = self._real_to_virtual(real)
self._virtual_base = virtual
self._real_base = real
self._rate = float(new_rate)
real = self._real_clock()
virtual = self._real_to_virtual(real)
self._virtual_base = virtual
self._real_base = real
self._rate = float(new_rate)

@property
def autojump_threshold(self) -> float:
Expand Down Expand Up @@ -144,10 +143,9 @@ def deadline_to_sleep_time(self, deadline: float) -> float:
virtual_timeout = deadline - self.current_time()
if virtual_timeout <= 0:
return 0
elif self._rate > 0:
if self._rate > 0:
return virtual_timeout / self._rate
else:
return 999999999
return 999999999

def jump(self, seconds: float) -> None:
"""Manually advance the clock by the given number of seconds.
Expand Down
74 changes: 35 additions & 39 deletions src/trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,10 +223,9 @@
exceptions[0].__traceback__,
)
return exceptions[0]
elif modified:
if modified:
return excgroup.derive(exceptions)
else:
return excgroup
return excgroup


@attrs.define(eq=False)
Expand Down Expand Up @@ -255,9 +254,8 @@
deadline, _, cancel_scope = self._heap[0]
if deadline == cancel_scope._registered_deadline:
return deadline
else:
# This entry is stale; discard it and try again
heappop(self._heap)
# This entry is stale; discard it and try again
heappop(self._heap)
return inf

def _prune(self) -> None:
Expand Down Expand Up @@ -666,22 +664,21 @@
remaining_error_after_cancel_scope = self._close(exc)
if remaining_error_after_cancel_scope is None:
return True
elif remaining_error_after_cancel_scope is exc:
if remaining_error_after_cancel_scope is exc:
return False
else:
# Copied verbatim from the old MultiErrorCatcher. Python doesn't
# allow us to encapsulate this __context__ fixup.
old_context = remaining_error_after_cancel_scope.__context__
try:
raise remaining_error_after_cancel_scope
finally:
_, value, _ = sys.exc_info()
assert value is remaining_error_after_cancel_scope
value.__context__ = old_context
# delete references from locals to avoid creating cycles
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage
# Note: still relevant
del remaining_error_after_cancel_scope, value, _, exc
# Copied verbatim from the old MultiErrorCatcher. Python doesn't
# allow us to encapsulate this __context__ fixup.
old_context = remaining_error_after_cancel_scope.__context__
try:
raise remaining_error_after_cancel_scope
finally:
_, value, _ = sys.exc_info()
assert value is remaining_error_after_cancel_scope
value.__context__ = old_context
# delete references from locals to avoid creating cycles
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage
# Note: still relevant
del remaining_error_after_cancel_scope, value, _, exc

def __repr__(self) -> str:
if self._cancel_status is not None:
Expand Down Expand Up @@ -788,7 +785,7 @@
def relative_deadline(self) -> float:
if self._has_been_entered:
return self._deadline - current_time()
elif self._deadline != inf:
if self._deadline != inf:
assert self._relative_deadline == inf
raise RuntimeError(
"unentered non-relative cancel scope does not have a relative deadline",
Expand Down Expand Up @@ -1032,21 +1029,20 @@
combined_error_from_nursery = self._scope._close(new_exc)
if combined_error_from_nursery is None:
return True
elif combined_error_from_nursery is exc:
if combined_error_from_nursery is exc:
return False
else:
# Copied verbatim from the old MultiErrorCatcher. Python doesn't
# allow us to encapsulate this __context__ fixup.
old_context = combined_error_from_nursery.__context__
try:
raise combined_error_from_nursery
finally:
_, value, _ = sys.exc_info()
assert value is combined_error_from_nursery
value.__context__ = old_context
# delete references from locals to avoid creating cycles
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage
del _, combined_error_from_nursery, value, new_exc
# Copied verbatim from the old MultiErrorCatcher. Python doesn't
# allow us to encapsulate this __context__ fixup.
old_context = combined_error_from_nursery.__context__
try:
raise combined_error_from_nursery
finally:
_, value, _ = sys.exc_info()
assert value is combined_error_from_nursery
value.__context__ = old_context
# delete references from locals to avoid creating cycles
# see test_cancel_scope_exit_doesnt_create_cyclic_garbage
del _, combined_error_from_nursery, value, new_exc

# make sure these raise errors in static analysis if called
if not TYPE_CHECKING:
Expand Down Expand Up @@ -2412,10 +2408,10 @@
# cluttering every single Trio traceback with an extra frame.
if isinstance(runner.main_task_outcome, Value):
return cast("RetT", runner.main_task_outcome.value)
elif isinstance(runner.main_task_outcome, Error):
if isinstance(runner.main_task_outcome, Error):
raise runner.main_task_outcome.error
else: # pragma: no cover
raise AssertionError(runner.main_task_outcome)
# pragma: no cover
raise AssertionError(runner.main_task_outcome)

Check warning on line 2414 in src/trio/_core/_run.py

View check run for this annotation

Codecov / codecov/patch

src/trio/_core/_run.py#L2414

Added line #L2414 was not covered by tests


# Explicit .../"Any" not allowed
Expand Down
3 changes: 1 addition & 2 deletions src/trio/_core/_tests/test_guest_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,8 +589,7 @@ def bad_get_events(
) -> trio._core._run.EventResult:
if threading.current_thread() is not t:
raise ValueError("oh no!")
else:
return old_get_events(self, timeout)
return old_get_events(self, timeout)

m.setattr("trio._core._run.TheIOManager.get_events", bad_get_events)

Expand Down
5 changes: 3 additions & 2 deletions src/trio/_core/_tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2091,8 +2091,9 @@ async def __anext__(self) -> list[int]:
StopAsyncIteration,
):
raise e.exceptions[0] from None
else: # pragma: no cover
raise AssertionError("unknown error in _accumulate") from e
raise AssertionError( # pragma: no cover
"unknown error in _accumulate",
) from e

return items

Expand Down
5 changes: 2 additions & 3 deletions src/trio/_core/_tests/test_thread_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,13 @@ def acquire(self, timeout: int = -1) -> bool:
got_it = self._lock.acquire(timeout=timeout)
if timeout == -1:
return True
elif got_it:
if got_it:
if self._counter > 0:
self._counter -= 1
self._lock.release()
return False
return True
else:
return False
return False

def release(self) -> None:
self._lock.release()
Expand Down
6 changes: 2 additions & 4 deletions src/trio/_core/_tests/test_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,7 @@ def patched_get_underlying(
sock = sock.fileno()
if which == WSAIoctls.SIO_BSP_HANDLE_SELECT:
return _handle(sock + 1)
else:
return _handle(sock)
return _handle(sock)

monkeypatch.setattr(_io_windows, "_get_underlying_socket", patched_get_underlying)
with pytest.raises(
Expand Down Expand Up @@ -288,8 +287,7 @@ def patched_get_underlying(
sock = sock.fileno()
if which == WSAIoctls.SIO_BASE_HANDLE:
raise OSError("nope")
else:
return _handle(sock)
return _handle(sock)

monkeypatch.setattr(_io_windows, "_get_underlying_socket", patched_get_underlying)
with pytest.raises(
Expand Down
9 changes: 4 additions & 5 deletions src/trio/_core/_unbounded_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,10 @@ async def get_batch(self) -> list[T]:
if not self._can_get:
await self._lot.park()
return self._get_batch_protected()
else:
try:
return self._get_batch_protected()
finally:
await _core.cancel_shielded_checkpoint()
try:
return self._get_batch_protected()
finally:
await _core.cancel_shielded_checkpoint()

def statistics(self) -> UnboundedQueueStatistics:
"""Return an :class:`UnboundedQueueStatistics` object containing debugging information."""
Expand Down
27 changes: 9 additions & 18 deletions src/trio/_dtls.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,13 @@
def packet_header_overhead(sock: SocketType) -> int:
if sock.family == trio.socket.AF_INET:
return 28
else:
return 48
return 48


def worst_case_mtu(sock: SocketType) -> int:
if sock.family == trio.socket.AF_INET:
return 576 - packet_header_overhead(sock)
else:
return 1280 - packet_header_overhead(sock)
return 1280 - packet_header_overhead(sock)

Check warning on line 59 in src/trio/_dtls.py

View check run for this annotation

Codecov / codecov/patch

src/trio/_dtls.py#L59

Added line #L59 was not covered by tests


def best_guess_mtu(sock: SocketType) -> int:
Expand Down Expand Up @@ -612,8 +610,7 @@
cookie,
old_cookie,
)
else:
return False
return False


def challenge_for(
Expand Down Expand Up @@ -655,10 +652,9 @@
)
payload = encode_handshake_fragment(hs)

packet = encode_record(
return encode_record(
Record(ContentType.handshake, ProtocolVersion.DTLS10, epoch_seqno, payload),
)
return packet


_T = TypeVar("_T")
Expand Down Expand Up @@ -740,9 +736,8 @@
if old_stream._client_hello == (cookie, bits):
# ...This was just a duplicate of the last ClientHello, so never mind.
return
else:
# Ok, this *really is* a new handshake; the old stream should go away.
old_stream._set_replaced()
# Ok, this *really is* a new handshake; the old stream should go away.
old_stream._set_replaced()
stream._client_hello = (cookie, bits)
endpoint._streams[address] = stream
endpoint._incoming_connections_q.s.send_nowait(stream)
Expand All @@ -765,8 +760,7 @@
# This is totally useless -- there's nothing we can do with this
# information. So we just ignore it and retry the recv.
continue
else:
raise
raise
endpoint = endpoint_ref()
try:
if endpoint is None:
Expand Down Expand Up @@ -802,9 +796,7 @@
if exc.errno in (errno.EBADF, errno.ENOTSOCK):
# socket was closed
return
else: # pragma: no cover
# ??? shouldn't happen
raise
raise # ??? shouldn't happen # pragma: no cover


@attrs.frozen
Expand Down Expand Up @@ -994,8 +986,7 @@
# openssl decided to retransmit; discard because we handle
# retransmits ourselves
return []
else:
return new_volley_messages
return new_volley_messages

# If we're a client, we send the initial volley. If we're a server, then
# the initial ClientHello has already been inserted into self._ssl's
Expand Down
6 changes: 2 additions & 4 deletions src/trio/_file_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,7 @@ async def __anext__(self: AsyncIOWrapper[_CanReadLine[AnyStr]]) -> AnyStr:
line = await self.readline()
if line:
return line
else:
raise StopAsyncIteration
raise StopAsyncIteration

async def detach(self: AsyncIOWrapper[_CanDetach[T]]) -> AsyncIOWrapper[T]:
"""Like :meth:`io.BufferedIOBase.detach`, but async.
Expand Down Expand Up @@ -467,7 +466,7 @@ async def open_file(
:func:`trio.Path.open`

"""
file_ = wrap_file(
return wrap_file(
await trio.to_thread.run_sync(
io.open,
file,
Expand All @@ -480,7 +479,6 @@ async def open_file(
opener,
),
)
return file_


def wrap_file(file: FileT) -> AsyncIOWrapper[FileT]:
Expand Down
3 changes: 1 addition & 2 deletions src/trio/_highlevel_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ async def send_eof(self) -> None:
stream = self.send_stream
if _is_halfclosable(stream):
return await stream.send_eof()
else:
return await stream.aclose()
return await stream.aclose()

# we intentionally accept more types from the caller than we support returning
async def receive_some(self, max_bytes: int | None = None) -> bytes:
Expand Down
3 changes: 1 addition & 2 deletions src/trio/_highlevel_open_tcp_listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,7 @@ async def open_tcp_listeners(
# failure to create the other.
unsupported_address_families.append(ex)
continue
else:
raise
raise
try:
# See https://github.com/python-trio/trio/issues/39
if sys.platform != "win32":
Expand Down
Loading
Loading