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

Steven D'Aprano steve at pearwood.info
Fri Apr 27 09:05:02 EDT 2018


Actually, I think I can think of a way to make this work, if we're 
willing to resurrect some old syntax.

On Fri, Apr 27, 2018 at 09:27:34PM +1000, Steven D'Aprano wrote:
> I think that this is either a great idea or pointless, depending on what 
> the built-in actually does.
> 
> If all it does is literally the debug print function you give:
> 
> > # "debug print": prints and then returns its argument
> > def dp(obj):
> >     print(repr(obj))
> >     return obj
> 
> then it is just a trivial helper as you say, and in my opinion too 
> trivial to bother making a builtin.

I changed my mind... let's add this as a builtin, under the name 
debugprint. It is a completely normal, non-magical function, which takes 
four (not one) arguments:


def debugprint(obj, lineno=None, module=None, source=None):
    out = []
    if module is not None:
        if lineno is None:
            lineno = "?"
        out.append(f"Line {lineno} of {module}")
    if source is not None:
        out.append(ascii(source))
    out.append(f"result {repr(obj)}")
    print(', '.join(out))
    return obj


Now let's put all the magic into some syntax. I'm going to suggest 
resurrecting the `` backtick syntax from Python 2. If that's not 
visually distinct enough, we could double them: ``expression``.

When the compiler sees an expression inside backticks, it grabs the name 
of the module, the line number, and the expression source, and compiles 
a call to:

    debugprint(expression, lineno, module, source)

in its place. That's the only magic needed, and since it is entirely at 
compile-time, all that information should be easily available. (I hope.) 
If not, then simply replace the missing values with None.

If the caller shadows debugprint, it is their responsibility to either 
give it the correct signature, or not to use the backticks. Since it's 
just a normal function call, the worst that happens is that a mismatch 
in arguments gives you a TypeError.

Shadowing debugprint would be an easy way to disable backticks on a 
per-module basis, at runtime. Simply define:

def debugprint(obj, *args):
    return obj

and Bob's yer uncle.



-- 
Steve


More information about the Python-ideas mailing list