How to register in the decorator all the functions that it decorates?

Say you have the following decorator. How can it be changed to say add some links to a list of all the functions that it decorates?

def memoize(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer @memoize def foo(bar): return bar ** 3 
+6
source share
1 answer

You can easily save the list of decorator objects ( memoize.decorated ):

 _decorated = [] def memoize(obj): cache = obj.cache = {} # add to the decorated list _decorated.append(obj) @functools.wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer # make the list accessible from the decorator: memoize.decorated = _decorated 

It can be used as:

 @memoize def foo(bar): return bar ** 3 print memoize.decorated 

As a note, you should consider storing WeakRef in a list to avoid memory leaks or objects that are not freed when no other "real" links to them remain.

+3
source

Source: https://habr.com/ru/post/986173/


All Articles