Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError: Decorator with default parameters

Here is my decorator code. I'm getting UnboundLocalError for some reason but I couldn't find it.

>>> def validate(schema=None):
        def wrap(f):
            def _f(*args, **kwargs):
                if not schema:
                schema = f.__name__
            print schema
            return f()
            return _f
        return wrap

>>> @validate()
    def some_function():
        print 'some function'


>>> some_function()
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    some_function()
  File "<pyshell#22>", line 4, in _f
    if not schema:
UnboundLocalError: local variable 'schema' referenced before assignment
>>> 

So, I thought maybe it's better to post here. I might be missing something.

Thanks.

like image 256
pocoa Avatar asked Apr 12 '11 04:04

pocoa


1 Answers

The compiler can't determine schema's proper scope. Either use nonlocal schema (3.x) within _f() or change the definition of _f() slightly:

def _f(self, schema=schema, *args, **kwargs):
like image 161
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 11:09

Ignacio Vazquez-Abrams