getting name of passed reference

Joel Davis callmeclaudius at gmail.com
Mon Dec 28 20:27:21 EST 2009


For posterity, I figured out a solution:

 > #!/usr/bin/python

 > import sys
 > from traceback import extract_stack

 > varPassed="varName get"

 > def MyFunc(varPassed):
 >         try:
 >                 raise None
 >         except:
 >                 frame = sys._getframe(1)
 >                 print extract_stack(frame,2)[0][3]


 > MyFunc(varPassed)


the print statement returns the full function call including
parameters as they were written in the script (variable names and all)


On Dec 28, 8:10 pm, Emile van Sebille <em... at fenx.com> wrote:
> On 12/28/2009 3:54 PM Joel Davis said...
>
> > I'm just curious if anyone knows of a way to get the variable name of
> > a reference passed to the function.
>
> For curiosity, sure -- but it's real weak...
>
> > Put another way, in the example:
>
> >    def MyFunc ( varPassed ):
> >       print varPassed;
>
> >    MyFunc(nwVar)
>
> > how would I get the string "nwVar" from inside of "MyFunc"?
>
> Here are some ways of doing this:http://www.python-forum.org/pythonforum/viewtopic.php?f=14&t=12659
>
> > is it possible?
>
> Yes -- but only for a limited set of situations.  Consider the following:
>
> MyFunc(3)
>
> a=[1,2,3,4]
> MyFunc(a[2])
>
> b=a
> MyFunc(b[2])
>
> def newval(): return 3
> MyFunc(newval())
>
> MyFunc(range(3)[-1])
>
> Emile

at first glance the solution i came up with seems to be in general the
same as the one presented there,  are there any portability issues
you're aware of? also, when can one _not_ get the name?



More information about the Python-list mailing list