处理可能为无的变量 [英] Handle variable that could be None

查看:78
本文介绍了处理可能为无的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管这与Django有关,但实际上只是一个通用的编程效率问题。

Although this is django related, it's really just a general, programming efficiency question.

我有一个模板,根据情况,该模板将获取并返回一种或两种形式。如果返回一种形式,则保存第二种形式的变量将为None。

I have a template that, depending on the scenario, will get and return either one or two forms. If it returns one form, the variable that holds the second form will be None.

我需要检查这些形式是否有效。类似于我在网上阅读的示例,在相同的if语句中检查两种形式的.is_valid()。但这并不奇怪,如果第二种形式为None,则会抛出错误(NoneType对象没有属性is_valid)。

I need to check if the forms are valid. Similar to an example I read online, I'm checking .is_valid() on both forms in the same if statement. But this unsurprisingly throws an error (NoneType object has no attribute is_valid) if the second form is None.

什么是检查两种形式都为最佳的最佳方法是什么?如果第二个格式为None,则有效而不会导致错误?

if request.method == 'POST':

    form = form_dict[modelname][1](request.POST) 
    try:
        form_two = form_dict[modelname][2](request.POST)
    except:
        form_two = None

    if form.is_valid() and form_two.is_valid():
        # Do some stuff and save the data from the form(s)      
    else:
        try:
            form = form_dict[modelname][1]()
            form_two = form_dict[modelname][2]()
        except:
            form_two = None


推荐答案

通常检查是否有东西是 None ..只需检查一下?

In the general case of checking if something is None.. just check it?

if x is not None and x.is_valid():
   ...

在Python中,短路,表示在表达式 x和y 中,<如果 x false ,则不会评估code> y (因为表达式不管 y 是什么,都是错误的。

In Python, or and and both short circuit, meaning that in the expression x and y, y is not evaluated if x is false (since the expression is false no matter what y is).

这篇关于处理可能为无的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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