4

I get the basic principle of Python decorators and I like the syntax. However, they seem a little limited on what you can do.

Is there an elegant way to go about handling multiple functions as arguments like below?

def parent_fn(child_fn1, child_fn2):
 def wrapper():
 print('stuff is happening here')
 child_fn1()
 print('other stuff is happening here')
 child_fn2()
 return wrapper
@parent_fn
def decorated():
 print('child_fn1 stuff here')
decorated()

Where could I put the child_fn2 code? The few ideas I have tried appears to take away from the simplicity and elegance of the decorator.

asked Sep 2, 2017 at 23:09

1 Answer 1

5

You could do that:

import functools
def sequence_with(f):
 def wrap(g):
 @functools.wraps(g)
 def sequenced_func():
 f()
 g()
 return sequenced_func
 return wrap
def func1():
 print('func1')
@sequence_with(func1)
def func2():
 print('func2')

but it's probably not a good conceptual fit for decorators. Conceptually, decorators are supposed to alter the functionality of a single function they decorate; a function that sequences two other functions on an equal footing may not make much sense as a decorator. For example, the new function created by the decorator is now under the name func2, replacing the original func2. That only makes sense for some specific use cases, whereas avoiding decorator syntax would give you more flexibility.

It makes more sense to not use decorator syntax:

def sequence(f, g):
 def sequenced_func():
 f()
 g()
 return sequenced_func
def func1():
 print('func1')
def func2():
 print('func2')
sequenced_func = sequence(func1, func2)
answered Sep 2, 2017 at 23:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.