Shortcutting the function call stack

John Machin sjmachin at lexicon.net
Tue Mar 25 00:24:27 CET 2008


On Mar 25, 9:05 am, Julien <jpha... at gmail.com> wrote:
> Hi all, and thanks a lot for your answers!
>
> I'll try to explain a bit more what I'm after, and hopefully that will
> be clearer. In fact, what I'm trying to do is to "hijack" (I'm making
> up the term) a function:
>
> def hijacker(arg):
>     if I_feel_its_necessary:
>         hijack_caller_function_and_make_it_return(1)
>
> def my_function1(arg):
>     hijacker(something)
>     ... # Continue as normal
>     return 2
>

Your end goal (avoiding duplicate code) is laudable. However most folk
manage to do this without needing to invent arcane control structures
like the COME FROM and the COBOL ALTER verb.

def common_code(arg):
    if necessary(arg):
        return 1
   # assuming None is not a valid return from myfunc1 etc
   return None

def myfunc1(arg):
    return_value = common_code(something)
    if return_value is not None:
         return return_value
    # continue

# Look, Ma! No decorators!

Those functions could be methods of classes, but IMHO you don't need
anything fancier than that.

You mentioned maintainability. To borrow someone else's advice:
Consider that the next person to maintain your code may know where you
live and may possess a chain-saw.

HTH,
John



More information about the Python-list mailing list