1

How do I make my python code prettier by shortening each row? For example: I have a really long if statement that I would like to make shorter => split it's length on to a couple of rows:

if (imgA.shape[0] != imgB.shape[0]) and (imgA.shape[1] != imgB.shape[1]) and (imgA.shape[2] != imgB.shape[2]):

I would like to have something like this:

    if (imgA.shape[0] != imgB.shape[0]) and 
      (imgA.shape[1] != imgB.shape[1]) and
      (imgA.shape[2] != imgB.shape[2]):

But I get a syntax error. Anyone?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Paul Erlenmeyer
  • 523
  • 2
  • 6
  • 29

5 Answers5

4

Just compare the arrays themselves?

if imgA.shape != imgB.shape:

Or if the rest of the elements are important:

if imgA.shape[0:2] != imgB.shape[0:2]:
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
3

you can put it in brackets:

if ((imgA.shape[0] != imgB.shape[0]) and 
    (imgA.shape[1] != imgB.shape[1]) and 
    (imgA.shape[2] != imgB.shape[2])):
    #do stuff
Derek Eden
  • 4,403
  • 3
  • 18
  • 31
2
if (
    (imgA.shape[0] != imgB.shape[0]) and 
    (imgA.shape[1] != imgB.shape[1]) and
    (imgA.shape[2] != imgB.shape[2])
):
    #do something

I usually rely on parentheses around arguments for breaking lines. This passes syntax in a Jupyter notebook.

Kermit
  • 4,922
  • 4
  • 42
  • 74
  • Although I don't like to use middle of nowhere indentation and I feel like the more segmented the code is more easily understood, the @Derek_Eden answer is probably more black-correct. – Kermit Sep 18 '19 at 00:14
2

Not an exact answer, but a good idea would be to assign variable names to each of these:

check_shape_0 = imgA.shape[0] != imgB.shape[0]
check_shape_1 = imgA.shape[1] != imgB.shape[1]
check_shape_2 = imgA.shape[2] != imgB.shape[2]

if (check_shape_0) and (check_shape_1) and (check_shape_2):
    #Do something

The renamed booleans would be more clear to future code readers on what's going on in your if statements.

With well picked variable name for booleans, if statements can be read almost like English, which makes the code very comfortable to read through.

And the shorter names makes your if statement smaller.

Farstride
  • 145
  • 11
1

You can use \ to break the same statement into multiple lines:

if (imgA.shape[0] != imgB.shape[0]) and \
    (imgA.shape[1] != imgB.shape[1]) and \
        (imgA.shape[2] != imgB.shape[2]):
Gabriel Cappelli
  • 3,632
  • 1
  • 17
  • 31