Eval the caller within a method?

Jan Dries jdries at mail.com
Sat Oct 21 11:01:02 EDT 2000


Franz GEIGER wrote:
> 
> I wonder if in Python there is a possibility to evaluate the method which
> called a method within that method like it is in Perl.
> 
> Any ideas?

Given you run the following python program (saved in file loginfo.py)

    from sys import exc_info

    def caller_info():
        try:
            raise StandardError
        except StandardError:
            caller = exc_info()[2].tb_frame.f_back.f_back.f_code
            return
(caller.co_name,caller.co_filename,caller.co_firstlineno)

    def log_info(msg):
        print "Message '%s' from function %s in file %s at line %s " %
((msg,) + caller_info())

    def my_function():
        log_info("some diagnostics")

    my_function()

the output is:

"Message 'some diagnostics' from function my_function in file loginfo.py
at line 13"

which I believe is what you were looking for.
The trick is in the traceback object you can obtain once you get an
exception. That contains the current stack frame (where the exception
occured). Each stack frame has, among other things, a ref to the
previous (the caller) frame (named f_back) and a ref to a code object
named f_code. The latter has various members with info about the
function.

Regards,
Jan




More information about the Python-list mailing list