Skip to content

Commit f85021e

Browse files
CoolCat467jakkdl
andauthored
Enable pyupgrade rule (#2809)
* Enable pyupgrade rule * Fix imports being seperated --------- Co-authored-by: John Litborn <11260241+jakkdl@users.noreply.github.com>
1 parent 9ec9d05 commit f85021e

17 files changed

Lines changed: 55 additions & 81 deletions

notes-to-self/file-read-latency.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,5 @@
2424
seek = (end - between) / COUNT * 1e9
2525
read = both - seek
2626
print(
27-
"{:.2f} ns/(seek+read), {:.2f} ns/seek, estimate ~{:.2f} ns/read".format(
28-
both, seek, read
29-
)
27+
f"{both:.2f} ns/(seek+read), {seek:.2f} ns/seek, estimate ~{read:.2f} ns/read"
3028
)

notes-to-self/proxy-benchmarks.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,10 @@ def __init__(self, wrapped):
5151

5252
def add_wrapper(cls, method):
5353
code = textwrap.dedent(
54-
"""
54+
f"""
5555
def wrapper(self, *args, **kwargs):
56-
return self._wrapped.{}(*args, **kwargs)
57-
""".format(
58-
method
59-
)
56+
return self._wrapped.{method}(*args, **kwargs)
57+
"""
6058
)
6159
ns = {}
6260
exec(code, ns)
@@ -106,7 +104,7 @@ def __init__(self, wrapped):
106104

107105
def add_wrapper(cls, attr):
108106
code = textwrap.dedent(
109-
"""
107+
f"""
110108
def getter(self):
111109
return self._wrapped.{attr}
112110
@@ -115,9 +113,7 @@ def setter(self, newval):
115113
116114
def deleter(self):
117115
del self._wrapped.{attr}
118-
""".format(
119-
attr=attr
120-
)
116+
"""
121117
)
122118
ns = {}
123119
exec(code, ns)
@@ -176,4 +172,4 @@ def check(cls):
176172
# obj.fileno
177173
end = time.perf_counter()
178174
per_usec = COUNT / (end - start) / 1e6
179-
print("{:7.2f} / us: {} ({})".format(per_usec, obj.strategy, obj.works_for))
175+
print(f"{per_usec:7.2f} / us: {obj.strategy} ({obj.works_for})")

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ select = [
2727
"E", # Error
2828
"W", # Warning
2929
"I", # isort
30+
"UP", # pyupgrade
3031
"B", # flake8-bugbear
3132
"YTT", # flake8-2020
3233
"ASYNC", # flake8-async

trio/_channel.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,7 @@ def __attrs_post_init__(self) -> None:
155155
self._state.open_send_channels += 1
156156

157157
def __repr__(self) -> str:
158-
return "<send channel at {:#x}, using buffer at {:#x}>".format(
159-
id(self), id(self._state)
160-
)
158+
return f"<send channel at {id(self):#x}, using buffer at {id(self._state):#x}>"
161159

162160
def statistics(self) -> MemoryChannelStats:
163161
# XX should we also report statistics specific to this object?

trio/_core/_io_epoll.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import select
44
import sys
55
from collections import defaultdict
6-
from typing import TYPE_CHECKING, DefaultDict, Literal
6+
from typing import TYPE_CHECKING, Literal
77

88
import attr
99

@@ -201,7 +201,7 @@ class _EpollStatistics:
201201
class EpollIOManager:
202202
_epoll: select.epoll = attr.ib(factory=select.epoll)
203203
# {fd: EpollWaiters}
204-
_registered: DefaultDict[int, EpollWaiters] = attr.ib(
204+
_registered: defaultdict[int, EpollWaiters] = attr.ib(
205205
factory=lambda: defaultdict(EpollWaiters)
206206
)
207207
_force_wakeup: WakeupSocketpair = attr.ib(factory=WakeupSocketpair)

trio/_core/_io_windows.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
Callable,
1212
Iterator,
1313
Literal,
14-
Optional,
1514
TypeVar,
1615
cast,
1716
)
@@ -245,9 +244,9 @@ class CKeys(enum.IntEnum):
245244
# operation and start a new one.
246245
@attr.s(slots=True, eq=False)
247246
class AFDWaiters:
248-
read_task: Optional[_core.Task] = attr.ib(default=None)
249-
write_task: Optional[_core.Task] = attr.ib(default=None)
250-
current_op: Optional[AFDPollOp] = attr.ib(default=None)
247+
read_task: _core.Task | None = attr.ib(default=None)
248+
write_task: _core.Task | None = attr.ib(default=None)
249+
current_op: AFDPollOp | None = attr.ib(default=None)
251250

252251

253252
# We also need to bundle up all the info for a single op into a standalone
@@ -585,9 +584,9 @@ def process_events(self, received: EventResult) -> None:
585584
pass
586585
else:
587586
exc = _core.TrioInternalError(
588-
"Failed to cancel overlapped I/O in {} and didn't "
587+
f"Failed to cancel overlapped I/O in {waiter.name} and didn't "
589588
"receive the completion either. Did you forget to "
590-
"call register_with_iocp()?".format(waiter.name)
589+
"call register_with_iocp()?"
591590
)
592591
# Raising this out of handle_io ensures that
593592
# the user will see our message even if some

trio/_core/_run.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
DEADLINE_HEAP_MIN_PRUNE_THRESHOLD: Final = 1000
7373

7474
# Passed as a sentinel
75-
_NO_SEND: Final["Outcome[Any]"] = cast("Outcome[Any]", object())
75+
_NO_SEND: Final[Outcome[Any]] = cast("Outcome[Any]", object())
7676

7777
FnT = TypeVar("FnT", bound="Callable[..., Any]")
7878
StatusT = TypeVar("StatusT")
@@ -537,8 +537,8 @@ def __enter__(self) -> Self:
537537
def _close(self, exc: BaseException | None) -> BaseException | None:
538538
if self._cancel_status is None:
539539
new_exc = RuntimeError(
540-
"Cancel scope stack corrupted: attempted to exit {!r} "
541-
"which had already been exited".format(self)
540+
f"Cancel scope stack corrupted: attempted to exit {self!r} "
541+
"which had already been exited"
542542
)
543543
new_exc.__context__ = exc
544544
return new_exc
@@ -559,10 +559,8 @@ def _close(self, exc: BaseException | None) -> BaseException | None:
559559
# cancel scope it's trying to close. Raise an error
560560
# without changing any state.
561561
new_exc = RuntimeError(
562-
"Cancel scope stack corrupted: attempted to exit {!r} "
563-
"from unrelated {!r}\n{}".format(
564-
self, scope_task, MISNESTING_ADVICE
565-
)
562+
f"Cancel scope stack corrupted: attempted to exit {self!r} "
563+
f"from unrelated {scope_task!r}\n{MISNESTING_ADVICE}"
566564
)
567565
new_exc.__context__ = exc
568566
return new_exc
@@ -1773,9 +1771,7 @@ def task_exited(self, task: Task, outcome: Outcome[Any]) -> None:
17731771
# traceback frame included
17741772
raise RuntimeError(
17751773
"Cancel scope stack corrupted: cancel scope surrounding "
1776-
"{!r} was closed before the task exited\n{}".format(
1777-
task, MISNESTING_ADVICE
1778-
)
1774+
f"{task!r} was closed before the task exited\n{MISNESTING_ADVICE}"
17791775
)
17801776
except RuntimeError as new_exc:
17811777
if isinstance(outcome, Error):
@@ -2596,10 +2592,10 @@ def unrolled_run(
25962592
runner.task_exited(task, msg.final_outcome)
25972593
else:
25982594
exc = TypeError(
2599-
"trio.run received unrecognized yield message {!r}. "
2595+
f"trio.run received unrecognized yield message {msg!r}. "
26002596
"Are you trying to use a library written for some "
26012597
"other framework like asyncio? That won't work "
2602-
"without some kind of compatibility shim.".format(msg)
2598+
"without some kind of compatibility shim."
26032599
)
26042600
# The foreign library probably doesn't adhere to our
26052601
# protocol of unwrapping whatever outcome gets sent in.

trio/_core/_windows_cffi.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
import enum
44
import re
5-
from typing import TYPE_CHECKING, NewType, Protocol, cast
5+
from typing import TYPE_CHECKING, NewType, NoReturn, Protocol, cast
66

77
if TYPE_CHECKING:
8-
from typing_extensions import NoReturn, TypeAlias
8+
from typing_extensions import TypeAlias
99

1010
import cffi
1111

trio/_file_io.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -501,8 +501,8 @@ def has(attr: str) -> bool:
501501

502502
if not (has("close") and (has("read") or has("write"))):
503503
raise TypeError(
504-
"{} does not implement required duck-file methods: "
505-
"close and (read or write)".format(file)
504+
f"{file} does not implement required duck-file methods: "
505+
"close and (read or write)"
506506
)
507507

508508
return AsyncIOWrapper(file)

trio/_path.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -413,23 +413,16 @@ async def group(self) -> str: ...
413413
async def is_mount(self) -> bool: ...
414414
if sys.version_info >= (3, 9):
415415
async def readlink(self) -> Path: ...
416-
if sys.version_info >= (3, 8):
417-
async def rename(self, target: StrPath) -> Path: ...
418-
async def replace(self, target: StrPath) -> Path: ...
419-
else:
420-
async def rename(self, target: StrPath) -> None: ...
421-
async def replace(self, target: StrPath) -> None: ...
416+
async def rename(self, target: StrPath) -> Path: ...
417+
async def replace(self, target: StrPath) -> Path: ...
422418
async def resolve(self, strict: bool = False) -> Path: ...
423419
async def rglob(self, pattern: str) -> Iterable[Path]: ...
424420
async def rmdir(self) -> None: ...
425421
async def symlink_to(self, target: StrPath, target_is_directory: bool = False) -> None: ...
426422
if sys.version_info >= (3, 10):
427423
async def hardlink_to(self, target: str | pathlib.Path) -> None: ...
428424
async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ...
429-
if sys.version_info >= (3, 8):
430-
async def unlink(self, missing_ok: bool = False) -> None: ...
431-
else:
432-
async def unlink(self) -> None: ...
425+
async def unlink(self, missing_ok: bool = False) -> None: ...
433426
@classmethod
434427
async def home(self) -> Path: ...
435428
async def absolute(self) -> Path: ...

0 commit comments

Comments
 (0)