Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is namespace in python

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()
by

1 Answer

Bharatv4tg1
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.

Login / Signup to Answer the Question.