Python语法:从三元表达式中的函数返回值中解包多个变量会产生意外结果

Python语法:从三元表达式中的函数返回值中解包多个变量会产生意外结果,python,syntax,ternary-operator,iterable-unpacking,Python,Syntax,Ternary Operator,Iterable Unpacking,我注意到在三元表达式中解包多个值时出现了一个奇怪的问题。首先,一个说明语法的MWE,其目的是解压右侧的元组,并将其中的列表分配给左侧的第一个名称,将数字分配给第二个名称 condition = False a, b = [1, 2], 3 if not condition else None, None # ValueError: too many values to unpack def foo(): return [1, 2], 3 ([1, 2], 3) == foo() #

我注意到在三元表达式中解包多个值时出现了一个奇怪的问题。首先,一个说明语法的MWE,其目的是解压右侧的元组,并将其中的列表分配给左侧的第一个名称,将数字分配给第二个名称

condition = False
a, b = [1, 2], 3 if not condition else None, None  # ValueError: too many values to unpack
def foo():
    return [1, 2], 3
([1, 2], 3) == foo()  # True
a, b = foo()  # works as expected: a = [1, 2] and b = 3
a, b = foo() if not condition else None, None  # now a = ([1, 2], 3) and b is None
我的问题是理解这里语法背后的基本原理。如果
condition
的计算结果为false,那么为什么三元表达式的最后一部分
else
子句会被计算呢?Python是否将第二个
None
分配给
b
?这对我来说毫无意义,但我看不出还有什么其他方法a)NoValueError被提出来告诉我解包根本不起作用(如果我的语法以某种方式迫使Python将整个元组视为一个实体而不是解包),b)值仍然被分配给
b
。接下来显而易见的测试是:

a, b = foo() if not condition else None, 'test'  # Now a = ([1, 2], 3) and b = 'test'
a, b = (lambda x: [[1, 2], 3])('blah') if not condition else None, 'test'  # Same result with a lambda function.
因此,似乎正在评估else子句。为什么会发生这种情况?有没有一种优雅的方式来重写它,让我能够调用这样一个三元表达式中的函数,除了明显的和可能更笨拙的之外

if not condition:
    a, b = foo()
else:
    a, b = None, None

这只是优先权。Python将此解析为:

a, b = (foo() if not condition else None), None
为获得预期结果,需要在“否”周围添加括号:

a, b = foo() if not condition else (None, None)

这只是优先权。Python将此解析为:

a, b = (foo() if not condition else None), None
为获得预期结果,需要在“否”周围添加括号:

a, b = foo() if not condition else (None, None)

这里发生的事情是,python将三元表达式作为第一个要解包的项,
,None
作为第二个项。括号中的内容也一样:

a, b = (foo() if not condition else None), None
这可以通过以下措施来缓解:

a, b = foo() if not condition else (None, None)
这将为您提供正确的结果:

>>> a, b = foo() if not condition else (None, None)
>>> a, b
([1, 2], 3)

这里发生的事情是,python将三元表达式作为第一个要解包的项,
,None
作为第二个项。括号中的内容也一样:

a, b = (foo() if not condition else None), None
这可以通过以下措施来缓解:

a, b = foo() if not condition else (None, None)
这将为您提供正确的结果:

>>> a, b = foo() if not condition else (None, None)
>>> a, b
([1, 2], 3)

谢谢我会在心里记下一句话,永远不要再轻描淡写了。谢谢。我将在脑海中作一个强烈的音符,永远不要再轻描淡写了。