Shortcutting the function call stack

Julien jphalip at gmail.com
Mon Mar 24 07:21:29 EDT 2008


Hello all,

I would like to do something like:

def called(arg)
    if arg==True:
        !!magic!!caller.return 1

def caller(arg)
    called(arg)
    return 2

Here, the fake !!!magic!!! represents a statement (which I ignore)
that would make the caller function return a value different from what
it'd return normally.

For example, caller(True) would return 1, and caller(False) would
return 2. The reason I want that is because I don't want the caller
function to know what's going on in the called function, and be
shortcut if the called function think it's necessary.

Would you know if that's possible, and if so, how?

I've done a bit of research and I think I've found some good pointers,
in particular using the 'inspect' library:

import inspect

def called(arg)
    if arg==True:
        caller_frame = inspect.stack()[1]
        ...

Here 'caller_frame' contains the frame of the caller function. Now,
how can I make that frame return a particular value?

By the way, I'm not really interested in 'called' throwing an
exception and 'caller' catching it. In fact, I want things to remain
completely transparent for 'caller'.

Hope that was clear... :/

Thanks!

Julien



More information about the Python-list mailing list