Skip to content

Commit b72a0ef

Browse files
committed
Only improve the message, keep the AttributeError handler
An isinstance() check on _BaseNetwork rejects a network-like object that is not a subclass, which works today. Keeping the handler and suppressing the context keeps that working and still gives the caller one clear error.
1 parent d79f302 commit b72a0ef

3 files changed

Lines changed: 15 additions & 15 deletions

File tree

Lib/ipaddress.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,14 +1026,16 @@ def is_multicast(self):
10261026

10271027
@staticmethod
10281028
def _is_subnet_of(a, b):
1029-
if not (isinstance(a, _BaseNetwork) and isinstance(b, _BaseNetwork)):
1030-
raise TypeError(f"Unable to test subnet containment between "
1031-
f"{a} and {b}: both must be network objects")
1032-
# Always false if one is v4 and the other is v6.
1033-
if a.version != b.version:
1034-
raise TypeError(f"{a} and {b} are not of the same version")
1035-
return (b.network_address <= a.network_address and
1036-
b.broadcast_address >= a.broadcast_address)
1029+
try:
1030+
# Always false if one is v4 and the other is v6.
1031+
if a.version != b.version:
1032+
raise TypeError(f"{a} and {b} are not of the same version")
1033+
return (b.network_address <= a.network_address and
1034+
b.broadcast_address >= a.broadcast_address)
1035+
except AttributeError:
1036+
raise TypeError(
1037+
f"Unable to test subnet containment between {a} and {b}: "
1038+
f"both must be network objects") from None
10371039

10381040
def subnet_of(self, other):
10391041
"""Return True if this network is a subnet of other."""

Lib/test/test_ipaddress.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -733,9 +733,8 @@ def test_subnet_of_non_network(self):
733733
with self.assertRaises(TypeError) as cm:
734734
method(other)
735735
self.assertIn('network', str(cm.exception))
736-
# The error should not be a swallowed AttributeError.
737-
self.assertNotIsInstance(cm.exception.__context__,
738-
AttributeError)
736+
# The internal AttributeError is not shown to the caller.
737+
self.assertTrue(cm.exception.__suppress_context__)
739738

740739

741740
class NetmaskTestMixin_v6(CommonTestMixin_v6):
Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
:meth:`~ipaddress.IPv4Network.subnet_of` and
2-
:meth:`~ipaddress.IPv4Network.supernet_of` now raise a clear
3-
:exc:`TypeError` when passed an argument that is not a network object,
4-
such as an address, instead of a confusing error that masked an internal
5-
:exc:`AttributeError`.
2+
:meth:`~ipaddress.IPv4Network.supernet_of` now say that both arguments must be
3+
network objects when passed something else, such as an address, and no longer
4+
show the internal :exc:`AttributeError` behind it.

0 commit comments

Comments
 (0)