0

I have a decorator like this:

def dec(default):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            default = default or ['abc']
            return func(*args, **kwargs)
        return wrapper
    return decorator

# use:
# decor = dec(default=['123'])
# @decor
# def something(default...

So I get this error, actually, my linter gives it to me before I even run the code, but I get it during testing too:

local variable 'default' defined in enclosing scope on line x referenced before assignment

What am I doing wrong in this decorator such that I can't use outside arguments it inside the wrapper?

Do I have to explicitly pass it to wrapper before *args, **kwargs? How am I supposed to do that if I return the decorator function itself without calling it? return decorator

other examples I can find don't seem to have this problem (How to build a decorator with optional parameters?)

is this a python 3 thing? those examples were mostly python 2. maybe in py3 I have to explicitly define them as global default?

it's cuz of @wraps isn't it? this example I found seems to work fine, but it doesn't use @wraps. though I need to use it.

def d(msg=None):
    def decorator(func):
        def newfn():
            msg = msg or 'abc'
            return func()
        return newfn
    return decorator

@d('This is working')
def hello():
    print 'hello world !'

@d()
def hello2():
    print 'also hello world'

what should I do?

MetaStack
  • 3,266
  • 4
  • 30
  • 67
  • Why is that line in the innermost function? Shouldn't it be in the outermost scope? I'm confused about when and in what scopes you want to change the value of `default` – Patrick Haugh Feb 06 '20 at 18:25
  • Your second example also throws the error. (I noticed it has Python 2 syntax, are you using Python 2?) – Patrick Haugh Feb 06 '20 at 18:28
  • @PatrickHaugh Python3, that was an example I got from the link in the question. And yes, I see it has the same problem. – MetaStack Feb 06 '20 at 20:28
  • 2
    Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – Patrick Haugh Feb 06 '20 at 20:33
  • @PatrickHaugh yes I think it does – MetaStack Feb 06 '20 at 20:43

0 Answers0