Skip to content

Commit 25cb98f

Browse files
committed
Replace most string forwarding with f-strings
This commit replaces most of the older modulo-based string formatting with f-strings. The one exception is in calls to the logger, which still uses printf-like substitutions. This is left alone, as the logger does additional type-specific formatting of the arguments passed into it.
1 parent 09e2fc5 commit 25cb98f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+305
-323
lines changed

asyncssh/agent.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ async def get_keys(self, identities: Optional[Sequence[bytes]] = None) -> \
298298
resp.check_end()
299299
return result
300300
else:
301-
raise ValueError('Unknown SSH agent response: %d' % resptype)
301+
raise ValueError(f'Unknown SSH agent response: {resptype}')
302302

303303
async def sign(self, key_blob: bytes, data: bytes,
304304
flags: int = 0) -> bytes:
@@ -315,7 +315,7 @@ async def sign(self, key_blob: bytes, data: bytes,
315315
elif resptype == SSH_AGENT_FAILURE:
316316
raise ValueError('Unable to sign with requested key')
317317
else:
318-
raise ValueError('Unknown SSH agent response: %d' % resptype)
318+
raise ValueError(f'Unknown SSH agent response: {resptype}')
319319

320320
async def add_keys(self, keylist: KeyPairListArg = (),
321321
passphrase: Optional[str] = None,
@@ -397,7 +397,7 @@ async def add_keys(self, keylist: KeyPairListArg = (),
397397
if not ignore_failures:
398398
raise ValueError('Unable to add key')
399399
else:
400-
raise ValueError('Unknown SSH agent response: %d' % resptype)
400+
raise ValueError(f'Unknown SSH agent response: {resptype}')
401401

402402
async def add_smartcard_keys(self, provider: str,
403403
pin: Optional[str] = None,
@@ -438,7 +438,7 @@ async def add_smartcard_keys(self, provider: str,
438438
elif resptype == SSH_AGENT_FAILURE:
439439
raise ValueError('Unable to add keys')
440440
else:
441-
raise ValueError('Unknown SSH agent response: %d' % resptype)
441+
raise ValueError(f'Unknown SSH agent response: {resptype}')
442442

443443
async def remove_keys(self, keylist: Sequence[SSHKeyPair]) -> None:
444444
"""Remove a key stored in the agent
@@ -461,7 +461,7 @@ async def remove_keys(self, keylist: Sequence[SSHKeyPair]) -> None:
461461
elif resptype == SSH_AGENT_FAILURE:
462462
raise ValueError('Key not found')
463463
else:
464-
raise ValueError('Unknown SSH agent response: %d' % resptype)
464+
raise ValueError(f'Unknown SSH agent response: {resptype}')
465465

466466
async def remove_smartcard_keys(self, provider: str,
467467
pin: Optional[str] = None) -> None:
@@ -487,7 +487,7 @@ async def remove_smartcard_keys(self, provider: str,
487487
elif resptype == SSH_AGENT_FAILURE:
488488
raise ValueError('Keys not found')
489489
else:
490-
raise ValueError('Unknown SSH agent response: %d' % resptype)
490+
raise ValueError(f'Unknown SSH agent response: {resptype}')
491491

492492
async def remove_all(self) -> None:
493493
"""Remove all keys stored in the agent
@@ -504,7 +504,7 @@ async def remove_all(self) -> None:
504504
elif resptype == SSH_AGENT_FAILURE:
505505
raise ValueError('Unable to remove all keys')
506506
else:
507-
raise ValueError('Unknown SSH agent response: %d' % resptype)
507+
raise ValueError(f'Unknown SSH agent response: {resptype}')
508508

509509
async def lock(self, passphrase: str) -> None:
510510
"""Lock the agent using the specified passphrase
@@ -528,7 +528,7 @@ async def lock(self, passphrase: str) -> None:
528528
elif resptype == SSH_AGENT_FAILURE:
529529
raise ValueError('Unable to lock SSH agent')
530530
else:
531-
raise ValueError('Unknown SSH agent response: %d' % resptype)
531+
raise ValueError(f'Unknown SSH agent response: {resptype}')
532532

533533
async def unlock(self, passphrase: str) -> None:
534534
"""Unlock the agent using the specified passphrase
@@ -552,7 +552,7 @@ async def unlock(self, passphrase: str) -> None:
552552
elif resptype == SSH_AGENT_FAILURE:
553553
raise ValueError('Unable to unlock SSH agent')
554554
else:
555-
raise ValueError('Unknown SSH agent response: %d' % resptype)
555+
raise ValueError(f'Unknown SSH agent response: {resptype}')
556556

557557
async def query_extensions(self) -> Sequence[str]:
558558
"""Return a list of extensions supported by the agent
@@ -581,7 +581,7 @@ async def query_extensions(self) -> Sequence[str]:
581581
elif resptype == SSH_AGENT_FAILURE:
582582
return []
583583
else:
584-
raise ValueError('Unknown SSH agent response: %d' % resptype)
584+
raise ValueError(f'Unknown SSH agent response: {resptype}')
585585

586586
def close(self) -> None:
587587
"""Close the SSH agent connection

asyncssh/agent_win32.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ class _PageantTransport:
7878
"""Transport to connect to Pageant agent on Windows"""
7979

8080
def __init__(self) -> None:
81-
self._mapname = '%s%08x' % (_AGENT_NAME, win32api.GetCurrentThreadId())
81+
self._mapname = f'{_AGENT_NAME}{win32api.GetCurrentThreadId():08x}'
8282

8383
try:
8484
self._mapfile = mmapfile.mmapfile('', self._mapname,

asyncssh/asn1.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2013-2021 by Ron Frederick <ronf@timeheart.net> and others.
1+
# Copyright (c) 2013-2024 by Ron Frederick <ronf@timeheart.net> and others.
22
#
33
# This program and the accompanying materials are made available under
44
# the terms of the Eclipse Public License v2.0 which accompanies this
@@ -169,8 +169,8 @@ def __init__(self, tag: int, content: bytes, asn1_class: int):
169169
self.content = content
170170

171171
def __repr__(self) -> str:
172-
return ('RawDERObject(%s, %s, %r)' %
173-
(_asn1_class[self.asn1_class], self.tag, self.content))
172+
return f'RawDERObject({_asn1_class[self.asn1_class]}, ' \
173+
f'{self.tag}, {self.content!r})'
174174

175175
def __eq__(self, other: object) -> bool:
176176
if not isinstance(other, RawDERObject): # pragma: no cover
@@ -213,10 +213,10 @@ def __init__(self, tag: int, value: object,
213213

214214
def __repr__(self) -> str:
215215
if self.asn1_class == CONTEXT_SPECIFIC:
216-
return 'TaggedDERObject(%s, %r)' % (self.tag, self.value)
216+
return f'TaggedDERObject({self.tag}, {self.value!r})'
217217
else:
218-
return ('TaggedDERObject(%s, %s, %r)' %
219-
(_asn1_class[self.asn1_class], self.tag, self.value))
218+
return f'TaggedDERObject({_asn1_class[self.asn1_class]}, ' \
219+
f'{self.tag}, {self.value!r})'
220220

221221
def __eq__(self, other: object) -> bool:
222222
if not isinstance(other, TaggedDERObject): # pragma: no cover
@@ -469,7 +469,7 @@ def __str__(self) -> str:
469469
return result
470470

471471
def __repr__(self) -> str:
472-
return "BitString('%s')" % self
472+
return f"BitString('{self}')"
473473

474474
def __eq__(self, other: object) -> bool:
475475
if not isinstance(other, BitString): # pragma: no cover
@@ -508,10 +508,10 @@ def __init__(self, value: Union[bytes, bytearray]):
508508
self.value = value
509509

510510
def __str__(self) -> str:
511-
return '%s' % self.value.decode('ascii')
511+
return self.value.decode('ascii')
512512

513513
def __repr__(self) -> str:
514-
return 'IA5String(%r)' % self.value
514+
return f'IA5String({self.value!r})'
515515

516516
def __eq__(self, other: object) -> bool: # pragma: no cover
517517
if not isinstance(other, IA5String):
@@ -569,7 +569,7 @@ def __str__(self) -> str:
569569
return self.value
570570

571571
def __repr__(self) -> str:
572-
return "ObjectIdentifier('%s')" % self.value
572+
return f"ObjectIdentifier('{self.value}')"
573573

574574
def __eq__(self, other: object) -> bool:
575575
if not isinstance(other, ObjectIdentifier): # pragma: no cover
@@ -685,7 +685,7 @@ def der_encode(value: object) -> bytes:
685685
identifier = cls.identifier
686686
content = cls.encode(value)
687687
else:
688-
raise ASN1EncodeError('Cannot DER encode type %s' % t.__name__)
688+
raise ASN1EncodeError(f'Cannot DER encode type {t.__name__}')
689689

690690
length = len(content)
691691
if length < 0x80:

asyncssh/auth_keys.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2015-2021 by Ron Frederick <ronf@timeheart.net> and others.
1+
# Copyright (c) 2015-2024 by Ron Frederick <ronf@timeheart.net> and others.
22
#
33
# This program and the accompanying materials are made available under
44
# the terms of the Eclipse Public License v2.0 which accompanies this
@@ -121,7 +121,7 @@ def _add_permitopen(self, option: str, value: str) -> None:
121121

122122
port = None if port_str == '*' else int(port_str)
123123
except ValueError:
124-
raise ValueError('Illegal permitopen value: %s' % value) from None
124+
raise ValueError(f'Illegal permitopen value: {value}') from None
125125

126126
permitted_opens = cast(Set[Tuple[str, Optional[int]]],
127127
self.options.setdefault(option, set()))

asyncssh/channel.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,7 @@ def __init__(self, conn: 'SSHConnection',
145145

146146
self._recv_chan: Optional[int] = conn.add_channel(self)
147147

148-
self._logger = conn.logger.get_child(context='chan=%d' %
149-
self._recv_chan)
148+
self._logger = conn.logger.get_child(context=f'chan={self._recv_chan}')
150149

151150
self.set_encoding(encoding, errors)
152151
self.set_write_buffer_limits()
@@ -877,8 +876,8 @@ def set_write_buffer_limits(self, high: Optional[int] = None,
877876
low = high // 4
878877

879878
if not 0 <= low <= high:
880-
raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
881-
(high, low))
879+
raise ValueError(f'high (high) must be >= low ({low}) '
880+
'must be >= 0')
882881

883882
self.logger.debug1('Set write buffer limits: low-water=%d, '
884883
'high-water=%d', low, high)
@@ -932,7 +931,7 @@ def write(self, data: AnyStr, datatype: DataType = None) -> None:
932931
datalen = len(encoded_data)
933932

934933
if datatype:
935-
typename = ' to %s' % _data_type_names[datatype]
934+
typename = f' to {_data_type_names[datatype]}'
936935
else:
937936
typename = ''
938937

@@ -1181,7 +1180,7 @@ async def create(self, session_factory: SSHClientSessionFactory[AnyStr],
11811180
modes = b''
11821181
for mode, mode_value in term_modes.items():
11831182
if mode <= PTY_OP_END or mode >= PTY_OP_RESERVED:
1184-
raise ValueError('Invalid pty mode: %s' % mode)
1183+
raise ValueError(f'Invalid pty mode: {mode}')
11851184

11861185
name = _pty_mode_names.get(mode, str(mode))
11871186
self.logger.debug2(' Mode %s: %d', name, mode_value)
@@ -1439,7 +1438,7 @@ def send_signal(self, signal: Union[str, int]) -> None:
14391438
try:
14401439
signal = _signal_names[signal]
14411440
except KeyError:
1442-
raise ValueError('Unknown signal: %s' % int(signal)) from None
1441+
raise ValueError(f'Unknown signal: {signal}') from None
14431442

14441443
self.logger.info('Sending %s signal', signal)
14451444

asyncssh/config.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,10 @@ def __init__(self, last_config: Optional['SSHConfig'], reload: bool):
7575

7676
self.loaded = False
7777

78-
def _error(self, reason: str, *args: object) -> NoReturn:
78+
def _error(self, reason: str) -> NoReturn:
7979
"""Raise a configuration parsing error"""
8080

81-
raise ConfigParseError('%s line %s: %s' % (self._path, self._line_no,
82-
reason % args))
81+
raise ConfigParseError(f'{self._path} line {self._line_no}: {reason}')
8382

8483
def _match_val(self, match: str) -> object:
8584
"""Return the value to match against in a match condition"""
@@ -116,7 +115,7 @@ def _expand_val(self, value: str) -> str:
116115
elif token == 'i':
117116
raise ConfigParseError('User id not available') from None
118117
else:
119-
raise ConfigParseError('Invalid token substitution: %s' %
118+
raise ConfigParseError('Invalid token substitution: ' +
120119
value[idx+1]) from None
121120

122121
result.append(value[last_idx:])
@@ -141,7 +140,7 @@ def _include(self, option: str, args: List[str]) -> None:
141140
paths = list(path.glob(pattern))
142141

143142
if not paths:
144-
logger.debug1('Config pattern "%s" matched no files', pattern)
143+
logger.debug1(f'Config pattern "{pattern}" matched no files')
145144

146145
for path in paths:
147146
self.parse(path)
@@ -178,7 +177,7 @@ def _match(self, option: str, args: List[str]) -> None:
178177
wild_pat = WildcardPatternList(args.pop(0))
179178
self._matching = wild_pat.matches(match_val)
180179
except IndexError:
181-
self._error('Missing %s match pattern', match)
180+
self._error(f'Missing {match} match pattern')
182181

183182
if not self._matching:
184183
args.clear()
@@ -194,7 +193,7 @@ def _set_bool(self, option: str, args: List[str]) -> None:
194193
elif value_str in ('no', 'false'):
195194
value = False
196195
else:
197-
self._error('Invalid %s boolean value: %s', option, value_str)
196+
self._error(f'Invalid {option} boolean value: {value_str}')
198197

199198
if option not in self._options:
200199
self._options[option] = value
@@ -207,7 +206,7 @@ def _set_int(self, option: str, args: List[str]) -> None:
207206
try:
208207
value = int(value_str)
209208
except ValueError:
210-
self._error('Invalid %s integer value: %s', option, value_str)
209+
self._error(f'Invalid {option} integer value: {value_str}')
211210

212211
if option not in self._options:
213212
self._options[option] = value
@@ -272,7 +271,7 @@ def _set_address_family(self, option: str, args: List[str]) -> None:
272271
elif value_str == 'inet6':
273272
value = socket.AF_INET6
274273
else:
275-
self._error('Invalid %s value: %s', option, value_str)
274+
self._error(f'Invalid {option} value: {value_str}')
276275

277276
if option not in self._options:
278277
self._options[option] = value
@@ -355,12 +354,12 @@ def parse(self, path: Path) -> None:
355354
continue
356355

357356
if not args:
358-
self._error('Missing %s value', option)
357+
self._error(f'Missing {option} value')
359358

360359
handler(self, option, args)
361360

362361
if args:
363-
self._error('Extra data at end: %s', ' '.join(args))
362+
self._error(f'Extra data at end: {" ".join(args)}')
364363

365364
self._set_tokens()
366365

@@ -487,7 +486,7 @@ def _set_request_tty(self, option: str, args: List[str]) -> None:
487486
elif value_str in ('no', 'false'):
488487
value = False
489488
elif value_str not in ('force', 'auto'):
490-
self._error('Invalid %s value: %s', option, value_str)
489+
self._error(f'Invalid {option} value: {value_str}')
491490
else:
492491
value = value_str
493492

0 commit comments

Comments
 (0)