简体   繁体   中英

Possible to call single-parameter Python function without using parentheses?

The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but

    myfunction "Hello!"

generates a syntax error. So, what's the deal?

(I'm using Python 3.1)

EDIT:

The statement that I read only applies to generator expressions :

The parentheses can be omitted on calls with only one argument.

For your edit:

If you write down a generator expression, like stuff = (f(x) for x in items) you need the brackets, just like you need the [ .. ] around a list comprehension.

But when you pass something from a generator expression to a function (which is a pretty common pattern, because that's pretty much the big idea behind generators) then you don't need two sets of brackets - instead of something like s = sum((f(x) for x in items)) (outer brackets to indicate a function call, inner for the generator expression) you can just write sum(f(x) for x in items)

您可以使用iPython执行此操作 - -autocall命令行选项控制此功能(使用-autocall 0禁用该功能,使用-autocall 1 ,默认值,仅在存在参数时使用它,并且-autocall 2 to它甚至可以用于无争议的可赎回事件。

Without parentheses those wouldn't be functions but statements or keywords (language-intrinsic).

This StackOverflow thread (with some very nice answers) contains a lead as to how one can create their own in pure Python (through advanced hackery, and not a good idea in 99.99% of the cases).

As I understand the rule is only about the generator expressions... so for example: sum(x 2 for x in range(10)), but you would still have to write: reduce(operator.add, (x 2 for x in range(10))).

This doesn't apply for generic functions though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM