Please translate this easy snip of C++ to Python
Fredrik Lundh
fredrik at effbot.org
Sun Feb 4 15:24:01 EST 2001
"Phlip" <phlip_cpp at my-deja.com> wrote:
> Ogle this awesome snip of C++:
>
> #define TRACE_(x) cout << #x ": " << x << endl
That's a preprocessor trick, not a C++ trick. Replace <<
with printf, and it works just as fine under C.
(iirc, bjarne thinks that real C++ programmers shouldn't
use the preprocessor at all, but what does he know...)
> How do I do that, just as easy to call, in Python?
Run your Python code through C's preprocessor?
Or use something like this:
def trace(expr):
# evaluate expression in callers namespace
import sys
try:
raise None
except:
frame = sys.exc_info()[2].tb_frame.f_back
print expr, "=", eval(expr, frame.f_globals, frame.f_locals)
x = 10
y = 20
trace("x + y")
## prints:
## x + y = 30
Cheers /F
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list