Long comments on single lines of code in Python

Although I read what PEP8 has to say about comments, I'm still curious about how best to write single lines of code in Python.

The above example is good if the line of code in question is very short:

x = x + 1 # Compensate for border 

But if the line or comment is longer, things get more complicated. For instance:

 import numpy as np import matplotlib.pyplot as plt a = np.random.random([3, 3]) b = np.random.random([3, 3]) coords = zip(a.ravel(), b.ravel()) # match elements of a with elements of b ignoring shape plt.scatter(*zip(*coords)) 

The comment is quite long, as is the line of code, which takes longer than the allowed line length.

I usually put a comment above the line, but then it is unclear whether the comment applies to the plt line or not:

 # match elements of a with elements of b ignoring shape coords = zip(a.ravel(), b.ravel()) plt.scatter(*zip(*coords)) 

I try to get around this by inserting a new line between the two lines:

 # match elements of a with elements of b ignoring shape coords = zip(a.ravel(), b.ravel()) plt.scatter(*zip(*coords)) 

I did this too, but it seems a bit bloated:

 """ match elements of a with elements of b ignoring shape """ # ================================ coords = zip(a.ravel(), b.ravel()) # ================================ plt.scatter(*zip(*coords)) 

Is there an accepted way to do this?

+5
source share
1 answer

The style that I seem to see the most puts the comment one line above. In most cases, someone reading your code will understand when the documented behavior ends. If it’s not clear what the code does under the link bar, it may need to comment too.

I would also try to summarize my comments. instead:

 # match elements of a with elements of b ignoring shape coords = zip(a.ravel(), b.ravel()) 

I would write:

 coords = zip(a.ravel(), b.ravel()) # match elements of a and b, ignore shape 

it will be short enough for PEP8. Although this may not be possible when using longer strings.

0
source

All Articles