]> git.ipfire.org Git - thirdparty/dnspython.git/commitdiff
More mostly automated (but reviewed!) f-string conversions.
authorBob Halley <halley@dnspython.org>
Wed, 24 Jul 2024 01:55:56 +0000 (18:55 -0700)
committerBob Halley <halley@dnspython.org>
Wed, 24 Jul 2024 01:55:56 +0000 (18:55 -0700)
21 files changed:
dns/dnssec.py
dns/dnssecalgs/__init__.py
dns/exception.py
dns/grange.py
dns/message.py
dns/rdataset.py
dns/rdtypes/ANY/ISDN.py
dns/rdtypes/ANY/LOC.py
dns/rdtypes/ANY/TKEY.py
dns/rdtypes/ANY/X25.py
dns/rdtypes/CH/A.py
dns/rdtypes/IN/NSAP.py
dns/rdtypes/euibase.py
dns/resolver.py
dns/set.py
dns/tokenizer.py
dns/ttl.py
dns/win32util.py
dns/xfr.py
dns/zonefile.py
pyproject.toml

index b6d146dc0fd613772fef5ddd6cb88dd1058250c9..9b1647753fe0c53779cef875be32f220b7952ced 100644 (file)
@@ -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:
index 3d9181a761c0f67213858cc9b2c573a562ca406f..b017d3e3fd6f67c9841132c5a8f3c854a8ad0941 100644 (file)
@@ -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'
     )
 
 
index 6982373de2a872057ca1fda3a2a752ff8d566355..223f2d68797aaab53009641c2a700b9df411c8b6 100644 (file)
@@ -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):
index 3a52278febf1302462e24ca5ece733492b55f096..a967ca41c63ac99d237619d884da4f1b5d0bc21e 100644 (file)
@@ -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")
index 74a451fc30baef8d471e6fe3ce6881425cedd9e0..f322895ae1358760142721a7420a1ef74b78f6ae 100644 (file)
@@ -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,
index b5bd40a3043507d3527b1b9b9e3dd6997d03a64d..52d2481d68371e204ccfd2669ab29e5d1058a7d1 100644 (file)
@@ -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:
index d2c44ed60e722cc81e28db4ba7df25dad1ff3821..ef8166ffbd4b85af8016ac7ae568b6be567555e3 100644 (file)
@@ -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(
index ced5dc0360edc4cb0461d47c4ed7ad4b0fd2b012..cf70893315083826c0ff9f510e4c4a8256871de9 100644 (file)
@@ -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)
 
 
index 5b490b82cde9d17013b8ce78a5e8d0e27946ccb2..75f62249e1daf7961370349752215fd367ed8b29 100644 (file)
@@ -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
 
index 8375611d25867047b6b4cf92ed30bef4b4109202..2436ddb62ec23d52a69c092e1194b599618681f8 100644 (file)
@@ -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(
index 583a88ac6119126652868c5c33f93055687fec42..832e8d3a5b86c3badce75c98833636b1f2ef4ba7 100644 (file)
@@ -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(
index a4854b3fa117109e05dab3921e01b6e096c57f51..d55edb7372afb143c72665775a3755a202969fc7 100644 (file)
@@ -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(
index 751087b4748cf1dd8745a227f970290e10b8b65f..a39c166b98fe2973fc64835c1209c12417535079 100644 (file)
@@ -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):
index da63eaf87e8d7a4f42002ec76fb0b3fa22b02550..df19f19495c1c296969dae0d8b91eef2c791737c 100644 (file)
@@ -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
index 04826e2e6ef93069ad37ec0c44a1a0ae0d272567..ae8f0dd5039693a24a14bf9cff638ee740798a07 100644 (file)
@@ -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."""
index 454cac4a85e609d3429df45cbdfcb4103bd19213..ab205bc39af26fba21255dc0e5cb124ddba0b10b 100644 (file)
@@ -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(
index 264b0338b64e827a2078ebb0edac7daf1a49cd0c..b9a99fe3c2246ba13e9a9d27b7f0c79cf2c1afce 100644 (file)
@@ -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:
index d92eb2dca385dae596399a10525c5d8f75afbe8a..ef1353b55e616436c0a655d0f60c0e3387018ad6 100644 (file)
@@ -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:
index dd247d33db4b6e827e5c540cf0e23965b0b0e10b..520aa32ddc32ea50b090ff4b08b9450709a5fb93 100644 (file)
@@ -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
 
index 2bb44a524b77916db087e4a4e9ef4344b3477570..873deb1f84a303eccc3fb32c5802f53847333a1a 100644 (file)
@@ -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)
index 71316241cfdf1f71c277a01a3d22d3f0dc6d48f0..9de8107481d5dbce8e84426cf80420d06daa674b 100644 (file)
@@ -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]