Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log a variable's name and value?

I am looking for a way to quickly print a variable name and value while rapidly developing/debugging a small Python script on a Unix command line/ssh session.

It seems like a very common requirement and it seems wasteful (on keystrokes and time/energy) to duplicate the variable_names on every line which prints or logs its value. i.e. rather than

print 'my_variable_name:', my_variable_name

I want to be able to do the following for str, int, list, dict:

log(my_variable_name)
log(i)
log(my_string)
log(my_list)

and get the following output:

my_variable_name:some string
i:10
my_string:a string of words
my_list:[1, 2, 3]

Ideally the output would also log the function name.

I have seen some solutions attempting to use locals, globals, frames etc., But I have not yet seen something that works for ints, strings, lists, and works inside functions too.

Thanks!

like image 420
Sean Avatar asked Oct 11 '13 12:10

Sean


People also ask

How do you log a variable name in Javascript?

There is no way to get the name of a variable inside of your log function. You can only do it inside of the caller of your log function, by converting the calling function to a string and parsing the code and grabbing the variable name passed to your log function.

How do you print variable names and values in Python?

Using f-strings in Python to print variables is the most commonly used method and I would personally recommend using this method. In this method, an 'f' is placed before the opening quotation mark of a string. Braces {} are placed around the names of variables that you are looking to print.

How do you log a value in a variable in Python?

The logging methods take the string as an argument, and it might seem natural to format the string with variable data in a separate line and pass it to the log method. But this can be done directly by using a format string for the message and appending the variable data as arguments.


1 Answers

If the tool you need is only for developing and debugging, there's a useful package called 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.

like image 55
Leonardo.Z Avatar answered Sep 28 '22 10:09

Leonardo.Z