How to write the name and value of a variable?

I am looking for a way to quickly print the name and value of a variable when quickly developing / debugging a small Python script in a Unix / ssh command line session.

This seems like a very common requirement, and it seems wasteful (on key presses and time / energy) to duplicate the variable_name name on every line that prints or writes its value. that is, not

 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 also writes the name of the function.

I have seen some solutions trying to use locals , globals , frames, etc., but I have not yet seen something that works for integers, strings, lists, and also works inside functions.

Thanks!

+8
source share
3 answers

If the tool you need is for development and debugging only, then there is a useful package called q .

It was sent to pypi, it can be installed using pip install q or easy_install q .

 import q; q(foo) # use @q to trace a function arguments and return value @q def bar(): ... # to start an interactive console at any point in your code: qd() 

By default, the results are output to the / tmp / q file (or any other custom paths), so they will not mix with stdout and regular logs. You can check the output with tail -f/tmp/q . The output is highlighted in different colors.

The author presented his library in a lightning conversation about PyconUS 2013. The video here starts at 25:15.

+7
source

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 will obviously require some range checks, better analysis, etc. Also works only if calls are always made the same and probably more - unknown to me - assumptions ...

+4
source

I do not know how to simply get the name of a string variable. however, you can get a list of arguments for the current synchronization log.

 import inspect def log(a): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) print "%s:%s" % (args[0], values[args[0]]) 
0
source

Source: https://habr.com/ru/post/955764/


All Articles