getting name of passed reference

Joel Davis callmeclaudius at gmail.com
Mon Dec 28 21:14:34 EST 2009


On Dec 28, 8:40 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Mon, 28 Dec 2009 17:27:21 -0800, Joel Davis wrote:
> > 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)
>
> Incorrect. Here's a copy-and-paste from an interactive session using that
> code:
>
> >>> 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)
> None
>
> > the print statement returns the full function call including parameters
> > as they were written in the script (variable names and all)
>
> I'm afraid not. I don't know what testing you did, but it doesn't work as
> you think it works.
>
> Also, I notice that you've called the variable local to the function the
> same name as the variable in the outer scope. What happens when you do
> this?
>
> >>> x = "something else"
> >>> MyFunc(x)
>
> None
>
> > 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?
>
> Yes.
>
> sys._getframe is a PRIVATE function, which means it is subject to change
> without notice. You're using an internal function clearly marked as
> private. It is unlikely to even exist at all in other implementations of
> Python (e.g. Jython, IronPython, PyPy, CLPython, etc.), and it might not
> even exist in future versions of CPython.
>
> > also, when can one _not_ get the name?
>
> When the object doesn't have a name at all, or when it has multiple
> names. Which is "the" name?
>
> --
> Steven

steven, when I said that's what the code returned I was explaining
what I saw when I ran it, if you're having trouble running it in the
interactive terminal, then that's probably because it can't be ran in
the interactive terminal.



More information about the Python-list mailing list