-1

I often need to print variables for debugging purposes, and I found out that it helps a lot to also know what those variables are. So I would like to have a function that does sort of the following:

from __future__ import print_function

def get_variable_name(my_variable):
  ... ?

def print_with_variable_name(my_variable):
  print (get_variable_name(my_variable), ': ', my_variable)

a = 30
print_with_variable_name(a);

Expected output:

a: 30

I found some partial solutions to the problem where I could do that only in the function where the function was defined by the name a, otherwise it would print:

my_variable: 30

Is there any elegant solution to the problem where I can just write a module with this new print function and import it wherever I like?

scapiskipi
  • 63
  • 7
  • 2
    This is tricky. A Python object doesn't know its name: it may have no name, or multiple names. OTOH, some object types (eg normal `def` functions) have a `.__name__` attribute. A much easier plan is to write a function that accepts a name _string_, which it can then use to see if there's an object bound to that name. BTW, you may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Nov 14 '17 at 11:12
  • 1
    Short answer: you can't. There are a couple special cases where you can use dirty tricks to get _one_ of the possible names bound to an object, but none is generic nor reliable. – bruno desthuilliers Nov 14 '17 at 11:14
  • 1
    I've just added some code to the end of [my answer](https://stackoverflow.com/a/31358785/4014959) in the linked question that you may find interesting. – PM 2Ring Nov 14 '17 at 11:24

2 Answers2

1

Try with dictionary: dict((name,eval(name)) for name in ['list', 'of', 'vars'])

canillas
  • 414
  • 3
  • 13
  • This won't be flexible enough; I just want to add it any program I want without any overhead (other than the import itself) – scapiskipi Nov 14 '17 at 12:22
0

I would suggest using a dictionary if that will suit how your program works (Lots of different variables). The dictionary will allow you to grab the value and the values name.

Thomas Youngson
  • 181
  • 3
  • 14