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 4 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 @@ -122,6 +122,7 @@ select = [
"PT", # flake8-pytest-style
"PYI", # flake8-pyi
"Q", # flake8-quotes
"RET", # flake8-return
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"TCH", # 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 @@ -77,9 +77,8 @@
events += batch
if len(batch) < max_events:
break
else:
timeout = 0
# and loop back to the start
timeout = 0

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

View check run for this annotation

Codecov / codecov/patch

src/trio/_core/_io_kqueue.py#L80

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

def process_events(self, events: EventResult) -> None:
Expand Down
15 changes: 7 additions & 8 deletions src/trio/_core/_ki.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: # type: ignore[
return coro # type: ignore[return-value]

return wrapper
elif inspect.isgeneratorfunction(fn):
if inspect.isgeneratorfunction(fn):

@wraps(fn)
def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: # type: ignore[misc]
Expand All @@ -165,7 +165,7 @@ def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: # type: ignore[
return gen # type: ignore[return-value]

return wrapper
elif inspect.isasyncgenfunction(fn) or legacy_isasyncgenfunction(fn):
if inspect.isasyncgenfunction(fn) or legacy_isasyncgenfunction(fn):

@wraps(fn) # type: ignore[arg-type]
def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: # type: ignore[misc]
Expand All @@ -175,14 +175,13 @@ def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT: # type: ignore[
return agen # type: ignore[return-value]

return wrapper
else:

@wraps(fn)
def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
sys._getframe().f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED] = enabled
return fn(*args, **kwargs)
@wraps(fn)
def wrapper_(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
sys._getframe().f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED] = enabled
return fn(*args, **kwargs)

return wrapper
return wrapper_

return decorator

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
71 changes: 33 additions & 38 deletions src/trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,9 @@ def collapse_exception_group(
excgroup.__traceback__, 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 @@ -254,9 +253,8 @@ def next_deadline(self) -> float:
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 @@ -642,22 +640,21 @@ def __exit__(
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 @@ -949,21 +946,20 @@ async def __aexit__(
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 @@ -2302,10 +2298,9 @@ def run(
# 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)
raise AssertionError(runner.main_task_outcome) # pragma: no cover


def start_guest_run(
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 @@ -554,8 +554,7 @@ async def crash_in_worker_thread_io(in_host: InHost) -> None:
def bad_get_events(*args: Any) -> object:
if threading.current_thread() is not t:
raise ValueError("oh no!")
else:
return old_get_events(*args)
return old_get_events(*args)

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 @@ -2039,8 +2039,9 @@ async def __anext__(self) -> list[int]:
e.exceptions[0], 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 @@ -147,14 +147,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 @@ -247,8 +247,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 All @@ -275,8 +274,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 @@ -53,15 +53,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 62 in src/trio/_dtls.py

View check run for this annotation

Codecov / codecov/patch

src/trio/_dtls.py#L62

Added line #L62 was not covered by tests


def best_guess_mtu(sock: SocketType) -> int:
Expand Down Expand Up @@ -600,8 +598,7 @@
return hmac.compare_digest(cookie, cur_cookie) | hmac.compare_digest(
cookie, old_cookie
)
else:
return False
return False


def challenge_for(
Expand Down Expand Up @@ -640,10 +637,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 @@ -737,9 +733,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 @@ -761,8 +756,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 @@ -798,9 +792,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 @@ -989,8 +981,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 @@ -265,8 +265,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 @@ -463,12 +462,11 @@ async def open_file(
:func:`trio.Path.open`

"""
_file = wrap_file(
return wrap_file(
await trio.to_thread.run_sync(
io.open, file, mode, buffering, encoding, errors, newline, closefd, opener
)
)
return _file


def wrap_file(file: FileT) -> AsyncIOWrapper[FileT]:
Expand Down
Loading
Loading