How to log a variable's name and value?

If the tool you need is only for developing and debugging, there's a useful package calle q.

It has been submitted to pypi, it can be installed with pip install q or easy_install q.

import q; q(foo)

# use @q to trace a function's arguments and return value
@q
def bar():
   ...

# to start an interactive console at any point in your code:
q.d()

The results are output to the file /tmp/q(or any customized paths) by default,so they won't be mixed with stdout and normal logs. You can check the output with tail -f /tmp/q. The output is highlighted with different colors.

The author introduced his library in a lightning talk of PyconUS 2013. The video is here, begins at 25:15.


Here is another evil hack:

import inspect

def log(a):
    call_line = inspect.stack()[1][4][0].strip()
    assert call_line.strip().startswith("log(")
    call_line = call_line[len("log("):][:-1]
    print "Log: %s = %s" % (call_line, a)

b=3
log(b)

This obviously would need some range checks, better parsing, etc. Also works only if the calls is made always in the same way and has probably more - unknown to me - assumptions...