[Python-ideas] Dunder method to make object str-like

Chris Angelico rosuav at gmail.com
Thu Apr 7 15:10:33 EDT 2016


On Fri, Apr 8, 2016 at 5:06 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 4/7/2016 11:03 AM, Ethan Furman wrote:
>>
>> On 04/07/2016 07:07 AM, Random832 wrote:
>>
>>> What's __index__ for?
>>
>>
>> __index__ is a way to get an int from an int-like object without losing
>> information; so it fails with values like 3.4, but should succeed with
>> values like Fraction(4, 2).
>>
>> __int__ is a way to convert the value to an int, so 3.4 becomes 3 (and
>> and the 4/10's is lost).
>
>
> Why is that a problem?  Loss is not the issue.  And as someone else pointed
> out, int('4') does not lose information, but seq['1'] is prohibited.  Why is
> passing integer strings as indexes bad?
>
> The answer to the latter, I believe, is that Guido is against treating
> numbers and string representations of numbers as interchangable.  And the
> answer to both, I believe, is that the downside of flexibility is ease of
> creating buggy code, especially code where bugs do not immediately raise
> something, or ease of creating confusing code that is hard to maintain.

Hence my wording of "string-like". Anything can be converted to a
string, but only certain objects are sufficiently string-like to be
implicitly treated as strings. But ultimately it's all the same
concept.

ChrisA


More information about the Python-ideas mailing list