[Python-ideas] Should __builtins__ have some kind of pass-through print function, for debugging?

Ken Hilton kenlhilton at gmail.com
Sat Apr 28 04:33:32 EDT 2018


Perhaps there could be a special magic method that classes could implement
for such a function? I.e. something like this:

    class Pizza(object):
        diameter = 1
        toppings = []
        def __init__(self, diameter=1, toppings=[]):
            self.diameter = diameter
            self.toppings = toppings
        def __str__(self):
            return '{}-inch pizza, toppings: {}'.format(self.diameter, ',
'.join(self.toppings))
        def __repr__(self):
            return '<{}-inch Pizza>'.format(self.diameter)
        def __dprint__(self):
            return '<Pizza: {}>'.format(self.__dict__)

This is just an idea on the side - basically, have a new magic method for
"dprint" (or whatever it should be called) that returns a separate string
form of an object to be debug-printed. So the following example (following
up from the Pizza example):

    def cheesepizza(size):
        return Pizza(size, ['cheese'])
    print(cheesepizza(1))
    print(repr(cheesepizza(1)))
    print(dprint(cheesepizza(1)))

Should produce the following output:

    1-inch pizza, toppings: cheese
    <1-inch Pizza>
    <Pizza: {'toppings': ['cheese'], 'diameter': 1}>
    1-inch pizza, toppings: cheese

Note the last line - remember, dprint passes through the first argument,
printing it in the process. So ``print(dprint(x))`` should first output
``x.__dprint__ + '\n'`` then output ``x.__str__ + '\n'``.
Behavior note: if __dprint__ is not available, fall back to __str__.
Such an extra magic method would be useful if the class should have a
different representation when debugging (i.e. maybe something makes use of
repr(x), but dprint(x) should only be used for debugging so it shows more
information). Also remember that it's totally plausible to simply state

    dprint(cheesepizza(1))

and thereby throw away the return value; such use would be like "print" but
more verbose (again assuming __dprint__ is implemented).

I would also like to ask whether "dprint" should support the same keyword
arguments as "print" - i.e. "end", "file", and so on. IMO it should, as the
only difference is that "dprint" returns its first argument while "print"
returns None.

But what are your thoughts?

Sincerely,
Ken
​ Hilton​
;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180428/d00cb157/attachment-0001.html>


More information about the Python-ideas mailing list