Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

syntax

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?

EDIT:

The statement that I read only applies to generator expressions:

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

like image 600
Tony the Pony Avatar asked May 28 '10 22:05

Tony the Pony


2 Answers

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)

like image 56
Jochen Ritzel Avatar answered Sep 28 '22 18:09

Jochen Ritzel


You can do it with IPython -- the %autocall magic command controls this feature (as well as the -autocall command line option). 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.

In [2]: %autocall 1
Automatic calling is: Smart

In [3]: int '5'
------> int('5')
Out[3]: 5

In [4]: %autocall 2
Automatic calling is: Full

In [5]: int
------> int()
Out[5]: 0
like image 42
Alex Martelli Avatar answered Sep 28 '22 19:09

Alex Martelli