[Tutor] printing variable name and value?

Emile van Sebille emile@fenx.com
Wed, 31 May 2000 17:40:37 -0700


Gabor,

Well, if you *really* don't want to pass locals() or
globals() to the function, it looks like this can dig
them out.   This should find all the names in the scope
of the caller that point to the id of the vars passed,
and appears to work in idle as well as imported.

def showvars(*vars):
  import sys
  try:
    1/0
  except ZeroDivisionError:
    callers_globals = sys.exc_info()[2].tb_frame.f_back.f_globals
    callers_locals = sys.exc_info()[2].tb_frame.f_back.f_locals
  varids=[]
  for eachvar in vars:
    varids.append(id(eachvar))
  for calling_var_name, calling_var_value in callers_locals.items() +
callers_globals.items():
    if id(calling_var_value) in varids:
      print calling_var_name, " = ", calling_var_

showvars(a,b,c)
b  =  4
c  =  6
a  =  2

It should probably verify that the variable names found are from
the invoking statement.  Particularly as:

showvars.showvars(a + b)
c  =  6

See you,

Emile van Sebille
emile@fenx.com
-------------------


----- Original Message -----
From: Borgulya Gabor <borgulya@pons.sote.hu>
To: Emile van Sebille <emile@fenx.com>
Cc: Python Tutor <tutor@python.org>
Sent: Wednesday, May 31, 2000 12:48 PM
Subject: Re: [Tutor] printing variable name and value?


> Hello,
>
> I have found a working, but unstable solution for my own question:
>
> import traceback
> def prvar(__x):
>     print traceback.extract_stack(limit=2)[0][3][6:][:-1],"=",__x
>
> Lets's test it:
>
> a=5; b=3
> prvar(a)
> prvar(a+b)
> for i in range(10,8,-1):
>     prvar(i)
>
> The output:
>
> a = 5
> a+b = 8
> i = 10
> i = 9
>
> It works, and I am going to use it for testing my scripts. But in many
> cases this method will fail:
> prvar (a)         #  because there is a space between prvar and the
'('
> (prvar(a))        #  such problems could be solved by cleverer search
>                   #    for the parameter in the traceback string
> prvar(a);prvar(b) #  would confuse the cleverer algorithms too
>
> Unfortunately, the outcome is unpredictable when running the script
from
> IDLE. I don't understand, why.
>
> Yours,
>
> Gabor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
>