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. As far as discoverability by 
beginners, I think that having their instructor teach them to write such 
a simple helper would be a good lesson.

But suppose we were willing to add a bit of compiler magic to the 
language, something that would be hard to do in pure Python: give dp() 
access to the source code of the argument it is called with, and then 
print out that source as well as the value's repr, plus the line number 
and name of the module it is called from.

An example:

    # module.py
    x = 1
    y = dp(x + 99)+2
    print("y is", y)


Then running that module would output:

    Line 2 of module.py, "x + 99", result 100
    y is 102


Compare that to the pretty anaemic output of the dp() helper you give:

    100
    y is 102

I know which I would rather see when debugging.

Obviously dp() would have to be magic. There's no way that I know of for 
a Python function to see the source code of its own arguments. I have no 
idea what sort of deep voodoo would be required to make this work. But 
if it could work, wow, that would really be useful. And not just for 
beginners.


Some objections... 


Objection 1: dp() looks like an ordinary function call. Magic in Python 
is usually a statement, like assert.

Answer: Very true. But on the other hand, there's super() inside 
classes.


Objection 2: Yes, but even super() isn't this magical.

Answer: Details, details. I'm just the ideas man, somebody else can work 
out the implementation... *wink*


Objection 3: What if the caller has shadowed or replaced dp()?

Answer: Don't do that. Let's make dp() a reserved name.


Objection 4: You're kidding, right? That needs a full deprecation cycle, 
it will break code, etc.

Answer: Okay, okay. Maybe the compiler could be smart enough to only 
pass the extra information on (line number, module, source code of 
argument) when dp() is the actual genuine builtin dp() function, and not 
if it has been shadowed.


Objection 5: Even if there is a way to do that, it would require an 
expensive runtime check that will slow down calls to anything called 
dp().

Answer: Yes, but that's only one name out of millions. All other 
function calls will be unaffected. And besides, performance regressions 
don't count as breakage. Much.



Yeah, I don't think this is going to fly either. But boy would it be 
useful if it could...



-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to