You can't.* The detailed reasons are discussed in the Python language reference, but basically what Python does when you call printL(A_minus_B)
is take the value that has been labeled A_minus_B
and create a new label, xlist
, that happens to refer to the same thing. From that point on, the label xlist
has absolutely no connection to the other label A_minus_B
, and in fact, the value which has been labeled A_minus_B
or xlist
or whatever has no connection to any of the names that have been used to label it.
*Well, you can, by using some deep "Python voodoo"... you would basically have to tell Python to read the piece of source code where you call printL(A_minus_B)
and extract the variable name from there. Normally that's the kind of thing you probably shouldn't be doing (not because you're a beginner, but because it usually indicates you've designed your program the wrong way), but debugging is one of those cases where it's probably appropriate. Here's one way to do it:
import inspect, pprint
def print_values(*names):
caller = inspect.stack()[1][0]
for name in names:
if name in caller.f_locals:
value = caller.f_locals[name]
elif name in caller.f_globals:
value = caller.f_globals[name]
else:
print 'no such variable: ' + name
# do whatever you want with name and value, for example:
print "****************************"
print name
print (" entries : "),len(value)
print value
print "****************************"
The catch is that when you call this function, you have to pass it the name of the variable you want printed, not the variable itself. So you would call print_values('A_minus_B')
, not print_values(A_minus_B)
. You can pass multiple names to have them all printed out, for example print_values('A_minus_B', 'C_minus_D', 'foo')
.