Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
klaus ruprecht Avatar asked Oct 28 '25 00:10

klaus ruprecht


2 Answers

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.

like image 132
dimo414 Avatar answered Oct 29 '25 15:10

dimo414


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
like image 43
letsc Avatar answered Oct 29 '25 14:10

letsc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!