0

I'm going over decorators with this page (scroll down to section 9) and the two examples work fine. However, I don't like how nested functions are used. It seems like a lot of extra effort for such a simple task. For the first example, using the outer() and inner() functions, I can't simply comment out inner like so

def outer(some_func):
#    def inner():
        print("before some_func")
        ret = some_func() # 1
        return ret + 1
#    return inner
def foo():
    return 1
decorated = outer(foo) # 2
print(decorated())

because Python gives

TypeError: 'int' object is not callable

on the print(decorated()) line.

I'm not sure what's going on here. Is there any way to rewrite this decorator without needing to use two nested functions? I'd also like to see if the second example, using coordinate pairs and the wrapper() and checker() functions can also be rewritten to avoid the extra function.

jktstance
  • 143
  • 2
  • 7
  • A decorator is supposed to return a replacement function. It is easiest done with nesting the function-to-return because that gives you access to the closure. But any other method that lets you return the same function or a replacement will do. – Martijn Pieters Aug 21 '15 at 21:16
  • 1
    Your `outer()` function must produce the result of the decorating. That's its task. – Martijn Pieters Aug 21 '15 at 21:17
  • Read *all* of e-satis' answer (highest upvoted, not the accepted answer) on the duplicate post I linked you to. – Martijn Pieters Aug 21 '15 at 21:19

0 Answers0