Please translate this easy snip of C++ to Python

Peter Hansen peter at engcorp.com
Mon Feb 5 00:37:08 EST 2001


Fredrik Lundh wrote:
> 
> "Phlip" <phlip_cpp at my-deja.com> wrote:
> > Ogle this awesome snip of C++:
> >
> >         #define TRACE_(x) cout << #x ": " << x << endl
> 
> > How do I do that, just as easy to call, in Python?
> 
> Or use something like this:
> 
[code snippet snipped]
> 
> Cheers /F

If I may humbly offer a small change which even handles 
something like the original __LINE__ request, I believe:

def trace(expr = None):
    # evaluate expression in callers namespace
    import sys
    try:
        raise None
    except:
        frame = sys.exc_info()[2].tb_frame.f_back
    if expr != None:
        print expr, ":", eval(expr, frame.f_globals, frame.f_locals)
    else:
        print '__LINE__ :', frame.f_lineno

x = 10
y = 20
strAnimals = "Lemmings"

trace("x + y")
trace("strAnimals")
trace()

## prints:
## x + y : 30
## strAnimals : Lemmings
## __LINE__ : 19



More information about the Python-list mailing list