UnboundLocalError: Decorator with default parameters

Here is my decorator code. For some reason I get UnboundLocalError, but I could not 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 it would be better to post here. Maybe I missed something.

Thank.

+5
source share
1 answer

The compiler cannot determine the schemacorrect area. Use nonlocal schema(3.x) inside _f()or slightly change the definition _f():

def _f(self, schema=schema, *args, **kwargs):
+9
source

All Articles