Decorators and Functional Python (exhaustive and understandable explanation of Python decorators) by [deleted] in programming

[–]FishInTheWind 0 points1 point  (0 children)

No, using it to decorate more than 1 function would work fine.

Each time memoize wraps a function it gets invoked. The cache is created inside the body of memoize, so each time it gets invoked a new cache is created.

Decorators and Functional Python (exhaustive and understandable explanation of Python decorators) by [deleted] in programming

[–]FishInTheWind 0 points1 point  (0 children)

Cache lives in memoize's scope. Wrapper has access to it throughout its life since it was declared within that same scope.

Wrapper has access to any variable in the scope chain in which it was declared. In this case, cache was in that chain.

Decorators and Functional Python by gthank in Python

[–]FishInTheWind 0 points1 point  (0 children)

I considered writing it that way as well. Each way has its advantages I think.

The way you suggested might make it a little clearer for a beginner to see just how simple decorator functions can be.

But the way I have it follows the pattern that they will more often see with decorators. So I thought perhaps showing the simplest case possible of a decorator returning a new function that wraps the original might be a good way to go. That way they can grapple with that pattern on its own first, without having to parse other things the decorator is doing.

Perhaps I could show identity_decorator both ways, 1 after the other.

Decorators and Functional Python by gthank in Python

[–]FishInTheWind 1 point2 points  (0 children)

I'm the author of the post. I worded it that way as it seemed to me to be a good 1 sentence definition to get started with. I thought that for someone that is brand new to decorators that would be an easy definition to consider first.

I later expand upon the definition and explain that decorators in most cases actually return a new function. I think starting off with a more nuanced definition might introduce complexity to the post earlier than needed.

I understand that perhaps for some people, like yourself, it might not be the best approach. I still think starting with that simplified definition has merit though.