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

M.-A. Lemburg mal at egenix.com
Thu Apr 7 14:42:46 EDT 2016


On 07.04.2016 18:46, Chris Angelico wrote:
> On Fri, Apr 8, 2016 at 2:27 AM, M.-A. Lemburg <mal at egenix.com> wrote:
>> Not necessarily. In fact, a string.String ABC could have only
>> a single method: .__str__() defined.
> 
> That wouldn't be very useful; object.__str__ exists and is functional,
> so EVERY object would count as a string.

No, only those objects that register with the ABC would be considered
string-like, not all objects implementing the .__str__() method.
In regular Python, only str() objects would register with
strings.String.

Path objects could also register to be treated as "string-like"
object.

Just like numeric types are only considered part of the ABCs
under numbers, if they register with these.

Perhaps the name strings.String sounds confusing, so
perhaps strings.StringLike or strings.FineToConvertToAStringIfNeeded
would be better :-)

> The point of "string-like" is that it can be treated as a string, not
> just that it can be converted to one. This is exactly parallel to the
> difference between __index__ and __int__; floats can be converted to
> int (and will truncate), but cannot be *treated* as ints.

Right, and that's what you can define via an ABC. Those abstract
base classes are not to be confused with introspecting methods
on objects - they help optimize this kind of test, but most
importantly help express the combination of providing an interface
by exposing methods with the semantics of how those
methods are expected to be used.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Apr 07 2016)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...           http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...           http://zope.egenix.com/
________________________________________________________________________

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/
                      http://www.malemburg.com/



More information about the Python-ideas mailing list