if, continuation and indentation

A

Aahz

While it's not PEP material, I tend to use the coding standards I
learned working for Computer Sciences Corporation (10 yrs ago, so
things may have changed) that mandated 2 levels of indentation
for continued lines, turning the above into

if (width == 0 and
height == 0 and
color == 'red' and
emphasis == 'strong' or
highlight> 100):
# or the closing "):" on this line,
# aligned with the previous line
raise ValueError("sorry, you lose")

+1
 
G

Greg Couch

I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

    if (width == 0 and
        height == 0 and
        color == 'red' and
        emphasis == 'strong' or
        highlight > 100):
        raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?

Thanks,
Henrik

To show another alternative, I like:

if (width == 0
and height == 0
and color == 'red'
and emphasis == 'strong'
or highlight > 100):
raise ValueError("sorry, you lose")

This works because and/or can not start an expression, so it is
obvious
that they continue the expression from the previous line. If I run
out
of room to put a full and/or clause on one line, then I'll indent the
subclause two levels.

-- Greg
 
P

Pete Forman

HH said:
> I have a question about best practices when it comes to line
> wrapping/ continuation and indentation, specifically in the case of
> an if statement.

There are several good suggestions for formatting but no-one has
mentioned rewriting the code. Use a boolean variable to hold the
result of the condition and then the if statement is more readable.
 
J

Jean-Michel Pichavant

Pete said:
There are several good suggestions for formatting but no-one has
mentioned rewriting the code. Use a boolean variable to hold the
result of the condition and then the if statement is more readable.
It has been suggested. ;)

JM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top