-3

Is it possible to return from a function and continue executing code from just under the function. I know that may sound vague but here is an example:


def sayhi():
    print("hi")
    continue_function() #makes this function continue below in stead of return

#the code continues here with execution and will print hey
print("hey")


sayhi()

when executing this the code should do this:

  • it prints "hey"
  • it calls the sayhi() function
  • it prints "hi"
  • it calls a function to make it continue after the function (in theory similar behavour could be achieve by using decorators)
  • it prints "hey" again
  • it calls sayhi() again
  • etc

i am fully aware of the fact that similar behaviour can be achieved by just using for loops but for the project i am working on this functionality is required and not achievable by using looping.


some solutions i have thought of (but i have no clue how i could execute them) are:

  • somehow clearing the stack python uses to return from one function to another
  • changing return values
  • changing python itself (just to make clear: it would solve the problem but it is something i do not want to do beacuse the project must be usable on non-altered versions of python
  • using some c extension to change python's behaviour from within python itself
jonathan
  • 590
  • 3
  • 14

1 Answers1

1

Repetition without loops can be done with recursion:

def sayhi():
    print("hey")
    print("hi")
    sayhi()


sayhi()

I assume you have some terminating condition to insert. If not, this code will give a RecursionError.

luther
  • 5,195
  • 1
  • 14
  • 24
  • of course that works. thanks for your help. it is however not what i'm looking for. i specifically want it to execute the code after the function so loops nor recursion will work. but thanks anyways. – jonathan Oct 17 '17 at 17:48