Search code examples
pythonpep8

python multiline comment indent


I have a Django project, and in some places we have multiline comments indented as follows:

field = models.IntegerField(default=0, null=True)  # 0-initial_email_sent
                                                   # 1-second_email_sent
                                                   # 2-third_email_sent

This clearly violates PEP, but, in my opinion, helps with readability. Of course, I could put comments like this:

# 0-initial_email_sent
# 1-second_email_sent
# 2-third_email_sent
field = models.IntegerField(default=0, null=True)

, but I would much rather prefer the first one.

Is there any way to indent comments as such without violating PEP 8?


Solution

  • Magic numbers are evil, so the best documentation here is to use named (pseudo) constants:

    INITIAL_EMAIL_SENT = 0
    SECOND_EMAIL_SENT = 1
    THIRD_EMAIL_SENT = 2
    field = models.IntegerField(default=INITIAL_EMAIL_SENT, null=True) 
    

    As a general rule, the less you have to comment the better (clear code needs no or very very few comments).

    For a more general answer about where to place comments, specially multiline ones:

    1. having the comments before the commented item is what most python users expect so for the majority of is it is "more readable"

    2. it also makes code editing easier (you don't have comments mixed with code, you don't have to maintain comments indentation etc).

    If it's your own personal project and you don't plan on sharing it or having anyone else working on it you are (hopefully) free to use any coding style / convention, pep08 is no religion, but if someone else ever have to work on your code he will certainly hate you for commenting this way.