On Thu, Feb 15, 2018 at 11:18 AM, Steven D'Aprano
This idea is inspired by Eric Osborne's post "Extending __format__ method in ipaddress", but I wanted to avoid derailing that thread.
I notice what seems to be an inconsistency in the ipaddress objects:
py> v4 = ipaddress.IPv4Address('1.2.3.4') py> bin(v4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'IPv4Address' object cannot be interpreted as an integer
But that's surely not right: we just need to explicitly do so:
py> bin(int(v4)) '0b1000000100000001100000100'
IP addresses are, in a strong sense, integers: either 32 or 128 bits. And they can be explicitly converted losslessly to and from integers:
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. The __index__ method means "this thing really is an integer, and can be used as an index". With IPv6, similar: you think about them as eight separate blocks of digits. 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 acknowledge one potentially undesirable side-effect: this would allow using IP addresses as indexes into sequences:
py> 'abcdef'[X('0.0.0.2')] 'c'
but while it's weird to do this, I don't think it's logically wrong.
That's not a side effect. That is the *primary* effect of __index__. If you call int() on something, you are *converting* it to an integer (eg int(2.3) ==> 2), and IMO that is the appropriate way to turn 192.168.0.19 into 3232235539 if ever you want that. Unless you have a use-case for using IP addresses as integers, distinct from Eric's ideas? ChrisA