How can I conveniently print an expression?

Issac Trotts trotts at
Sun Dec 31 02:10:17 EST 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


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


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

i = 1

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?


More information about the Python-list mailing list