Is there a better way of doing this?

Magnus Lycka lycka at carmen.se
Mon May 30 08:05:36 EDT 2005


Steven D'Aprano wrote:
 > print is a statement, not a function. The brackets are syntactically
 > correct, but pointless. Remove them.
...
> On Sat, 28 May 2005 13:24:19 +0000, Michael wrote:
>> while( newNS ):
> 
> Guido (our Benevolent Dictator For Life and creator of Python) hates
> seeing whitespace next to parentheses. I agree with him. while(newNS)
> good, while( newNS ) bad.

while is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them. ;^)

     while newNS:

Not only are they pointless (in both print and while), but they are
blurring the distinction between statements and callables, and they
add noise. Only wrap the expression following a statement such as
while, if, print etc in () if the following expression spans several
lines.

Using () instead of \ as line continuator is considered good style.
(See http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf
slide 3.) In that case, make sure you have a space between the
statement and the (. Never have space between a callable and
the (. That way, we emphasize the difference between a statemens
and a call. E.g:

while (aVeryVeryVeryLongVariableName == anotherVeryVeryLongName
        or aThirdLongVariableName == aFourthLongVariableName):
     something = function(parameterOne, parameterTwo, parameterThree,
                          parameterFour, parameterFive, etc)


N.B. Use "while (" but "function(".

(I'm not suggesting that such long variable names are generally
good, but there are certainly cases where both logical expressions
and parameter lists will be too long for one line, for instance when
working with stuff such as the win32 APIs.)

Please note the big conceptual difference in using a statement which
controls local program flow, and calling a function/method/class etc
which means that we transfer control to a different part of the
program. Some of the current statements in Python, e.g. print,
actually behaves more like a function than like the normal statements,
and this might be considered a wart. It's also mentioned in Guido's
"regrets" slides mentioned above. Print and exec *are* still not
callables though. They *are* statements, whether we like it or not.

If writing "print(something)" feels better than "print something",
I suggest you define a function called writeln etc and use that
instead of print, e.g.

 >>> import sys
 >>> def writeln(*args):
...     sys.stdout.write(" ".join(map(str, args)) + '\n')



More information about the Python-list mailing list