Getting the argument names passed to a function ?

Quinn Dunkan quinn at riyal.ugcs.caltech.edu
Tue Apr 4 21:30:10 EDT 2000


> > 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



More information about the Python-list mailing list