检查 Python 中的初始化变量

Check for initialized variable in Python

我是 Python 的新手,正在尝试一些代码片段。

在我的代码中,我需要检查变量初始化,我使用了这个习惯用法:

if my_variable:
    # execute some code

但阅读一些帖子我发现使用了另一个成语:

if my_variable is not None:
    # execute some code

它们是等价的还是有一些语义差异?

以空字符串为例,即 '' 不是 None

>>> a = ""
>>> if a:
...     print (True)
... 
>>> if a is not None:
...     print (True)
... 
True
>>> 

和一个布尔值

>>> a = False
>>> if a:
...     print (True)
... 
>>> if a is not None:
...     print (True)
... 
True
>>> 

因此它们不等价

没有 if 0 会是 False,如果 my_variable 实际上是 0 那么 if my_variable is not None: 会是 True,对于任何 Falsey 值都是一样的。

In [10]: bool([])
Out[10]: False

In [11]: bool(0)
Out[11]: False

In [12]: bool({})
Out[12]: False
In [13]: [] is not None
Out[13]: True
In [14]: 0 is not None
Out[14]: True

引用 Python documentation on boolean operations,

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

因此,如果 my_variable 具有上述任何虚假值,则 if my_variable 将失败,而第二个仅当 my_variableNone 时才会失败。通常情况下,变量使用 None 作为占位符值进行初始化,如果在程序中的某个时间点它不是 None,那么它们将知道已为其分配了其他值。

例如,

def print_name(name=None):
    if name is not None:
        print(name)
    else:
        print("Default name")

这里,函数 print_name 需要一个参数。如果用户提供它,那么它可能不是 None,所以我们打印用户传递的实际名称,如果我们不传递任何东西,默认情况下将分配 None。现在,我们检查 name 是否不是 None 以确保我们打印的是实际名称而不是 Default name

注意:如果你真的想知道你的变量是否被定义,你可能想试试这个

try:
    undefined_variable
except NameError as e:
    # Do whatever you want if the variable is not defined yet in the program.
    print(e)

值得注意的是,python 变量不能未初始化。 python 中的变量是通过赋值创建的。

如果您想检查实际未初始化,您应该通过捕获 NameError 异常来检查(不)存在。

检查变量是否存在于全局字典中,如果不存在则初始化变量。

    if 'ots' not in globals():
        ots=0.0