getting name of passed reference

Joel Davis callmeclaudius at gmail.com
Tue Dec 29 10:02:03 EST 2009


On Dec 29, 2:29 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Tue, 29 Dec 2009 00:28:32 -0300, Joel Davis <callmeclaud... at gmail.com>  
> escribió:
>
>
>
> > On Dec 28, 9:37 pm, Joel Davis <callmeclaud... at gmail.com> wrote:
> > my thanks go out to Emile and Mr Hanson for their responses, I think
> > I've found the solution, much shorter as well:
>
> >     > #!/usr/bin/python
>
> >     > import traceback
>
> >     > def testing ( varPassed ):
> >     >         print traceback.extract_stack()[0][3]
>
> >     > testing("123")
>
> > and it seems the traceback module in general seems to have a lot of
> > history to it. This project is for CPython so compatibility with
> > Jython, Iron Python, et al isn't really that important right now. So
> > as far as functionality and compatibility I think I'm set as long as
> > traceback.extract_stack is 3.0 safe.
>
> Test with this:
>
> def f(): return g()
> def g(): return h()
> def h(): testing("123")
> f()
>
> You probably want traceback.extract_stack()[-2][3] instead.
>
> Note that your solution solves a different problem: you asked "the name of  
> the passed object" and testing() above prints "the source line of the  
> previous stack frame". This method may be good enough for you, but you  
> should be aware of its limitations:
>
> - The source code (.py file) of the module containing the calling function  
> must be present (a .pyc file is not enough).
> - It must be a plain text file in the filesystem, directly reachable in a  
> directory along sys.path (it may not be contained in a .zip file, an .egg,  
> or use any other kind of import mechanism).
> - The source retrieval may fail if your program changes the current  
> directory
> - If the calling function is not actually inside a module, you can't  
> retrieve its source (e.g. when using exec/eval, or from inside the  
> interactive interpreter).
> - Only the last line of the function invocation is returned; you miss all  
> its previous lines and/or arguments.
>
> I'm sure other limitations apply too -- don't rely on this technique for  
> anything critical.
>
> --
> Gabriel Genellina

Gabriel,

thanks for your input, I had no idea that did that and it could have
been deployed without even being aware of it, caused consternation and
headaches galore.



More information about the Python-list mailing list