On 3/16/2020 1:15 PM, Steve Jorgensen wrote:
Steve Jorgensen wrote:
Based on the conversations stemming from my previous post, it is clear that the
topic
was too implementation-specific. It is not clear whether dunder methods are an
appropriate
component of the solution (they might or might not be).
Also, it presumably makes sense to start by looking at prior art rather than
inventing
from scratch.
There has been some argument regarding whether objects should say how to present
themselves "prettily". I think a case can be made either way, but in either
case, it makes sense that it should be easy to override the representation for an object
type without subclassing or monkey-patching it. Also, it might make sense not to clutter
up the dunder-method space for all kinds of objects with this kind of thing.
This is exactly what singledispatch is designed for:
https://www.python.org/dev/peps/pep-0443/
Without using dunder methods, it could still be possible for any body of code
to provide default special-representational rules for its objects by
registering hooks. Also, as a hybrid-approach, it could be that the defaults
for representation are determined first by looking at a default registry and
then falling back to dunder methods if present.
Which a singledispatch default handler could do.
==========================
from functools import singledispatch
@singledispatch
def pretty(arg):
try:
fn = arg.pretty
except AttributeError:
return f"pretty default {arg}"
return fn()
@pretty.register(int)
def _(arg):
return f"pretty int {arg}"
class HasPretty:
def pretty(self):
return "custom pretty function"
print(pretty(1))
print(pretty(object))
print(pretty('a string'))
print(pretty(HasPretty()))
==========================
produces:
==========================
pretty int 1
pretty default <class 'object'>
pretty default 'a string'
custom pretty function
==========================
Just add arguments if desired and change the names as necessary.
Eric
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/OSXRHTEAH6ZKQGNPW5QU2S5OE7D7LU6S/
Code of Conduct: http://python.org/psf/codeofconduct/