Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - 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 maintenance processing now.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could still do some work after return if you return from a try-block, the finally-block would still be executed, e.g.:

def fun(x):
    try:
        return x * 20
    finally:
        print("Yay! I still got executed, even though my function has already returned!")

print(fun(5))

Expected Output:

Yay! I still got executed, even though my function has already returned!
100

Quoting the docs:

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...