Shortcutting the function call stack
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Mon Mar 24 09:54:08 EDT 2008
On Mon, 24 Mar 2008 04:21:29 -0700, Julien wrote:
> Hello all,
>
> I would like to do something like:
>
> def called(arg)
> if arg==True:
> !!magic!!caller.return 1
Instead of writing "if arg==True", or "if (arg==True)==True", or even
"if ((arg==True)==True)==True", you should just write:
"if arg:"
That's probably all you need.
>
> def caller(arg)
> called(arg)
> return 2
def called(arg):
return 1
def caller(arg):
if arg: return called(arg)
return 2
And if you wish to change the place where the decision is made:
def called(arg):
if arg: return 1
else: return 2
def caller(arg):
return called(arg)
> 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.
The statement you use to return a value different from what you would
normally return is the "return" statement. You need to call that
statement from the function doing the returning, not from another
function.
> 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.
Not knowing what's going on in called functions is why functions were
invented in the first place. That's what they do.
What shortcut do you think you might want to take? There are probably
better solutions than playing around with the internals of the
interpreter. I have a feeling you are trying to implement some sort of
function cache, maybe...
def check_in_cache(arg): # fake cache code
if arg:
!!magic!!caller.return 1 # not real Python
def function(arg):
check_in_cache(arg) # magic happens here
# but if it doesn't, we do lots of calculations here
return 2 # and finally return
Is that the sort of thing you're trying for? If so, that's not the way to
go about it.
--
Steven
More information about the Python-list
mailing list