UnboundLocalError:局部变量...在分配前被引用 [英] UnboundLocalError: local variable ... referenced before assignment

查看:128
本文介绍了UnboundLocalError:局部变量...在分配前被引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个 UnboundLocalError ,因为我在一个if语句中使用了一个未执行的模板值。处理这种情况的标准方法是什么?

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,
                       }

错误:

UnboundLocalError: local variable 'greeting' referenced before assignment


推荐答案

只需切换:

class Test(webapp.RequestHandler):
    def err_user_not_found(self):
        self.redirect(users.create_login_url(self.request.uri))
    def get(self):      
        user = users.get_current_user()
        # error path
        if not user:
            self.err_user_not_found()
            return

        # happy path
        greeting = ('Hello, ' + user.nickname())
        ...
        template_values = {"greeting": greeting,}

这篇关于UnboundLocalError:局部变量...在分配前被引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆