[Python-ideas] Give ipaddresses an __index__ method

Steven D'Aprano steve at pearwood.info
Wed Feb 14 23:14:03 EST 2018


On Thu, Feb 15, 2018 at 11:45:46AM +1100, Chris Angelico wrote:

> Except that this computer's IPv4 is not 3232235539, and I never want
> to enter it that way. I enter it as 192.168.0.19 - as four separate
> integers.

That's partly convention (and a useful convention: it is less error- 
prone than 3232235539) and partly that because you're a sys admin who 
can read the individual subfields of an IP address. I'm not suggesting 
you ought to change your habit.

But to civilians, 192.168.0.19 is as opaque as 3232235539 or 0xC0A80013 
would be.

We allow creating IP address objects from a single int, we don't require 
four separate int arguments (one for each subfield), and unless I've 
missed something, IP addresses are not treated as a collection of four 
separate integers (or more for v6). I can't even find a method to split 
an address into four ints. (Nor am I sure that there is good reason to 
want to do so.) So calling a single address "four separate integers" is 
not really accurate.


[...]
> IP addresses can be losslessly converted to and from strings, too, and
> that's a lot more useful. But they still don't have string methods,
> because they're not strings.

I agree they're not strings, I never suggested they were. Python only 
allows IP addresses to be entered as strings because we don't have a 
"dotted-quad" syntax for 32-bit integers. (Nor am I suggesting we 
should.)

It is meaningless to perform string operations on IP addresses. What 
would it mean to call addr.replace('.', 'Z') or addr.split('2')?

But doing *at least some* int operations on addresses isn't meaningless:

py> a = ipaddress.ip_address('192.168.0.19')
py> a + 1
IPv4Address('192.168.0.20')



-- 
Steve


More information about the Python-ideas mailing list