2

I'm using decorator with the functional syntax as it's described here.

I loop over a list of dict. In this loop I wrap a generic function with a decorator taking a parameter. Then i call the wrapped function with the current dict as parameters.

My problem is that i get an local variable 'generic_evaluator' referenced before assignment error.

Here is my code:

The concerned decorator:

def log(logfile_name):
    def inner_log(func):
        def wrapped(*args, **kwargs):
            import os
            ret = func()
            # business code...
        return wraps(func)(wrapped)
    return inner_log

And here the place where I wrap generic_evaluator function with the log decorator.

for evaluation in generic_evaluations:
    generic_evaluator = log(evaluation['suffix'])(generic_evaluator)
    generic_evaluator(evaluation['suffix'], evaluation['id'])

EDIT

It'll be probably more clear with this piece of code in addition:

@tictoc
def generic_evaluator(suffix_url, id):
    xml = etree.parse(get_resource(base_url + "/" + suffix_url + "/" + str(id)))
    links = fetch_urls_from_xml(xml)
    return links
renard
  • 1,368
  • 6
  • 20
  • 40
  • Why do you think it should work. Here: `log(evaluation['suffix'])(generic_evaluator)` you are using `generic_evaluator`, which is not yet assigned. Hence the error. What exactly are you trying to achieve? – Vikas Jun 06 '12 at 11:18

2 Answers2

2

If generic_evaluator is a global function, and you actually want to rebind the global name generic_evaluator, declare this name as global:

global generic_evaluator

If you don't want to rebind the global name, use a different local name and initialise it:

local_generic_evaluator = generic_evaluator

This answer gives an explanation of what's going on.

Community
  • 1
  • 1
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0
generic_evaluator = log(evaluation['suffix'])(generic_evaluator)

You are referrencing generic_evaluator before assignment here log(evaluation['suffix'])(generic_evaluator)

try this:

for evaluation in generic_evaluations:
    generic_evaluator = log(evaluation['suffix'])(use_some_other_variable)
    generic_evaluator(evaluation['suffix'], evaluation['id'])
shiva
  • 2,674
  • 4
  • 23
  • 37
  • I forgot to precise that ``generic_evaluator`` is already defined. (See my EDIT) – renard Jun 06 '12 at 11:35
  • @renard you ve problem wit this line generic_evaluator = log(evaluation['suffix'])(generic_evaluator) – shiva Jun 06 '12 at 11:38
  • It's not another variable i need to use. It is a function object i use here, and it's a function already defined as i said in my edit. – renard Jun 06 '12 at 11:41
  • @renard, `ev = log(evaluation['suffix'])(generic_evaluator)` good for you? or cascade wrapping of generic_evaluator is needed? – Aleksei astynax Pirogov Jun 06 '12 at 12:17