No, there is no such closure. Functions can close variables that are present in the surrounding lexical context, and not in the calling context. In other words, if you are actually writing one function to another, then the inside can have access to the variables in the outside:
def f(): g = 2 def f2(): print g f2()
But functions never have access to variables inside the function they call.
In general, there is no way to do what you want, namely, to set an arbitrary variable in a function from outside the function. The closest thing is that you can use global inputed_num in your decorator to assign inputed_num as a global variable. Then test will access the global value.
def num(num): def deco(func): def wrap(*args, **kwargs): global outsider outsider = num return func(*args, **kwargs) return wrap return deco @num(5) def test(a): print a+outsider >>> test(2) 7
But, of course, the variable parameter is global, so multiple concurrent uses (like recursion) will not work. (Just for fun, you can also see here for a very secret way to do this, but it's too crazy to be useful in the real world.)
source share