klaus ruprecht
klaus ruprecht

Reputation: 127

Call one function after another python, wrapping?

I have two functions "a" and "b". "b" gets called when a user uploads a file. "b" renames the file and returns the new filename. After that the file is supposed to be edited. Like this:

def a():
    edits file
def b():
    renames file  
    return file

So if b happens and ends, a is supposed to happen. Once "b" returns file the function is over and nothing happens after. Exactly at this point I want "a" to happen, how is this possible? Right now I call "a" with a timer

t=Timer(1.0,a)
t.start() 

but that's not a good solution. I tried with global variables but it doesn't work. I also tried return file, a() cause I thought then a would maybe get started. And finally wrapping it:

def b():
    global filename
    renames filename
    def a():
         edits filename  
    return filename

Is there something like if b(): a() ?

Anyone a suggestion?

Upvotes: 3

Views: 17720

Answers (3)

Jamey Hart
Jamey Hart

Reputation: 31

I found a solution to a similar question here.

Using that, I think you might want something like this:

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 a():
    edits file

@run_before(a)
def b():
    renames file  
    return file

b()

I think this question is confused further by the fact that you want b to run before a. For a more logical flow, I would suggest switching these around if possible.

All credit goes to agf for the original solution.

Upvotes: 1

dimo414
dimo414

Reputation: 48834

It sounds like you're looking for decorators, added by PEP 0318. Some (complex) examples are in the Decorator Library.

def a():
    edits file

def call_a_after(f):
  def decorate(*args, **kwargs):
    ret = f(*args, **kwargs)
    a()
    return ret
  return decorate

@call_a_after
def b():
    renames file  
    return file

This wraps b() in call_a_after() (decorators are syntactic sugar for b = call_a_after(b)) letting you redifine, or decorate, what b() does.

Upvotes: 3

letsc
letsc

Reputation: 2567

Just do this:

def a():
    #your code

def b():
    #your code
    a()

Example:

def first():
    print 'first'

def second():
    print 'second'
    first()

>>> second()
second
first

Upvotes: 2

Related Questions