Re:Implementing Rust's dbg! in Python
by dagmx on Friday December 11, 2020 @12:52PM
(#25388532)
Do you have an example of using it in C or C++?
[ Parent
| on HN ]
Re:Implementing Rust's dbg! in Python
by steveklabnik on Friday December 11, 2020 @01:28PM
(#25388922)
There's a few significant differences here. This is a printf that only happens in debug mode; dbg is something that takes an expression, returns that expression, and will print out its filename, line number, and a pretty-printed version of the value.
For an example of how this plays out, I had some code:
let x = y + z;
I wasn't sure what y was, so I was able to let x = dbg!(y) + z;
this is much easier to insert into (and remove from) existing code. Plus, you don't need to write the formatting code.Basically, what you posted is in the same genre of thing, but is very different in a lot of meaningful ways.
Re:Implementing Rust's dbg! in Python
by CJefferson on Friday December 11, 2020 @02:30PM
(#25389713)
After I saw this in Rust, I had to implement it in C++:
#include <iostream>
#include <string>
template<typename T>
T print_dbg(T val, std::string exp, std::string file, int line)
{
std::cerr << exp << " = " << val << " @ " << file << ":" << line << "\n";
return val;
}
#define dbg(x) print_dbg(x,#x,__FILE__,__LINE__)Close. Applying that to
double c = dbg(dbg(a) + dbg(b));
gives a = 1 @ debug.cxx:16
b = 2 @ debug.cxx:16
dbg(a) + dbg(b) = 3 @ debug.cxx:16
which has extra dbg()s on the third line.If I could I would probably want to write
double dbg(c) = dbg(a) + dbg(b);
but that of course doesn't work.You can use dbg inline within an expression!? How did I miss that?
Re:Implementing Rust's dbg! in Python
by steveklabnik on Friday December 11, 2020 @02:57PM
(#25390148)
You can even use it inside itself. I've written
let c = dbg!(dbg!(a) + dbg!(b));
one time...I've written a 3 nested dbg! line for a complex boolean expression... I should have just written a truth table...
Maybe you should write a truth table/source code macro!
Like Steve said, what you're talking about is quite a bit different than what the rust dbg macro does.
Re:Implementing Rust's dbg! in Python
by CyberDildonics on Friday December 11, 2020 @04:22PM
(#25391185)
It isn't really that different, it can just be used in inline expressions. Having the macro do nothing or just evaluating to the expression in debug mode is trivial, since a debug symbol would be defined.