TzurEl TzurEl - 1 year ago 60
Python Question

Break one line of "if else" statement into multiple lines

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.

Answer Source

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)
    ex = foo()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download