函数调用中的Python理解(PEP 448)

2024-04-19 09:59:07 发布

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

(这些都在python3.5.2上)

PEP 448的底部,我看到:

Unbracketed comprehensions in function calls, such as f(x for x in it) , are already valid.

这很有趣。如果我定义以下函数:

def f(a, b, c):
    return a + b + c

那么这个措辞让我觉得f(thing for thing in [1, 2, 3]) == 6。但事实上,我得到:

>>> f(thing for thing in [1, 2, 3])
TypeError: f() missing 2 required positional arguments: 'b' and 'c'

即,整个生成器表达式作为a传递。你知道吗

那么PEP448中的这句话是什么意思呢?只是你可以传递一个生成器表达式作为参数?你知道吗


Tags: infor表达式asitfunctionarepep
3条回答

此语句仅表示在pre PEPworld中f(x for x in it)已经有效,并将生成器表达式作为第一个函数参数传递。你知道吗

为了使您的示例工作,您需要显式地解包生成器,如PEP示例所示。你知道吗

f(*(thing for thing in [1, 2, 3]))  # returns 6

在第f(thing for thing in [1, 2, 3])行中,只传递第一个参数,它是一个生成器。缺少参数bc。你知道吗

同时,检查政治公众人物的以下部分:

However, it wasn't clear if this was the best behaviour or if it should unpack into the arguments of the call to f . Since this is likely to be confusing and is of only very marginal utility, it is not included in this PEP. Instead, these will throw a SyntaxError and comprehensions with explicit brackets should be used instead.

Python允许您将单个生成器表达式传递给正在调用的函数,而不需要额外的括号。例如:

foo(x for x in range(10))

主要相当于:

genexp = (x for x in range(10)) # parentheses are necessary here
foo(genexp)

如果有其他参数传递给函数调用(例如foo(w, (x for x in range(10)), y, z),其中第二个参数是x的生成器表达式),那么在定义生成器表达式时仍然需要括号。你知道吗

政治公众人物顺便提到,在这种情况下,进一步扩展解包语法可能会令人困惑。如果一种新的生成器表达式(*x for x in nested)是合法的(它不是最终PEP的一部分,但正在考虑一段时间),那么foo(*x for x in nested)应该如何工作?它是否等同于foo((*x for x in nested))(使用单个生成器表达式调用,其中包括新的“展平”*),或者它是否意味着foo(*(x for x in nested))(这现在是合法的)?你知道吗

相关问题 更多 >