[Python-Dev] Semantics of __int__(), __index__()
larry at hastings.org
Fri Apr 5 06:26:43 CEST 2013
On 04/03/2013 09:04 AM, Steven D'Aprano wrote:
> On 04/04/13 01:16, Barry Warsaw wrote:
>> It's analogous to all
>> the other built-in types-as-functions, so int() calls __int__() which
>> return a concrete integer.
> Why must it? I think that's the claim which must be justified, not
> just taken
> as a given.
Principle Of Least Surprise. My observation of the thread is that the
majority of people feel "of course __int__ needs to return a real int".
People are surprised that you can return subclasses. Nick thought there
was an explicit check to prevent it!
Why is this so surprising? I think it's because int, str, and float are
all classes. Therefore, as callables they are constructors. When you
call a constructor, you expect to get an instance of that specific
class. Yes, it's always been possible with new-style classes to return
a subclass from the constructor. But calling a constructor and getting
a subclass is always surprising behavior.
Also, permitting subclasses means the interface becomes conceptually far
more complicated. We would need to restrict it to subclasses that don't
hijack the representation. It's plausible, for example, to write a
subclass of str that uses a novel approach for storing the string data,
say as a rope. It could overload all the magic methods and behave
identically to a str in every important way. But if its __str__
returned self instead of a real str object, that means that
PyUnicode_AS_UNICODE would blissfully return the bypassed internal
string value, whatever it is, and Python breaks. So we can't enforce it
programmatically, we'd need to document it as convention. But
explaining that is complicated, and If The Implementation Is Hard To
Explain, It's A Bad Idea.
> When we call n = int(something), what's the use-case for caring that n
> is an
> instance of built-in int but not of a subclass, and is that use-case so
> compelling that it must be enforced for all uses of int() etc.?
I'm much more interested in your counter use-case. When is it appealing
or necessary to you to return a subclass of int from __int__()? In your
postings so far you've said that this makes sense to you, but you
haven't said why you need it.
In lieu of a compelling use case, my vote is firmly against surprise and
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-Dev