getting name of passed reference
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Dec 28 20:40:00 EST 2009
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
More information about the Python-list
mailing list