How can I conveniently print an expression?

Issac Trotts trotts at llnl.gov
Sun Dec 31 08:10:17 CET 2000


Suppose I want to print the expression len(sys.argv).
The most straightforward way to do this is to incant

print 'len(sys.argv) = '+`len(sys.argv)`

Naturally this chafes at my sense of hackerly laziness.
I would prefer to have something in python akin to my 
favorite C++ macro:

#define COUT(expr) cout<<#expr<<" = "<<expr<<endl;

which allows me to write the concise statement

COUT(argc);

rather than the needlessly verbose

cout<<"argc = "<<argc<<endl;

In Python, one might naively try something like

def printexpr(expr_string): 
  expr = eval(expr_string)
  print expr_string+' = '+`expr`

which would be used to say things like

printexpr('len(sys.argv)')

but of course this does not always work because when Python executes
eval(expr_string), it assumes that the elements of the expression
specified by expr_string are to be found in the global scope.  So 
when we write 

def do_stuff():
  i = 2
  printexpr('i')

i = 1
printexpr('i')
do_stuff()

we obtain the following output:

i = 1
i = 1

whereas we were hoping for:

i = 1
i = 2

If there were some mechanism that allowed us to access the variables
of a calling function from within a called function, then the problem
would be solved.  Does anyone know of such a mechanism?

Thanks,
Issac






More information about the Python-list mailing list