from functools import wraps
def panel(title=None, footer=None):
def decorator(func):
@wraps(func)
def inner(*args, **kwargs):
heading = ''
if title:
heading = title
if footer:
footer = footer + '\n'
return heading + footer
return inner
return decorator
@panel(title='Hello', footer='World')
def hello_foo():
print 'Executing'
hello_foo()
So, I am working on a code sample which follows the same logic . On executing this code I get an error:
UnboundLocalError: local variable 'footer' referenced before assignment
After debugging, I found that if try to update the value of footer
it throws me an error as it is a decorator parameter.
So, the two code samples given below work
def panel(title=None, footer=None):
def decorator(func):
@wraps(func)
def inner(*args, **kwargs):
heading = ''
if title:
heading = title
if footer:
print footer
print heading + footer
return inner
return decorator
In the above sample I am just printing the value of footer and not doing any update operation
def panel(title=None, footer_t=None):
def decorator(func):
@wraps(func)
def inner(*args, **kwargs):
heading = ''
footer = ''
if title:
heading = title
if footer_t:
footer = footer_t + '\n'
return heading + footer
return inner
return decorator
Here I changed the decorator parameter from footer
to footer_t
.
My question is what could be the possible reason behind the the error when I try to update the decorator parameter?