Python Forum
Decorator and namespace.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decorator and namespace.
#1
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()
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function-decorator , which is checking an access according to USERNAME Liki 6 548 Feb-17-2024, 03:36 AM
Last Post: deanhystad
  Decorator for a function with argument(s) banidjamali 1 1,829 Feb-09-2021, 11:55 AM
Last Post: Gribouillis
  i got a decorator question yosef 3 2,568 Aug-25-2020, 04:14 PM
Last Post: DeaD_EyE
  Decorator is using in class,but not working mbilalshafiq 2 2,111 Jul-04-2020, 08:53 PM
Last Post: mbilalshafiq
  global / local namespace nzcan 3 2,422 Oct-31-2018, 04:49 PM
Last Post: woooee
  python decorator alfredocabrera 0 3,131 Feb-22-2017, 07:04 AM
Last Post: alfredocabrera

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020