En Tue, 29 Dec 2009 00:28:32 -0300, Joel Davis <callmeclaud...@gmail.com> escribió:
On Dec 28, 9:37 pm, Joel Davis <callmeclaud...@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

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to