Getting the argument names passed to a function ?

Mark Jackson mjackson at wc.eso.mc.xerox.com
Wed Apr 5 03:55:02 CEST 2000


quinn at riyal.ugcs.caltech.edu (Quinn Dunkan) writes:
> > > Hmm, could you say:
> > > 
> > > def arghack(arg):
> > >     for k, v in globals().items():
> > >         if arg is v:
> > >             return k
> > >     else:
> > >         return None
> > > 
> > > Seems to work ok...
> > This only works if the argument passed in is a global.  For example:
> > >>> def hackSpoiler():
> > ...     a = 2
> > ...     print arghack(a)
> > ...
> > >>> hackSpoiler()
> > None
> 
> Ok, Mr. Spoilsport :)
> 
> import sys
> def arghack(arg):
>     try:
>         1/0
>     except:
>         frame = sys.exc_info()[2].tb_frame.f_back
>     while frame:
>         for k, v in frame.f_locals.items():
>             if arg is v:
>                 return k
>         frame = frame.f_back
>     else:
>         return None

But you forget about:

>>> a=1
>>> b=a
>>> arghack(a)
'a'
>>> arghack(b)
'a'
>>> 

Your move. . . :-)

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
	An advertiser will happily make you feel bad about
	yourself if that will make you buy, say, a Bic pen.
				- George Meyer





More information about the Python-list mailing list