背景是我从 JSON API 获取数据,其中很多字段是可选的,我想要数据库中的大部分字段。当特定字段不可用时,我想将一个空字符串 (""
) 写入数据库。
目前我在做:
if jsonobject.what_i_look_for:
dbstring = jsonobject.what_i_look_for
else:
dbstring = ""
然后将dbstring插入到数据库中。然而,我现在得到了更多这些字段,我想要一个更简洁的代码,而不是一个包含大约 80% 的 if 语句的函数。
我找到了 if-shorthands和 this检查变量是否为空的简写,但两者似乎都不能直接作为字符串使用。我在交互式 python 3.5.2 shell 中使用 print()
对此进行了测试:
>>> print(testvar or "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
>>> print(testvar if testvar else "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
这个:echo (isset($testvar) ? $testvar : "");
是我寻找的 PHP 等价物。
编辑: 因为它似乎相关:我尝试处理的对象来自 Telegram 的 JSON API。我正在使用 python-telegram-bot
作为库和 this是一个示例对象。
Pythonic 方法是寻找NameError
异常,当变量未定义时会引发异常,名称未绑定(bind)到任何对象 准确地说。
所以,例如:
try:
foobar
except NameError:
# Do stuffs
print('foobar is not defined')
raise # raise the original exception again, if you want
名称驻留在 namespace 中,例如局部名称驻留在 locals()
(dict
) 命名空间中,全局名称驻留在 globals()
(dict
) 中命名空间。您可以定义一个函数,该函数将名称字符串和命名空间作为参数来检查是否存在,这里有一个提示将命名空间作为 dict
传递并捕获 KeyError
:
In [1213]: def is_defined(name, namespace):
...: try:
...: namespace[name]
...: except KeyError:
...: return False
...: return True
...:
In [1214]: is_defined('spamegg', globals())
Out[1214]: False
In [1215]: spamegg = 10
In [1216]: is_defined('spamegg', globals())
Out[1216]: True
另一方面,如果您希望获取对象属性字符串的值,getattr
是可行的方法:
getattr(obj, attr)
例如下面两个是等价的:
obj.foobar
getattr(obj, 'foobar')
即使您可以在缺少对象属性时添加默认值:
getattr(obj, 'foobar', 'spamegg')
以上将输出值obj.foobar
,如果缺少foobar
,它将输出spamegg
。
您可能还对 hasattr
感兴趣,它返回 True
/False
进行属性存在检查,而不需要手动处理 属性错误
。