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

Steven D'Aprano steve at pearwood.info
Fri Apr 5 04:04:03 CEST 2013


On 05/04/13 01:23, Oscar Benjamin wrote:

> The reason for calling int(obj) is to get an object that is precisely
> of type int. When I call this I do not want any modified or additional
> methods or data attached to the resulting object.

When I call int(), I'm expecting an int. That includes well-behaved subclasses of int that continue to behave like ints in all the ways that matter.

It's curious to see the (d)evolution of thinking on type checking in Python circles. Once upon a time, type checking was discouraged, duck-typing was encouraged, and the philosophy was that an int is anything that behaves like an int. Now type-checking is tolerated or even encouraged, provided that you use isinstance, and an int is anything that inherits from the builtin (or the ABC). And this proposed change in behaviour continues the move away from Python's former emphasis on duck-typing. Now an int is only the builtin.

Oscar, a question: what harm does it do to you if the int you receive has additional methods or data attached? I can appreciate Guido's concern that (say) a subclass might mess with the repr of the number, and he doesn't want that. (I don't find that argument compelling, but it does make sense.) But I don't understand why you would care if the int you receive happens to have an additional method or data that you don't expect.



[...]
> I think it's fair to
> say that there are times when someone wants an object that is
> precisely of type int. They should be able to rely on int(obj)
> returning an int or raising an error.

The first part of that is correct, but I disagree on the second. The 90-10 rule applies here. 90% of the time, we shouldn't care whether we receive an actual builtin int, only that we receive something that quacks like an int. In practice, that generally means something that inherits from int. IMO, int() and __int__ should support the common case, and not enforce the uncommon case


> This is true similarly for __index__.

I have no argument with the idea that __index__ should guarantee to return a builtin int. I thought it already did make that guarantee.




-- 
Steven


More information about the Python-Dev mailing list