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?