[Python-Dev] cpython: Close #15559: Implementing __index__ creates a nasty interaction with the bytes

Nick Coghlan ncoghlan at gmail.com
Sun Aug 5 15:42:38 CEST 2012


On Sun, Aug 5, 2012 at 11:00 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Sun,  5 Aug 2012 10:20:36 +0200 (CEST)
> nick.coghlan <python-checkins at python.org> wrote:
>
>> http://hg.python.org/cpython/rev/5abea8a43f19
>> changeset:   78426:5abea8a43f19
>> user:        Nick Coghlan <ncoghlan at gmail.com>
>> date:        Sun Aug 05 18:20:17 2012 +1000
>> summary:
>>   Close #15559: Implementing __index__ creates a nasty interaction with the bytes constructor. At least for 3.3, ipaddress objects must now be explicitly converted with int() and thus can't be passed directly to the hex() builtin.

I noticed this when I tried
"bytes(ipaddress.Ipv4Address('192.168.0.1')" Apparently allocating and
initialising a 3.2 GB array on an ASUS Zenbook consumes large amounts
of time and makes the X server rather unresponsive. Even
faulthandler's timeout thread took more than ten times the specified
timeout to actually kill the operation. Who knew? :)

> __index__, as the name implies, allows instances to be used as sequence
> indices, which does sound like a weird thing to serve as for an IP
> address :-)

I expect the original reasoning had to do with the hex() builtin. In
2.x you could selectively support that by implementing __hex__
directly. In 3.x, the __oct__ and __hex__ methods are gone and the
only way to support those builtins (as well as bin()) is by
implementing __index__ instead. However, implementing __index__ makes
the type usable in a whole host of other contexts as well, so the
naive __hex__ -> __index__ conversion really wasn't a good idea.

I'm thinking it may make sense to eventually implement __bytes__, as
having bytes(address) be equivalent to address.packed *does* make
sense. No hurry on that, though.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list