Answer the question
In order to leave comments, you need to log in
Is it possible to use variables from a decorator in Python in a function?
We have a decorator like:
def base_context(fun):
def decorate_maker(request, slug, var):
context = {}
context['info'] = slug
return fun(request, var)
return decorate_maker
def fun(request, var):
context['data'] = var
return context
Answer the question
In order to leave comments, you need to log in
Not the best option, use what she doesn't have. With a decorator, you can change the input or output of this function. And if you need to use something from the decorator in the function, then explicitly pass to it everything that may be required.
Explicit is better than implicit.
Only if you pass the variable itself from the decorator to the function by adding the context argument to it.
You can use the namespace of the passed function itself
def base_context(fun):
def decorate_maker(nums,*args):
fun.func_globals['nums'] = nums
return fun(*args)
return decorate_maker
@base_context
def fun(pow):
return [(k,v**pow) for k,v in nums.iteritems()]
nums = {'one':1,'two':2,'four':4}
>>>>fun(nums,2)
[('four', 16), ('two', 4), ('one', 1)]
>>>>fun(nums,3)
[('four', 64), ('two', 8), ('one', 1)]
def base_context(fun):
def decorate_maker(request, slug, var):
context = {}
context['info'] = slug
fun.func_globals['context']=context
return fun(request, var)
return decorate_maker
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question