[Python-ideas] Dunder method to make object str-like
Paul Moore
p.f.moore at gmail.com
Fri Apr 8 10:33:16 EDT 2016
On 7 April 2016 at 16:26, M.-A. Lemburg <mal at egenix.com> wrote:
> We have abstract base classes for such tests, but there's nothing
> which would define "string-like" as ABC. Before trying to define
> a test via a special method, I think it's better to define what
> exactly you mean by "string-like".
As a more general point here, if the point is simply to group a set of
types together for use by "user" code (whether application code or 3rd
party libraries) then that's precisely what the ABC machinery is for.
It doesn't require a core change or a PEP or anything other than
agreement between the users of the facility to define an ABC for
*anything*, even something as vague as "string-like" - if all parties
concerned agree that something is "string-like" when it is an instance
of the StringLike ABC, then that's a done deal. You can add a
"to_string()" method to the ABC, which can be as simple as
def to_string(obj):
return str(obj)
and let types for which that's not appropriate override it.
The only real reason for a new "protocol" (a dunder method) is if the
core interpreter or low-level parts of the stdlib need to participate.
In that case, the ABC mechanisms may not be available/appropriate or
may introduce unacceptable overhead (e.g., in something like dict
lookup)
But in general, we have a mechanism for things like this, why are
people inventing home-grown solutions rather than using them? (In the
case of pathlib and __fspath__, it's because of the low-level
implications of adding support to open() and places like importlib -
but that's *also* why the solution should remain focused on the
specific problem, and not become over-generalised).
Paul
More information about the Python-ideas
mailing list