Python Forum
Decorator and namespace. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Decorator and namespace. (/thread-13674.html)



Decorator and namespace. - JayIvhen - Oct-26-2018

So. This decorator works. It provides saving function retirned value between calls.

The probles is that in standart way how function works I think dict should born and die EVRY call. But it does not!
For me it is very important to deeply understand how Python work. And now my had wil blow UP.

Why this dict(line 2) live??? Which namespace it lives in??? I cant find it any where! dir()/dir(f2)/dir(function_cachier)
Is there any special behavior for decorators??I noticed that if i define decorator sign(@), decorator body runs right after script start(u can see if add any print before cashe = dict()). May be it is loaded somewere and it lives like some special namespace?

 def function_cachier(func, *a):
    cashe = dict()
    def wraped(n):
        if n in cashe:
            return cashe[n]
        res = func(n)
        cashe[n] = res
        return res
    return wraped

@function_cachier
def f2(n):
    print 'f2 called'
    return n*n*n
f2(2)
f2(2)
print dir()



RE: Decorator and namespace. - ichabod801 - Oct-26-2018

This is called a closure. Since cache exists only in function_cachier, and not in the global namespace, Python saves it in the closure of f2. You can access it with f2.__closure__[0].cell_contents.

You should switch to Python 3. In just over a year support for 2.7 will stop.


RE: Decorator and namespace. - nilamo - Oct-26-2018

Here's some more reading: https://www.geeksforgeeks.org/python-closures/

As a question you can ask yourself, what would be purpose in having a cache that didn't persist between calls? That's just extra work with no benefit.