[Python-ideas] Give ipaddresses an __index__ method

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


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:

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('1.2.3.4')
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.


-- 
Steve


More information about the Python-ideas mailing list