我想知道是否有一种 Pythonic/hacky 方法来检查集合中的所有(或没有)项目和依赖项是否为空。
假设我有一个变量
foo
,它是一个字典,但可以为空:
foo: Optional[dict] = None
我想检查两个 foo 不是 None 或其键之一:
if foo is not None and foo.get('bar') is not None:
pass
使用 AND,它会在其他任何事情之前“短路”,因此我可以安全地检查可空项上的其他键。
我正在考虑如何更巧妙地做到这一点,就像我们可以使用
any()
或 all()
那样。
我想在列表理解中做到这一点,但它会失败:
if not all(item is not None for item in [foo, foo.get('bar'), foo.get('baz')]:
# Value Error! :sad
一种方法可能是使用 try/catch,但这很丑陋并且不会让它看起来有趣......
我们不能选择海象运算符,因为它在列表理解中不可分配:
if not all (item for item in [foo := foo or {}, foo.get('bar'), foo.get('baz')]:
# SyntaxError, can't use walrus in list comprehension
我还想知道是否没有一个维护良好的工具可以实现此目的。还有更好的想法吗?
只需将
foo
与所有 foo.get
分开并使用 and
:
if foo is not None and all(foo.get(key) is not None for key in ('bar', 'baz')):
您还可以使用
key in foo
来检查字典中是否存在该键,这实际上更安全,因为如果键存在并且值为 None
那么使用上述方法将无法区分这两种情况:
if foo is not None and all(key in foo is not None for key in ('bar', 'baz')):
您可以使用模式匹配:
foo = {"bar": 111}
# foo can be None and it will work:
match foo:
case {"bar": int(val)}:
print(val)
打印:
111
或者:
foo = {"bar": 111}
match foo:
case {"bar": val} if val is not None:
print(val)