Skip to content

gh-153769: Clarify the TypeError from ipaddress subnet_of()/supernet_of()#154147

Open
fedonman wants to merge 1 commit into
python:mainfrom
fedonman:fix-gh-153769-ipaddress-subnet-of-typeerror
Open

gh-153769: Clarify the TypeError from ipaddress subnet_of()/supernet_of()#154147
fedonman wants to merge 1 commit into
python:mainfrom
fedonman:fix-gh-153769-ipaddress-subnet-of-typeerror

Conversation

@fedonman

Copy link
Copy Markdown
Contributor

Calling subnet_of() or supernet_of() on a network and passing something that is not a network object, such as an address, gives a confusing error today:

>>> import ipaddress
>>> ipaddress.IPv6Network('::/0').subnet_of(ipaddress.IPv6Address('::1'))
AttributeError: 'IPv6Address' object has no attribute 'network_address'

During handling of the above exception, another exception occurred:

TypeError: Unable to test subnet containment between ::/0 and ::1

An address has a version attribute, so the version check passes, and the code then reaches for network_address, which the address does not have. The AttributeError is caught and re-raised as a TypeError whose message reads like a real containment result and hides what actually went wrong.

This checks that both arguments are network objects before touching any attributes, and raises a clear TypeError that says a network object is required. Nothing masks an internal AttributeError anymore:

>>> ipaddress.IPv6Network('::/0').subnet_of(ipaddress.IPv6Address('::1'))
TypeError: Unable to test subnet containment between ::/0 and ::1: both must be network objects

The existing behaviour for valid networks and for the mixed IPv4/IPv6 case is unchanged.

…ernet_of()

Passing something that is not a network object, such as an address, to
IPv4Network.subnet_of() or supernet_of() made _is_subnet_of() reach for
the network_address attribute, fail with an AttributeError, and turn that
into a TypeError with a message that read like a real containment result
and hid the actual cause.

Check that both arguments are network objects up front and raise a clear
TypeError explaining what is required, so nothing masks an internal
AttributeError anymore.
@python-cla-bot

python-cla-bot Bot commented Jul 19, 2026

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant