I get an UnboundLocalError
because I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
...
template_values = {"greeting": greeting,
}
Error:
UnboundLocalError: local variable 'greeting' referenced before assignment
Just Switch:
I guess I need to explain the problem first: in creating template_values, you use a greeting variable. This variable will not be set if there is no user.
There isn't a standard way to handle this situation. Common approaches are:
Like Daniel, I suspect that after the redirect call, you are not supposed to produce any output, anyway, so the corrected code might read