0

It would be very useful for debugging to have a function like thus:

a = np.arange(20)
debug_print(a)

The above should print

variable: a
val: [...]

thanks a lot.

Karthick
  • 4,456
  • 7
  • 28
  • 34
  • You are trying to print the name of the variable in the *calling frame*. The function itself will have a *different* name for that parameter. What you are trying to do is rather... cumbersome. Isn't printing the value enough? – Martijn Pieters Jul 11 '13 at 07:55
  • I have a function with half a dozen intermediate steps. It would be really helpful to know which variable is being printed, without having to do print 'var', var everytime. – Karthick Jul 11 '13 at 08:01
  • 1
    You could maybe mash something up with - http://docs.python.org/2/library/inspect.html – YXD Jul 11 '13 at 08:01
  • How is that different from `print debug_print(var)`? You already know `var` at that moment. – Martijn Pieters Jul 11 '13 at 08:02
  • Make it a keyword argument (`debug_print(var=var)`) and it is trivial, see linked dupe. – Martijn Pieters Jul 11 '13 at 08:03
  • @MartijnPieters, I'm trying to avoid having to type the name twice. I guess I have to bend over backwards in Python to achieve something similar to a C style macro. – Karthick Jul 11 '13 at 08:17
  • @MartijnPieters, I saw the example in the link. It again depends on the name i give. That IS cumbersome as print 'var',var is going to do the same thing. – Karthick Jul 11 '13 at 08:18

1 Answers1

1

Try following code:

import inspect
import re

def debug_print(*args):
    lines = ''.join(inspect.stack()[1][4])
    matched = re.search('debug_print\((.*?)\)', lines).group(1)
    names = map(str.strip, matched.split(','))
    for name, value in zip(names, args):
        print('{} = {}'.format(name, value))

a = 1
b = 2
debug_print(a, b)
debug_print('a')
debug_print('a,aa') # Not work well for this case.
falsetru
  • 357,413
  • 63
  • 732
  • 636