[Python-Dev] Semantics of __int__(), __index__()

Hrvoje Niksic hrvoje.niksic at avl.com
Thu Apr 4 11:39:35 CEST 2013


Eric Snow:
> On Wed, Apr 3, 2013 at 6:47 AM, Hrvoje Niksic <hrvoje.niksic at avl.com> wrote:
>> It seems like a good feature that an __int__ implementation can choose to
>> return an int subclass with additional (and optional) information. After
>> all, int subclass instances should be usable everywhere where ints are,
>> including in C code.
>
> Unless you want to try to use the concrete C-API in CPython.  In my
> experience the concrete API is not very subclass friendly.

Nick:
 > Using it with subclasses is an outright bug (except as part of
 > a subclass implementation).

This is true for mutable objects like dicts and lists where calling 
things like PyDict_SetItem will happily circumvent the object.

But for ints and floats, all that the C code really cares about is the 
object's intrinsic value as returned by PyLong_AS_LONG and friends, 
which is constant and unchangeable by subclasses.

The typical reason to subclass int is to add more information or new 
methods on the instance, not to break basic arithmetic. Doing anything 
else breaks subtitutability and is well outside the realm of "consenting 
adults". Someone who wants to change basic arithmetic is free to 
implement an independent int type.

Hrvoje



More information about the Python-Dev mailing list