diff --git a/Lib/ipaddress.py b/Lib/ipaddress.py index 3421c9f40ce843..b9c9d52a257b3a 100644 --- a/Lib/ipaddress.py +++ b/Lib/ipaddress.py @@ -1954,21 +1954,22 @@ def _explode_shorthand_ip_string(self): """ if isinstance(self, IPv6Network): - ip_str = str(self.network_address) - elif isinstance(self, IPv6Interface): - ip_str = str(self.ip) + ip_int = self.network_address._ip + scope_id = self.network_address._scope_id else: - ip_str = self._string_from_ip_int(self._ip) - - ip_int = self._ip_int_from_string(ip_str) - hex_str = '%032x' % ip_int - exploded = ':'.join([hex_str[x:x+4] for x in range(0, 32, 4)]) - if isinstance(self, _BaseNetwork): - return '%s/%d' % (exploded, self._prefixlen) - if self._scope_id: - exploded = '%s%%%s' % (exploded, self._scope_id) - if isinstance(self, IPv6Interface): - return '%s/%d' % (exploded, self._prefixlen) + ip_int = self._ip + scope_id = self._scope_id + + exploded = ( + f'{ip_int >> 112:04x}:{(ip_int >> 96) & 0xFFFF:04x}:' + f'{(ip_int >> 80) & 0xFFFF:04x}:{(ip_int >> 64) & 0xFFFF:04x}:' + f'{(ip_int >> 48) & 0xFFFF:04x}:{(ip_int >> 32) & 0xFFFF:04x}:' + f'{(ip_int >> 16) & 0xFFFF:04x}:{ip_int & 0xFFFF:04x}' + ) + if scope_id: + exploded = f'{exploded}%{scope_id}' + if isinstance(self, (_BaseNetwork, IPv6Interface)): + return f'{exploded}/{self._prefixlen}' return exploded def _reverse_pointer(self): diff --git a/Lib/test/test_ipaddress.py b/Lib/test/test_ipaddress.py index 4b398c1f41ef60..1796e5adfaf9be 100644 --- a/Lib/test/test_ipaddress.py +++ b/Lib/test/test_ipaddress.py @@ -2807,6 +2807,10 @@ def testExplodeShortHandIpStr(self): ipaddress.IPv6Address('fe80::1%eth0').exploded) self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0001%1/64', ipaddress.IPv6Interface('fe80::1%1/64').exploded) + self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0000%eth0/64', + ipaddress.IPv6Network('fe80::%eth0/64').exploded) + self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0000%1/64', + ipaddress.IPv6Network('fe80::%1/64').exploded) # issue 77 self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1', addr2.exploded) diff --git a/Misc/NEWS.d/next/Library/2026-11-26-20-50-00.gh-issue-161384.ip6exp.rst b/Misc/NEWS.d/next/Library/2026-11-26-20-50-00.gh-issue-161384.ip6exp.rst new file mode 100644 index 00000000000000..404fdf7b0a5cd9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-26-20-50-00.gh-issue-161384.ip6exp.rst @@ -0,0 +1,2 @@ +Fix :attr:`ipaddress.IPv6Network.exploded` for networks with a scope ID and +avoid redundant string round-tripping in ``_BaseV6._explode_shorthand_ip_string()``.