timger
timger

Reputation: 962

is there any way to run a other function after a function run finish?

def foo():
    pass

def bar():
    print 'good bay'

two function like blow and now i want to run bar function after foo run finish

is there some method like class use __del__? as i know in class method i can use __del__ like follow:

 class A(object):
    def __init__(self):
        pass
    def __del__(self):
        bar()

but i can't use foo.__del__ is there any other method to do this ?

Upvotes: 0

Views: 5339

Answers (2)

agf
agf

Reputation: 176770

This is what decorators are for. This decorator, used on foo with bar as an argument will will run bar after foo and still return foos result. It will work on functions with any number of arguments.

def run_before(lastfunc, *args1, **kwargs1):
    def run(func):
        def wrapped_func(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
            except:
                result = None
            finally:
                lastfunc(*args1, **kwargs1)
                return result
        return wrapped_func
    return run

def bar():
    print 'goodby'

@run_before(bar)
def foo():
    print "hello"

foo()

Edit: Added error handling. Thanks @Björn

Upvotes: 4

viraptor
viraptor

Reputation: 34145

Why not:

foo()
bar()

?

In case you want to have some general way to do it, you can try:

def run_after(f_after):
    def wrapper(f):
        def wrapped(*args, **kwargs):
            ret = f(*args, **kwargs)
            f_after()
            return ret
        return wrapped
    return wrapper

@run_after(bar)
def foo():
    ....

This way bar is always run after foo is executed.

Upvotes: 0

Related Questions