From 2156992a9da153e4af07d0d70a0c35d33d0a5e25 Mon Sep 17 00:00:00 2001 From: Bob Halley Date: Tue, 23 Jul 2024 18:55:56 -0700 Subject: [PATCH] More mostly automated (but reviewed!) f-string conversions. --- dns/dnssec.py | 6 +++--- dns/dnssecalgs/__init__.py | 2 +- dns/exception.py | 2 +- dns/grange.py | 2 +- dns/message.py | 14 +++++++------- dns/rdataset.py | 2 +- dns/rdtypes/ANY/ISDN.py | 2 +- dns/rdtypes/ANY/LOC.py | 6 +++--- dns/rdtypes/ANY/TKEY.py | 2 +- dns/rdtypes/ANY/X25.py | 2 +- dns/rdtypes/CH/A.py | 2 +- dns/rdtypes/IN/NSAP.py | 2 +- dns/rdtypes/euibase.py | 8 ++++---- dns/resolver.py | 4 ++-- dns/set.py | 2 +- dns/tokenizer.py | 2 +- dns/ttl.py | 2 +- dns/win32util.py | 4 ++-- dns/xfr.py | 2 +- dns/zonefile.py | 14 +++++++------- pyproject.toml | 11 +---------- 21 files changed, 42 insertions(+), 51 deletions(-) diff --git a/dns/dnssec.py b/dns/dnssec.py index b6d146dc..9b164775 100644 --- a/dns/dnssec.py +++ b/dns/dnssec.py @@ -224,7 +224,7 @@ def make_ds( if isinstance(algorithm, str): algorithm = DSDigest[algorithm.upper()] except Exception: - raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm) + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') if validating: check = policy.ok_to_validate_ds else: @@ -240,7 +240,7 @@ def make_ds( elif algorithm == DSDigest.SHA384: dshash = hashlib.sha384() else: - raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm) + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') if isinstance(name, str): name = dns.name.from_text(name, origin) @@ -837,7 +837,7 @@ def make_ds_rdataset( if isinstance(algorithm, str): algorithm = DSDigest[algorithm.upper()] except Exception: - raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm) + raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"') _algorithms.add(algorithm) if rdataset.rdtype == dns.rdatatype.CDS: diff --git a/dns/dnssecalgs/__init__.py b/dns/dnssecalgs/__init__.py index 3d9181a7..b017d3e3 100644 --- a/dns/dnssecalgs/__init__.py +++ b/dns/dnssecalgs/__init__.py @@ -59,7 +59,7 @@ def get_algorithm_cls( if cls: return cls raise UnsupportedAlgorithm( - 'algorithm "%s" not supported by dnspython' % Algorithm.to_text(algorithm) + f'algorithm "{Algorithm.to_text(algorithm)}" not supported by dnspython' ) diff --git a/dns/exception.py b/dns/exception.py index 6982373d..223f2d68 100644 --- a/dns/exception.py +++ b/dns/exception.py @@ -81,7 +81,7 @@ class DNSException(Exception): if kwargs: assert ( set(kwargs.keys()) == self.supp_kwargs - ), "following set of keyword args is required: %s" % (self.supp_kwargs) + ), f"following set of keyword args is required: {self.supp_kwargs}" return kwargs def _fmt_kwargs(self, **kwargs): diff --git a/dns/grange.py b/dns/grange.py index 3a52278f..a967ca41 100644 --- a/dns/grange.py +++ b/dns/grange.py @@ -54,7 +54,7 @@ def from_text(text: str) -> Tuple[int, int, int]: elif c.isdigit(): cur += c else: - raise dns.exception.SyntaxError("Could not parse %s" % (c)) + raise dns.exception.SyntaxError(f"Could not parse {c}") if state == 0: raise dns.exception.SyntaxError("no stop value specified") diff --git a/dns/message.py b/dns/message.py index 74a451fc..f322895a 100644 --- a/dns/message.py +++ b/dns/message.py @@ -221,16 +221,16 @@ class Message: s = io.StringIO() s.write("id %d\n" % self.id) - s.write("opcode %s\n" % dns.opcode.to_text(self.opcode())) - s.write("rcode %s\n" % dns.rcode.to_text(self.rcode())) - s.write("flags %s\n" % dns.flags.to_text(self.flags)) + s.write(f"opcode {dns.opcode.to_text(self.opcode())}\n") + s.write(f"rcode {dns.rcode.to_text(self.rcode())}\n") + s.write(f"flags {dns.flags.to_text(self.flags)}\n") if self.edns >= 0: - s.write("edns %s\n" % self.edns) + s.write(f"edns {self.edns}\n") if self.ednsflags != 0: - s.write("eflags %s\n" % dns.flags.edns_to_text(self.ednsflags)) + s.write(f"eflags {dns.flags.edns_to_text(self.ednsflags)}\n") s.write("payload %d\n" % self.payload) for opt in self.options: - s.write("option %s\n" % opt.to_text()) + s.write(f"option {opt.to_text()}\n") for name, which in self._section_enum.__members__.items(): s.write(f";{name}\n") for rrset in self.section_from_number(which): @@ -1213,7 +1213,7 @@ class _WireReader: else: key = self.keyring if key is None: - raise UnknownTSIGKey("key '%s' unknown" % name) + raise UnknownTSIGKey(f"key '{name}' unknown") self.message.keyring = key self.message.tsig_ctx = dns.tsig.validate( self.parser.wire, diff --git a/dns/rdataset.py b/dns/rdataset.py index b5bd40a3..52d2481d 100644 --- a/dns/rdataset.py +++ b/dns/rdataset.py @@ -160,7 +160,7 @@ class Rdataset(dns.set.Set): return s[:100] + "..." return s - return "[%s]" % ", ".join("<%s>" % maybe_truncate(str(rr)) for rr in self) + return "[" + ", ".join(f"<{maybe_truncate(str(rr))}>" for rr in self) + "]" def __repr__(self): if self.covers == 0: diff --git a/dns/rdtypes/ANY/ISDN.py b/dns/rdtypes/ANY/ISDN.py index d2c44ed6..ef8166ff 100644 --- a/dns/rdtypes/ANY/ISDN.py +++ b/dns/rdtypes/ANY/ISDN.py @@ -40,7 +40,7 @@ class ISDN(dns.rdata.Rdata): if self.subaddress: return f'"{dns.rdata._escapify(self.address)}" "{dns.rdata._escapify(self.subaddress)}"' else: - return '"%s"' % dns.rdata._escapify(self.address) + return f'"{dns.rdata._escapify(self.address)}"' @classmethod def from_text( diff --git a/dns/rdtypes/ANY/LOC.py b/dns/rdtypes/ANY/LOC.py index ced5dc03..cf708933 100644 --- a/dns/rdtypes/ANY/LOC.py +++ b/dns/rdtypes/ANY/LOC.py @@ -44,7 +44,7 @@ def _exponent_of(what, desc): exp = i - 1 break if exp is None or exp < 0: - raise dns.exception.SyntaxError("%s value out of bounds" % desc) + raise dns.exception.SyntaxError(f"{desc} value out of bounds") return exp @@ -83,10 +83,10 @@ def _encode_size(what, desc): def _decode_size(what, desc): exponent = what & 0x0F if exponent > 9: - raise dns.exception.FormError("bad %s exponent" % desc) + raise dns.exception.FormError(f"bad {desc} exponent") base = (what & 0xF0) >> 4 if base > 9: - raise dns.exception.FormError("bad %s base" % desc) + raise dns.exception.FormError(f"bad {desc} base") return base * pow(10, exponent) diff --git a/dns/rdtypes/ANY/TKEY.py b/dns/rdtypes/ANY/TKEY.py index 5b490b82..75f62249 100644 --- a/dns/rdtypes/ANY/TKEY.py +++ b/dns/rdtypes/ANY/TKEY.py @@ -69,7 +69,7 @@ class TKEY(dns.rdata.Rdata): dns.rdata._base64ify(self.key, 0), ) if len(self.other) > 0: - text += " %s" % (dns.rdata._base64ify(self.other, 0)) + text += f" {dns.rdata._base64ify(self.other, 0)}" return text diff --git a/dns/rdtypes/ANY/X25.py b/dns/rdtypes/ANY/X25.py index 8375611d..2436ddb6 100644 --- a/dns/rdtypes/ANY/X25.py +++ b/dns/rdtypes/ANY/X25.py @@ -36,7 +36,7 @@ class X25(dns.rdata.Rdata): self.address = self._as_bytes(address, True, 255) def to_text(self, origin=None, relativize=True, **kw): - return '"%s"' % dns.rdata._escapify(self.address) + return f'"{dns.rdata._escapify(self.address)}"' @classmethod def from_text( diff --git a/dns/rdtypes/CH/A.py b/dns/rdtypes/CH/A.py index 583a88ac..832e8d3a 100644 --- a/dns/rdtypes/CH/A.py +++ b/dns/rdtypes/CH/A.py @@ -37,7 +37,7 @@ class A(dns.rdata.Rdata): def to_text(self, origin=None, relativize=True, **kw): domain = self.domain.choose_relativity(origin, relativize) - return "%s %o" % (domain, self.address) + return f"{domain} {self.address:o}" @classmethod def from_text( diff --git a/dns/rdtypes/IN/NSAP.py b/dns/rdtypes/IN/NSAP.py index a4854b3f..d55edb73 100644 --- a/dns/rdtypes/IN/NSAP.py +++ b/dns/rdtypes/IN/NSAP.py @@ -36,7 +36,7 @@ class NSAP(dns.rdata.Rdata): self.address = self._as_bytes(address) def to_text(self, origin=None, relativize=True, **kw): - return "0x%s" % binascii.hexlify(self.address).decode() + return f"0x{binascii.hexlify(self.address).decode()}" @classmethod def from_text( diff --git a/dns/rdtypes/euibase.py b/dns/rdtypes/euibase.py index 751087b4..a39c166b 100644 --- a/dns/rdtypes/euibase.py +++ b/dns/rdtypes/euibase.py @@ -36,7 +36,7 @@ class EUIBase(dns.rdata.Rdata): self.eui = self._as_bytes(eui) if len(self.eui) != self.byte_len: raise dns.exception.FormError( - "EUI%s rdata has to have %s bytes" % (self.byte_len * 8, self.byte_len) + f"EUI{self.byte_len * 8} rdata has to have {self.byte_len} bytes" ) def to_text(self, origin=None, relativize=True, **kw): @@ -49,16 +49,16 @@ class EUIBase(dns.rdata.Rdata): text = tok.get_string() if len(text) != cls.text_len: raise dns.exception.SyntaxError( - "Input text must have %s characters" % cls.text_len + f"Input text must have {cls.text_len} characters" ) for i in range(2, cls.byte_len * 3 - 1, 3): if text[i] != "-": - raise dns.exception.SyntaxError("Dash expected at position %s" % i) + raise dns.exception.SyntaxError(f"Dash expected at position {i}") text = text.replace("-", "") try: data = binascii.unhexlify(text.encode()) except (ValueError, TypeError) as ex: - raise dns.exception.SyntaxError("Hex decoding error: %s" % str(ex)) + raise dns.exception.SyntaxError(f"Hex decoding error: {str(ex)}") return cls(rdclass, rdtype, data) def _to_wire(self, file, compress=None, origin=None, canonicalize=False): diff --git a/dns/resolver.py b/dns/resolver.py index da63eaf8..df19f194 100644 --- a/dns/resolver.py +++ b/dns/resolver.py @@ -162,7 +162,7 @@ class LifetimeTimeout(dns.exception.Timeout): """The resolution lifetime expired.""" msg = "The resolution lifetime expired." - fmt = "%s after {timeout:.3f} seconds: {errors}" % msg[:-1] + fmt = f"{msg[:-1]} after {{timeout:.3f}} seconds: {{errors}}" supp_kwargs = {"timeout", "errors"} # We do this as otherwise mypy complains about unexpected keyword argument @@ -211,7 +211,7 @@ class NoNameservers(dns.exception.DNSException): """ msg = "All nameservers failed to answer the query." - fmt = "%s {query}: {errors}" % msg[:-1] + fmt = f"{msg[:-1]} {{query}}: {{errors}}" supp_kwargs = {"request", "errors"} # We do this as otherwise mypy complains about unexpected keyword argument diff --git a/dns/set.py b/dns/set.py index 04826e2e..ae8f0dd5 100644 --- a/dns/set.py +++ b/dns/set.py @@ -44,7 +44,7 @@ class Set: self.add(item) # lgtm[py/init-calls-subclass] def __repr__(self): - return "dns.set.Set(%s)" % repr(list(self.items.keys())) # pragma: no cover + return f"dns.set.Set({repr(list(self.items.keys()))})" # pragma: no cover def add(self, item): """Add an item to the set.""" diff --git a/dns/tokenizer.py b/dns/tokenizer.py index 454cac4a..ab205bc3 100644 --- a/dns/tokenizer.py +++ b/dns/tokenizer.py @@ -528,7 +528,7 @@ class Tokenizer: if value < 0 or value > 65535: if base == 8: raise dns.exception.SyntaxError( - "%o is not an octal unsigned 16-bit integer" % value + f"{value:o} is not an octal unsigned 16-bit integer" ) else: raise dns.exception.SyntaxError( diff --git a/dns/ttl.py b/dns/ttl.py index 264b0338..b9a99fe3 100644 --- a/dns/ttl.py +++ b/dns/ttl.py @@ -73,7 +73,7 @@ def from_text(text: str) -> int: elif c == "s": total += current else: - raise BadTTL("unknown unit '%s'" % c) + raise BadTTL(f"unknown unit '{c}'") current = 0 need_digit = True if not current == 0: diff --git a/dns/win32util.py b/dns/win32util.py index d92eb2dc..ef1353b5 100644 --- a/dns/win32util.py +++ b/dns/win32util.py @@ -164,7 +164,7 @@ if sys.platform == "win32": lm, r"SYSTEM\CurrentControlSet\Control\Network" r"\{4D36E972-E325-11CE-BFC1-08002BE10318}" - r"\%s\Connection" % guid, + rf"\{guid}\Connection", ) try: @@ -177,7 +177,7 @@ if sys.platform == "win32": raise ValueError # pragma: no cover device_key = winreg.OpenKey( - lm, r"SYSTEM\CurrentControlSet\Enum\%s" % pnp_id + lm, rf"SYSTEM\CurrentControlSet\Enum\{pnp_id}" ) try: diff --git a/dns/xfr.py b/dns/xfr.py index dd247d33..520aa32d 100644 --- a/dns/xfr.py +++ b/dns/xfr.py @@ -33,7 +33,7 @@ class TransferError(dns.exception.DNSException): """A zone transfer response got a non-zero rcode.""" def __init__(self, rcode): - message = "Zone transfer error: %s" % dns.rcode.to_text(rcode) + message = f"Zone transfer error: {dns.rcode.to_text(rcode)}" super().__init__(message) self.rcode = rcode diff --git a/dns/zonefile.py b/dns/zonefile.py index 2bb44a52..873deb1f 100644 --- a/dns/zonefile.py +++ b/dns/zonefile.py @@ -230,7 +230,7 @@ class Reader: try: rdtype = dns.rdatatype.from_text(token.value) except Exception: - raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value) + raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") try: rd = dns.rdata.from_text( @@ -309,9 +309,9 @@ class Reader: width = int(width) if sign not in ["+", "-"]: - raise dns.exception.SyntaxError("invalid offset sign %s" % sign) + raise dns.exception.SyntaxError(f"invalid offset sign {sign}") if base not in ["d", "o", "x", "X", "n", "N"]: - raise dns.exception.SyntaxError("invalid type %s" % base) + raise dns.exception.SyntaxError(f"invalid type {base}") return mod, sign, offset, width, base @@ -375,7 +375,7 @@ class Reader: if not token.is_identifier(): raise dns.exception.SyntaxError except Exception: - raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value) + raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") # rhs (required) rhs = token.value @@ -410,8 +410,8 @@ class Reader: lzfindex = _format_index(lindex, lbase, lwidth) rzfindex = _format_index(rindex, rbase, rwidth) - name = lhs.replace("$%s" % (lmod), lzfindex) - rdata = rhs.replace("$%s" % (rmod), rzfindex) + name = lhs.replace(f"${lmod}", lzfindex) + rdata = rhs.replace(f"${rmod}", rzfindex) self.last_name = dns.name.from_text( name, self.current_origin, self.tok.idna_codec @@ -443,7 +443,7 @@ class Reader: # helpful filename:line info. (ty, va) = sys.exc_info()[:2] raise dns.exception.SyntaxError( - "caught exception %s: %s" % (str(ty), str(va)) + f"caught exception {str(ty)}: {str(va)}" ) self.txn.add(name, ttl, rd) diff --git a/pyproject.toml b/pyproject.toml index 71316241..9de81074 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,16 +104,7 @@ lint.select = [ # isort "I", ] -lint.ignore = [ - "E501", - "E741", - "F401", - "I001", - "SIM102", - "B904", - "B011", - "UP031", -] +lint.ignore = ["E501", "E741", "F401", "I001", "SIM102", "B904", "B011"] lint.exclude = ["tests/*"] [tool.isort] -- 2.47.3