Lets say I have two functions:
def foo():
return \'foo\'
def bar():
yield \'bar\'
The first one is a normal function, and the second i
I've implemented a decorator that hooks on the decorated function returned/yielded value. Its basic goes:
import types
def output(notifier):
def decorator(f):
def wrapped(*args, **kwargs):
r = f(*args, **kwargs)
if type(r) is types.GeneratorType:
for item in r:
# do something
yield item
else:
# do something
return r
return decorator
It works because the decorator function is unconditionnaly called: it is the return value that is tested.
EDIT: Following the comment by Robert Lujo, I ended up with something like:
def middleman(f):
def return_result(r):
return r
def yield_result(r):
for i in r:
yield i
def decorator(*a, **kwa):
if inspect.isgeneratorfunction(f):
return yield_result(f(*a, **kwa))
else:
return return_result(f(*a, **kwa))
return decorator