Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing names of variables passed to a function

In some circumstances, I want to print debug-style output like this:

# module test.py
def f()
  a = 5
  b = 8
  debug(a, b) # line 18

I want the debug function to print the following:

debug info at test.py: 18
function f
a = 5
b = 8

I am thinking it should be possible by using inspect module to locate the stack frame, then finding the appropriate line, looking up the source code in that line, getting the names of the arguments from there. The function name can be obtained by moving one stack frame up. (The values of the arguments is easy to obtain: they are passed directly to the function debug.)

Am I on the right track? Is there any recipe I can refer to?

like image 707
max Avatar asked Mar 30 '12 06:03

max


People also ask

How do you print variable names?

To print a variable's name: Use a formatted string literal to get the variable's name and value. Split the string on the equal sign and get the variable's name. Use the print() function to print the variable's name.

How do you print statements with variables?

You first include the character f before the opening and closing quotation marks, inside the print() function. To print a variable with a string in one line, you again include the character f in the same place – right before the quotation marks.

What is the variable name that is used by a function to receive passed values?

The variables within the function which receive the passed data are referred to as the "formal" parameters.

Can you print the name of a variable in C?

How to print and store a variable name in string variable? In C, there's a # directive, also called 'Stringizing Operator', which does this magic. Basically # directive converts its argument in a string. We can also store variable name in a string using sprintf() in C.


2 Answers

You could do something along the following lines:

import inspect

def debug(**kwargs):
  st = inspect.stack()[1]
  print '%s:%d %s()' % (st[1], st[2], st[3])
  for k, v in kwargs.items():
    print '%s = %s' % (k, v)

def f():
  a = 5
  b = 8
  debug(a=a, b=b) # line 12

f()

This prints out:

test.py:12 f()
a = 5
b = 8
like image 190
NPE Avatar answered Nov 04 '22 01:11

NPE


You're generally doing it right, though it would be easier to use AOP for this kinds of tasks. Basically, instead of calling "debug" every time with every variable, you could just decorate the code with aspects which do certain things upon certain events, like upon entering the function to print passed variables and it's name.

Please refer to this site and old so post for more info.

like image 1
Dmitry Reznik Avatar answered Nov 04 '22 03:11

Dmitry Reznik