Add methods in IPv4Address and IPv6Address to return IPv4Interface and IPv6Interface instances

Currently there does not seem to be a native way to add netmask/prefixlen to an IPv4Address/IPv6Address object to create an interface object.

I’m proposing adding with_prefixlen() and with_netmask() methods (or similar) for returning the corresponding IPv4Interface/IPv6Interface object.

Example:

>>> ip = ipaddress.IPv4Address("10.1.2.3")
>>> 
>>> ip.with_prefixlen(24)
IPv4Interface('10.1.2.3/24')
>>>

Currently this is maybe the easiest option for getting the interface object:

>>> ipaddress.IPv4Interface(f"{ip}/24")
IPv4Interface('10.1.2.3/24')
>>>

The IP interface constructors accept address + prefixlen-or-netmask 2-tuples the same way the network constructors do:

>>> import ipaddress
>>> ip = ipaddress.IPv4Address("10.1.2.3")
>>> ip
IPv4Address('10.1.2.3')
>>> ipaddress.IPv4Interface((ip, 24))
IPv4Interface('10.1.2.3/24')
>>> ipaddress.IPv4Interface((ip, "255.255.255.0"))
IPv4Interface('10.1.2.3/24')

It’s not immediately obvious in the documentation as the details of the accepted input types are in the network constructor docs, while the address constructor docs just link to the network constructor docs.

1 Like

Thank you! Your reply brought a big aha-moment to me! Never realized the tuple constructor syntax, I see it was introduced already in 3.5.

2 Likes