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

Terry Reedy tjreedy at udel.edu
Thu Apr 7 14:48:55 EDT 2016

On 4/7/2016 12:16 PM, Random832 wrote:
> On Thu, Apr 7, 2016, at 11:01, Paul Moore wrote:
>> Someone (lost is quotes)
>>> What's __index__ for?
>> I don't follow. It's for indexing, which requires an integer.
> Sure, but why isn't int() good enough?

Good question. The reason to add __index__ was to allow indexing with 
some things other that ints while not allowing just anything that can be 
converted to int (with or without loss).  The reason for the restriction 
is to prevent subtle bugs.  Expanding the domain of indexing with 
__index__ instead of int() was a judgment call, not a logical necessity.

 > For the same reason you only want
> the kinds of objects that implement __index__ (and not, say, a float or
> a string that happens to be numeric) for indexing, you only want the
> kinds of objects that implement this method for certain purposes.

I understand this, but I am going to challenge the analogy.  An index 
really is a int -- a count of items of the sequence from either end 
(where the right end can be thought of as an invisible End_ofSequence 
item).  A path, on the other hand, is not really a string.  A path is a 
sequence of nodes in the filesystem graph.  Converting structured data, 
in this case paths, to strings, is just a least-common-denominator way 
of communicating structured data between different languages.

To me, the default proposal to expand the domain of open and other path 
functions is to call str on the path arg, either always or as needed. 
We should then ask "why isn't str() good enough"?  Most bad args for 
open will immediately result in a file-not-found exception.  But the 
os.path functions would not.  Do the possible bugs and violation of 
python philosophy out-weigh the simplicity of the proposal?

Terry Jan Reedy

More information about the Python-ideas mailing list