Printing literal text of an argument

Gregory Bond gnb at itga.com.au
Fri Aug 12 03:55:29 CEST 2005


Rex Eastbourne wrote:

> def debug(aname, avalue):
>     print aname, 'is':
>     pprint.pprint(avalue)
> 

use eval:

def debug(s):
	print s, 'is'
	pprint.pprint(eval(s))

(it does mean the arg is a string not code......)

>  On a
> slightly different topic, is it also possible to make the macro print
> the line number where the function was first called?

You can raise and catch an exception then walk up the call stack:

import sys

def debug(s):
	print s, 'is'
	pprint.pprint(eval(s))
	
	try:
		raise ""
	except:
		tb = sys.exc_info()[2]
	# Find the calling frame
	frame = tb.tb_frame.f_back
	print "Called from line", frame.f_lineno

See the language reference manual sec 3.2 "Standard Type Hierarchy".



More information about the Python-list mailing list