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('220.127.116.11') 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:
py> v4 == ipaddress.IPv4Address(int(v4)) True
Is there a good reason not to give them an __index__ method so that bin(), oct() and hex() will work directly?
py> class X(ipaddress.IPv4Address): ... def __index__(self): ... return int(self) ... py> a = X('18.104.22.168') py> bin(a) '0b1000000100000001100000100'
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.