Python中没有多行Lambda:为什么不呢?

2024-04-25 11:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

请看以下内容:

map(multilambda x:
      y=x+1
      return y
   , [1,2,3])

这是一个返回(y, [1,2,3])的lambda吗(因此map只获取一个参数,从而导致错误)?还是返回y?或者是语法错误,因为新行上的逗号放错了地方?Python怎么知道你想要什么?

在parens中,缩进与python无关,因此不能明确地使用多行。

这只是一个简单的例子,可能还有更多的例子。

Guido van Rossum(Python的发明者)在an old blog post中亲自回答了这个问题。
基本上,他承认这在理论上是可能的,但任何提议的解决方案都是非Python式的:

"But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate Rube Goldberg contraption."

这通常是非常难看的(但有时替代方案更难看),因此解决方法是生成一个大括号表达式:

lambda: (
    doFoo('abc'),
    doBar(123),
    doBaz())

它不会接受任何任务,所以你必须事先准备好数据。 我发现这个有用的地方是PySide包装器,在这里您有时会有短的回调。编写额外的成员函数将更加难看。通常你不需要这个。

示例:

pushButtonShowDialog.clicked.connect(
    lambda: (
    field1.clear(),
    spinBox1.setValue(0),
    diag.show())

相关问题 更多 >

    热门问题