Lostsoul Lostsoul - 1 month ago 5
Python Question

Is there a way to do more work after a return statement?

I was a bit curious if I could do more work in a function after returning a result. Basically I'm making a site using the pyramid framework(which is simply coding in python) after I process the inputs I return variables to render the page but sometimes I want to do more work after I render the page.

For example, you come to my site and update your profile and all you care about is that its successful so I output a message saying 'success!' but after that done I want to take your update and update my activity logs of what your doing, update your friends activity streams, etc.. Right now I'm doing all that before I return the result status that you care about but I'm curious if I can do it after so users get their responses faster.

I have done multi-processing before and worst case I might just fork a thread to do this work but if there was a way to do work after a return statement then that would be simpler.

example:

def profile_update(inputs):
#take updates and update the database
return "it worked"
#do maintainence processing now..

Answer

No, unfortunately, once you hit the return statement, you return from the function/method (either with or without a return value).

From the docs for return:

return leaves the current function call with the expression list (or None) as return value.

You may want to look into generator functions and the yield statement, this is a way to return a value from a function and continue processing and preparing another value to be returned when the function is called the next time.