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

Émanuel Barry vgr255 at live.ca
Thu Apr 7 09:46:52 EDT 2016


+1 for me.

On Thu, Apr 07, 2016 at 11:04:56PM +1000, Chris Angelico <rosuav at gmail.com>
wrote:
> 1) What should the dunder method be named? __str_coerce__? __stringlike__?

The equivalent for ints is __index__, which is one subset of the vast
possibilities of integers, yet one that will mostly be served by int-like
objects.
By that reasoning, the str-like method should correspond to a large - yet
wide - use case. The first use case for strings that comes to mind is dict
(namespace) keys. I'd rule out __keys__ as not explicit enough. I was
thinking __item__, but then again probably not explicit enough. I don't have
"the obvious choice" in mind, but I'd like to be one word only.

> 2) Which standard types are sufficiently string-like to be used thus?

No built-in types, but I'd like the feature for a third-party app, for
example, that pretends to be a string.

> 3) Should there be a bytes equivalent?

This would probably fall in the "nice to have, but no use case backing it
up" category. +0 for me.

> 4) Should there be a format string "coerce to str"? "{}".format(x) is
equivalent to str(x), but it might be nice to be able to assert that
something's stringish already.

__index__ is meant to return the same thing as __int__, and I think the same
restrictions should apply here - we have an object pretending to be a
string, so there should *not* be a difference between use_as_string(obj) and
use_as_string(str(obj)) - in the same sense that there should not be a
difference between use_as_int(obj) and use_as_int(int(obj)).

-Emanuel


More information about the Python-ideas mailing list