A
A
Artem Matyashov2016-07-31 21:59:16
Python
Artem Matyashov, 2016-07-31 21:59:16

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

The function itself looks like:
def fun(request, var):
    context['data'] = var
    return context

If you wrap a function with a decorator, Python swears at an unknown global variable 'context'.
Is it possible to somehow use the variables described in decorate_maker?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2016-07-31
@FireGM

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.

A
Alexey Cheremisin, 2016-07-31
@leahch

Only if you pass the variable itself from the decorator to the function by adding the context argument to it.

P
Pavel, 2016-07-31
@Ermako

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)]

This is how it will look like for you
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 question

Ask a Question

731 491 924 answers to any question