1

I have the following, rather large conditional already nested 4 tabs in. I don't want to create placeholder variables to reduce readability, but I also want to comply with line length.

What is the pythonic way to group and break this conditional up to multiple lines?

In the format if (a and b) or (c and d)

if self.container.name == 'bill' and self.container.box.chest.props.by_idnum 
    or self.container.name == 'steve' and self.container.box.trunk.props.by_idnum:
Matt_G
  • 506
  • 4
  • 14
  • 1
    pep-8 recommends something like http://dpaste.com/26T4DX6 – cs95 May 24 '18 at 19:11
  • I think this can solve your problem https://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python Regards – sebashc3712 May 24 '18 at 19:12
  • I also recommend an extra set of parentheses around the `and` parts, to make the precedence clear. – Barmar May 24 '18 at 19:13
  • 1
    turning `self.container` to `c` wouldn't reduce readability, it would be much clearer. Matter of opinion – Jean-François Fabre May 24 '18 at 19:13
  • Adding placeholder variables with good names won't reduce readability. `if bill_has_chest_props or steve_has_trunk_props:` shows much more intent that a long string of conditionals. – munk Jun 06 '18 at 20:24

1 Answers1

0

Neither yapf or autopep8 clean this up without parenthesis. But it's cleaner when you add them:

 % yapf code.py             
if (self.container.name == 'bill' and self.container.box.chest.props.by_idnum
        or self.container.name == 'steve'
        and self.container.box.trunk.props.by_idnum):
    pass

 % autopep8 code.py               
if (self.container.name == 'bill' and self.container.box.chest.props.by_idnum
        or self.container.name == 'steve' and self.container.box.trunk.props.by_idnum):
    pass

If it fits under 80 chars, I'd go with the latter. If this is still too long, I'd consider moving (a and b) into a function. Generally that may be preferable as then you can explain in the code - by the variable name - what (a and b) means.

Note: In this case it might be cleaner still as:

if (self.container.name in ['bill', 'steve']
        and self.container.box.trunk.props.by_idnum):
    pass
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535