UnboundLocalError:在赋值之前引用的局部变量....

时间:2010-10-29 03:24:09

标签: python error-handling

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

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

2 个答案:

答案 0 :(得分:3)

Just Switch:

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

答案 1 :(得分:2)

我想我需要先解释一下这个问题:在创建template_values时,你会使用一个问候变量。如果没有用户,则不会设置此变量。

没有一种标准方法可以处理这种情况。常见的方法是:

1. make sure that the variable is initialized in every code path (in your case: including the else case)
2. initialize the variable to some reasonable default value at the beginning
3. return from the function in the code paths which cannot provide a value for the variable.

像丹尼尔一样,我怀疑在重定向调用之后,你不应该产生任何输出,所以纠正的代码可能会读取

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))
        return
...

    template_values = {"greeting": greeting,
                   }