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

前端 未结 4 1377
南方客
南方客 2021-01-05 15:40

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

    myfunction \"Hello!\"


        
相关标签:
4条回答
  • 2021-01-05 16:07

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

    This doesn't apply for generic functions though.

    0 讨论(0)
  • 2021-01-05 16:16

    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).

    0 讨论(0)
  • 2021-01-05 16:18

    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)

    0 讨论(0)
  • 2021-01-05 16:29

    You can do it with iPython -- the -autocall command line option controls this feature (use -autocall 0 to disable the feature, -autocall 1, the default, to have it work only when an argument is present, and -autocall 2 to have it work even for argument-less callables).

    0 讨论(0)
提交回复
热议问题