简体   繁体   中英

Long comments on single lines of code in Python

Despite have read what PEP8 has to say on the subject of comments, I still wonder how best to comment single lines of code in Python.

The example given is fine when the line of code in question is (very) short:

x = x + 1                 # Compensate for border

But if the line or the comment is longer things get more difficult. For example:

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 fairly long, and so is the line of code, making the whole thing longer than the acceptable line length.

I usually put the comment above the line, but it's then not clear 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 tend to get around this by inserting a newline 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've also done this, but it seems a bit overblown:

"""
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 of doing this?

The style that I seem to see the most is putting the comment one line above. In most cases, someone reading your code will understand when the documented behaviour ends. If it is not clear what the code underneath the referenced line does, maybe it needs to commented too.

I would also try to condensate my comments. instead of:

# 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

this would be short enough for PEP8. Although this might not be possible with longer lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM