Skip to content

Commit

Permalink
Enable ruff flake8-simplify rule
Browse files Browse the repository at this point in the history
  • Loading branch information
CoolCat467 committed Oct 19, 2023
1 parent b324b3a commit 94d11a2
Show file tree
Hide file tree
Showing 39 changed files with 385 additions and 452 deletions.
35 changes: 17 additions & 18 deletions notes-to-self/file-read-latency.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,22 @@
# ns per call, instead of ~500 ns/call for the syscall and related overhead.
# That's probably more fair -- the BufferedIOBase code can't service random
# accesses, even if your working set fits entirely in RAM.
f = open("/etc/passwd", "rb") # , buffering=0)
with open("/etc/passwd", "rb") as f: # , buffering=0)
while True:
start = time.perf_counter()
for _ in range(COUNT):
f.seek(0)
f.read(1)
between = time.perf_counter()
for _ in range(COUNT):
f.seek(0)
end = time.perf_counter()

while True:
start = time.perf_counter()
for _ in range(COUNT):
f.seek(0)
f.read(1)
between = time.perf_counter()
for _ in range(COUNT):
f.seek(0)
end = time.perf_counter()

both = (between - start) / COUNT * 1e9
seek = (end - between) / COUNT * 1e9
read = both - seek
print(
"{:.2f} ns/(seek+read), {:.2f} ns/seek, estimate ~{:.2f} ns/read".format(
both, seek, read
both = (between - start) / COUNT * 1e9
seek = (end - between) / COUNT * 1e9
read = both - seek
print(
"{:.2f} ns/(seek+read), {:.2f} ns/seek, estimate ~{:.2f} ns/read".format(
both, seek, read
)
)
)
42 changes: 21 additions & 21 deletions notes-to-self/proxy-benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,24 +156,24 @@ def check(cls):
for cls in classes:
check(cls)

f = open("/etc/passwd")
objs = [c(f) for c in classes]

COUNT = 1000000
try:
import __pypy__ # noqa: F401 # __pypy__ imported but unused
except ImportError:
pass
else:
COUNT *= 10

while True:
print("-------")
for obj in objs:
start = time.perf_counter()
for _ in range(COUNT):
obj.fileno()
# obj.fileno
end = time.perf_counter()
per_usec = COUNT / (end - start) / 1e6
print("{:7.2f} / us: {} ({})".format(per_usec, obj.strategy, obj.works_for))
with open("/etc/passwd") as f:
objs = [c(f) for c in classes]

COUNT = 1000000
try:
import __pypy__ # noqa: F401 # __pypy__ imported but unused
except ImportError:
pass
else:
COUNT *= 10

while True:
print("-------")
for obj in objs:
start = time.perf_counter()
for _ in range(COUNT):
obj.fileno()
# obj.fileno
end = time.perf_counter()
per_usec = COUNT / (end - start) / 1e6
print("{:7.2f} / us: {} ({})".format(per_usec, obj.strategy, obj.works_for))
5 changes: 3 additions & 2 deletions notes-to-self/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,6 @@ async def parent():
print("parent: all done!")


t = Trace(open("/tmp/t.json", "w"))
trio.run(parent, instruments=[t])
with open("/tmp/t.json", "w") as t_json:
t = Trace(t_json)
trio.run(parent, instruments=[t])
5 changes: 2 additions & 3 deletions notes-to-self/win-waitable-timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@
# make this fairly straightforward, but you obviously need to use a separate
# time source

import contextlib
from datetime import datetime, timedelta, timezone

import cffi
import trio
from trio._core._windows_cffi import ffi, kernel32, raise_winerror

try:
with contextlib.suppress(cffi.CDefError):
ffi.cdef(
"""
typedef struct _PROCESS_LEAP_SECOND_INFO {
Expand All @@ -50,8 +51,6 @@
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;
"""
)
except cffi.CDefError:
pass

ffi.cdef(
"""
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ select = [
"F", # pyflakes
"I", # isort
"YTT", # flake8-2020
"SIM", # flake8-simplify
]
extend-ignore = [
'F403', # undefined-local-with-import-star
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

__version__ = "0.0.0" # Overwritten from _version.py below, needed for linter to identify that this variable is defined.

exec(open("trio/_version.py", encoding="utf-8").read())
with open("trio/_version.py", encoding="utf-8") as version_code:
exec(version_code.read())

LONG_DESC = """\
.. image:: https://raw.githubusercontent.com/python-trio/trio/9b0bec646a31e0d0f67b8b6ecc6939726faf3e17/logo/logo-with-background.svg
Expand Down
5 changes: 2 additions & 3 deletions trio/_core/_io_epoll.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import contextlib
import select
import sys
from collections import defaultdict
Expand Down Expand Up @@ -324,7 +325,5 @@ def notify_closing(self, fd: int | _HasFileNo) -> None:
_core.ClosedResourceError("another task closed this fd"),
)
del self._registered[fd]
try:
with contextlib.suppress(OSError, ValueError):

Check warning on line 328 in trio/_core/_io_epoll.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_io_epoll.py#L328

Added line #L328 was not covered by tests
self._epoll.unregister(fd)
except (OSError, ValueError):
pass
17 changes: 10 additions & 7 deletions trio/_core/_multierror.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def catch(
return MultiErrorCatcher(handler)


if TYPE_CHECKING:
if TYPE_CHECKING: # noqa: SIM108
_ExceptionGroup = ExceptionGroup[Exception]
else:
_ExceptionGroup = ExceptionGroup
Expand Down Expand Up @@ -432,12 +432,15 @@ def controller(operation: tputil.ProxyOperation) -> Any | None:
# 'opname' that isn't __getattr__ or __getattribute__. So there's
# no missing test we could add, and no value in coverage nagging
# us about adding one.
if operation.opname in [
"__getattribute__",
"__getattr__",
]: # pragma: no cover
if operation.args[0] == "tb_next":
return tb_next
if (
operation.opname
in {
"__getattribute__",
"__getattr__",
}
and operation.args[0] == "tb_next"
): # pragma: no cover
return tb_next
return operation.delegate() # Deligate is reverting to original behaviour

return cast(
Expand Down
21 changes: 10 additions & 11 deletions trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
Iterator,
Sequence,
)
from contextlib import AbstractAsyncContextManager, contextmanager
from contextlib import AbstractAsyncContextManager, contextmanager, suppress
from contextvars import copy_context
from heapq import heapify, heappop, heappush
from math import inf
Expand Down Expand Up @@ -792,15 +792,19 @@ def cancel_called(self) -> bool:
cancelled, then :attr:`cancelled_caught` is usually more
appropriate.
"""
if self._cancel_status is not None or not self._has_been_entered:
if (
self._cancel_status is not None
or not self._has_been_entered
and not self._cancel_called
and current_time() >= self._deadline
):
# Scope is active or not yet entered: make sure cancel_called
# is true if the deadline has passed. This shouldn't
# be able to actually change behavior, since we check for
# deadline expiry on scope entry and at every checkpoint,
# but it makes the value returned by cancel_called more
# closely match expectations.
if not self._cancel_called and current_time() >= self._deadline:
self.cancel()
self.cancel()

Check warning on line 807 in trio/_core/_run.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_run.py#L807

Added line #L807 was not covered by tests
return self._cancel_called


Expand Down Expand Up @@ -1705,10 +1709,7 @@ def spawn_impl(
# Propagate contextvars
######
if context is None:
if system_task:
context = self.system_context.copy()
else:
context = copy_context()
context = self.system_context.copy() if system_task else copy_context()

Check warning on line 1712 in trio/_core/_run.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_run.py#L1712

Added line #L1712 was not covered by tests

######
# Call the function and get the coroutine object, while giving helpful
Expand Down Expand Up @@ -1940,10 +1941,8 @@ def current_trio_token(self) -> TrioToken:
# This gets called from signal context
def deliver_ki(self) -> None:
self.ki_pending = True
try:
with suppress(RunFinishedError):

Check warning on line 1944 in trio/_core/_run.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_run.py#L1944

Added line #L1944 was not covered by tests
self.entry_queue.run_sync_soon(self._deliver_ki_cb)
except RunFinishedError:
pass

def _deliver_ki_cb(self) -> None:
if not self.ki_pending:
Expand Down
21 changes: 10 additions & 11 deletions trio/_core/_tests/test_asyncgen.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import contextlib
import sys
import weakref
from collections.abc import AsyncGenerator
Expand All @@ -17,10 +18,8 @@ def test_asyncgen_basics() -> None:

async def example(cause: str) -> AsyncGenerator[int, None]:
try:
try:
with contextlib.suppress(GeneratorExit):

Check warning on line 21 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L21

Added line #L21 was not covered by tests
yield 42
except GeneratorExit:
pass
await _core.checkpoint()
except _core.Cancelled:
assert "exhausted" not in cause
Expand All @@ -44,14 +43,14 @@ async def async_main() -> None:
with pytest.warns(
ResourceWarning, match="Async generator.*collected before.*exhausted"
):
assert 42 == await example("abandoned").asend(None)
assert await example("abandoned").asend(None) == 42

Check warning on line 46 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L46

Added line #L46 was not covered by tests
gc_collect_harder()
await _core.wait_all_tasks_blocked()
assert collected.pop() == "abandoned"

aiter = example("exhausted 1")
try:
assert 42 == await aiter.asend(None)
assert await aiter.asend(None) == 42

Check warning on line 53 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L53

Added line #L53 was not covered by tests
finally:
await aiter.aclose()
assert collected.pop() == "exhausted 1"
Expand All @@ -67,7 +66,7 @@ async def async_main() -> None:
aiter = example("exhausted 3")
try:
saved.append(aiter)
assert 42 == await aiter.asend(None)
assert await aiter.asend(None) == 42

Check warning on line 69 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L69

Added line #L69 was not covered by tests
finally:
await aiter.aclose()
assert collected.pop() == "exhausted 3"
Expand All @@ -83,7 +82,7 @@ async def async_main() -> None:
collected.append("outlived run")
else:
saved.append(example("outlived run"))
assert 42 == await saved[-1].asend(None)
assert await saved[-1].asend(None) == 42

Check warning on line 85 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L85

Added line #L85 was not covered by tests
assert collected == []

_core.run(async_main)
Expand Down Expand Up @@ -137,8 +136,8 @@ async def funky_agen() -> AsyncGenerator[int, None]:
async def async_main() -> None:
aiter = funky_agen()
saved.append(aiter)
assert 1 == await aiter.asend(None)
assert 2 == await aiter.asend(None)
assert await aiter.asend(None) == 1
assert await aiter.asend(None) == 2

Check warning on line 140 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L139-L140

Added lines #L139 - L140 were not covered by tests

_core.run(async_main)
assert record == ["cleanup 2", "cleanup 1"]
Expand Down Expand Up @@ -178,7 +177,7 @@ async def async_main() -> None:
for idx in range(100):
ag_chain = agen(idx, ag_chain)
saved.append(ag_chain)
assert 1 == await ag_chain.asend(None)
assert await ag_chain.asend(None) == 1

Check warning on line 180 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L180

Added line #L180 was not covered by tests
assert record == []

_core.run(async_main)
Expand Down Expand Up @@ -320,7 +319,7 @@ async def example(arg: str) -> AsyncGenerator[int, None]:

async def async_main() -> None:
await step_outside_async_context(example("theirs"))
assert 42 == await example("ours").asend(None)
assert await example("ours").asend(None) == 42

Check warning on line 322 in trio/_core/_tests/test_asyncgen.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_asyncgen.py#L322

Added line #L322 was not covered by tests
gc_collect_harder()
assert record == ["firstiter theirs", "finalizer theirs"]
record[:] = []
Expand Down
5 changes: 2 additions & 3 deletions trio/_core/_tests/test_guest_mode.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import contextlib
import contextvars
import queue
import signal
Expand Down Expand Up @@ -593,10 +594,8 @@ async def agen(label):
yield 1
finally:
library = sniffio.current_async_library()
try:
with contextlib.suppress(trio.Cancelled):

Check warning on line 597 in trio/_core/_tests/test_guest_mode.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_guest_mode.py#L597

Added line #L597 was not covered by tests
await sys.modules[library].sleep(0)
except trio.Cancelled:
pass
record.add((label, library))

async def iterate_in_aio():
Expand Down
2 changes: 1 addition & 1 deletion trio/_core/_tests/test_ki.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def protected_manager():
with protected_manager():
assert not _core.currently_ki_protected()

with pytest.raises(KeyError):
with pytest.raises(KeyError): # noqa: SIM117 # multiple-with-statements

Check warning on line 141 in trio/_core/_tests/test_ki.py

View check run for this annotation

Codecov / codecov/patch

trio/_core/_tests/test_ki.py#L141

Added line #L141 was not covered by tests
# This is the one that used to fail
with protected_manager():
raise KeyError
Expand Down
Loading

0 comments on commit 94d11a2

Please sign in to comment.