3

I want to break this code:

ex = func(object) if not self.is_object() else foo()

to multiple lines (pep 8). What is the best way to do it? I thought about this:

ex = func(object) \
    if not self.is_object() \
    else foo()

But this seems a bit ugly and not very neat. Is there another way?

Edit: This is different from just breaking a line into multiple lines, because this is a special "expression if stmnt else stmnt" and not just breaking any python code.

TzurEl
  • 792
  • 3
  • 9
  • 15
  • It's not that special; it's just a ternary operator `... if ... else ...` as opposed to a binary operator `... + ...`. – chepner Sep 28 '16 at 16:59

4 Answers4

5

What exactly is ugly here? Backslashes? There's a way to avoid them
To split a statement into multiple lines, use parentheses around the conditional like so:

ex = (func(object)
      if not self.is_object()
      else foo())

But perhaps it would be better to write an entire conditional structure:

if not self.is_object():
    ex = func(object)
else:
    ex = foo()
illright
  • 3,991
  • 2
  • 29
  • 54
0

The best way to break that into multiple lines is as follows:

if not self.is_object():
    ex = func(object)
else:
    ex = foo()

If you don't need it to be contained in a single expression, you might as well use a traditional if..else block.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

If you absolutely must avoid the ternary expression (many people seem to dislike them) the canonical method would be neater:

if self.is_object():
    ex = foo()
else:
    ex = func(object)

which has the advantage that any Python programmer can read it without wondering what on Earth is going on!

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

Might be best to break it into an if statement if it doesn't fit onto one line:

if self.is_object():
    ex = foo()
else:
    ex = func(object)

Or you can use parentheses:

ex = (func(object)
       if not self.is_object()
       else foo())
flornquake
  • 3,156
  • 1
  • 21
  • 32