Skip to content

Commit

Permalink
Enable ruff's Perflint rule. (python-trio#2969)
Browse files Browse the repository at this point in the history
  • Loading branch information
CoolCat467 authored May 20, 2024
1 parent 60b5804 commit a23b727
Show file tree
Hide file tree
Showing 12 changed files with 34 additions and 44 deletions.
8 changes: 4 additions & 4 deletions notes-to-self/fbsd-pipe-close-notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
os.set_blocking(w, False)

print("filling pipe buffer")
while True:
try:
try:
while True:
os.write(w, b"x")
except BlockingIOError:
break
except BlockingIOError:
pass

_, wfds, _ = select.select([], [w], [], 0)
print("select() says the write pipe is", "writable" if w in wfds else "NOT writable")
Expand Down
3 changes: 1 addition & 2 deletions notes-to-self/print-task-tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ def _render_subtree(name, rendered_children):
first_prefix = MID_PREFIX
rest_prefix = MID_CONTINUE
lines.append(first_prefix + child_lines[0])
for child_line in child_lines[1:]:
lines.append(rest_prefix + child_line)
lines.extend(rest_prefix + child_line for child_line in child_lines[1:])
return lines


Expand Down
16 changes: 9 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ select = [
"F", # pyflakes
"FA", # flake8-future-annotations
"I", # isort
"PERF", # Perflint
"PT", # flake8-pytest-style
"PYI", # flake8-pyi
"RUF", # Ruff-specific rules
Expand All @@ -122,13 +123,14 @@ select = [
"YTT", # flake8-2020
]
extend-ignore = [
'A002', # builtin-argument-shadowing
'E402', # module-import-not-at-top-of-file (usually OS-specific)
'E501', # line-too-long
'F403', # undefined-local-with-import-star
'F405', # undefined-local-with-import-star-usage
'PT012', # multiple statements in pytest.raises block
'SIM117', # multiple-with-statements (messes up lots of context-based stuff and looks bad)
'A002', # builtin-argument-shadowing
'E402', # module-import-not-at-top-of-file (usually OS-specific)
'E501', # line-too-long
'F403', # undefined-local-with-import-star
'F405', # undefined-local-with-import-star-usage
'PERF203', # try-except-in-loop (not always possible to refactor)
'PT012', # multiple statements in pytest.raises block
'SIM117', # multiple-with-statements (messes up lots of context-based stuff and looks bad)
]

[tool.ruff.lint.per-file-ignores]
Expand Down
4 changes: 1 addition & 3 deletions src/trio/_core/_tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2044,9 +2044,7 @@ async def __anext__(self) -> list[int]:

return items

result: list[list[int]] = []
async for vals in async_zip(it(4), it(2)):
result.append(vals)
result: list[list[int]] = [vals async for vals in async_zip(it(4), it(2))]
assert result == [[0, 0], [1, 1]]


Expand Down
2 changes: 1 addition & 1 deletion src/trio/_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ async def read_output(
) -> None:
async with stream:
async for chunk in stream:
chunks.append(chunk)
chunks.append(chunk) # noqa: PERF401

# Opening the process does not need to be inside the nursery, so we put it outside
# so any exceptions get directly seen by users.
Expand Down
14 changes: 5 additions & 9 deletions src/trio/_tests/test_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,7 @@ async def producer(send_channel: trio.MemorySendChannel[int], i: int) -> None:
for i in range(10):
nursery.start_soon(producer, send_channel.clone(), i)

got = []
async for value in receive_channel:
got.append(value)
got = [value async for value in receive_channel]

got.sort()
assert got == list(range(30))
Expand Down Expand Up @@ -291,16 +289,14 @@ async def receive_will_succeed() -> None:


async def test_inf_capacity() -> None:
s, r = open_memory_channel[int](float("inf"))
send, receive = open_memory_channel[int](float("inf"))

# It's accepted, and we can send all day without blocking
with s:
with send:
for i in range(10):
s.send_nowait(i)
send.send_nowait(i)

got = []
async for i in r:
got.append(i)
got = [i async for i in receive]
assert got == list(range(10))


Expand Down
2 changes: 1 addition & 1 deletion src/trio/_tests/test_exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def test_nopublic_is_final() -> None:
assert class_is_final(_util.NoPublicConstructor) # This is itself final.

for module in ALL_MODULES:
for _name, class_ in module.__dict__.items():
for class_ in module.__dict__.values():
if isinstance(class_, _util.NoPublicConstructor):
assert class_is_final(class_)

Expand Down
4 changes: 1 addition & 3 deletions src/trio/_tests/test_file_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,9 @@ async def test_open_context_manager(path: pathlib.Path) -> None:
async def test_async_iter() -> None:
async_file = trio.wrap_file(io.StringIO("test\nfoo\nbar"))
expected = list(async_file.wrapped)
result = []
async_file.wrapped.seek(0)

async for line in async_file:
result.append(line)
result = [line async for line in async_file]

assert result == expected

Expand Down
4 changes: 1 addition & 3 deletions src/trio/_tests/test_scheduler_determinism.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ async def tracer(name: str) -> None:

def test_the_trio_scheduler_is_not_deterministic() -> None:
# At least, not yet. See https://github.com/python-trio/trio/issues/32
traces = []
for _ in range(10):
traces.append(trio.run(scheduler_trace))
traces = [trio.run(scheduler_trace) for _ in range(10)]
assert len(set(traces)) == len(traces)


Expand Down
9 changes: 5 additions & 4 deletions src/trio/_tests/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,11 @@ async def test_sniff_sockopts() -> None:
from socket import AF_INET, AF_INET6, SOCK_DGRAM, SOCK_STREAM

# generate the combinations of families/types we're testing:
sockets = []
for family in [AF_INET, AF_INET6]:
for type_ in [SOCK_DGRAM, SOCK_STREAM]:
sockets.append(stdlib_socket.socket(family, type_))
sockets = [
stdlib_socket.socket(family, type_)
for family in [AF_INET, AF_INET6]
for type_ in [SOCK_DGRAM, SOCK_STREAM]
]
for socket in sockets:
# regular Trio socket constructor
tsocket_socket = tsocket.socket(fileno=socket.fileno())
Expand Down
6 changes: 2 additions & 4 deletions src/trio/_tools/gen_exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,11 @@ def create_passthrough_args(funcdef: ast.FunctionDef | ast.AsyncFunctionDef) ->
Example input: ast.parse("def f(a, *, b): ...")
Example output: "(a, b=b)"
"""
call_args = []
for arg in funcdef.args.args:
call_args.append(arg.arg)
call_args = [arg.arg for arg in funcdef.args.args]
if funcdef.args.vararg:
call_args.append("*" + funcdef.args.vararg.arg)
for arg in funcdef.args.kwonlyargs:
call_args.append(arg.arg + "=" + arg.arg)
call_args.append(arg.arg + "=" + arg.arg) # noqa: PERF401 # clarity
if funcdef.args.kwarg:
call_args.append("**" + funcdef.args.kwarg.arg)
return "({})".format(", ".join(call_args))
Expand Down
6 changes: 3 additions & 3 deletions src/trio/_unix_pipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,13 @@ async def receive_some(self, max_bytes: int | None = None) -> bytes:
data = os.read(self._fd_holder.fd, max_bytes)
except BlockingIOError:
await trio.lowlevel.wait_readable(self._fd_holder.fd)
except OSError as e:
if e.errno == errno.EBADF:
except OSError as exc:
if exc.errno == errno.EBADF:
raise trio.ClosedResourceError(
"file was already closed"
) from None
else:
raise trio.BrokenResourceError from e
raise trio.BrokenResourceError from exc
else:
break

Expand Down

0 comments on commit a23b727

Please sign in to comment.