DEV Community

Discussion on: Commenting: where?

Collapse
 
clpsplug profile image
C. Plug

This depends on the scope and the length of the comment and the PEP 8 coding standard.

  • On the same line if the comment:

    • is for only one line and it doesn't make the line longer than 120 characters (see PEP8,) or
    • it is for type-hinting a variable.
    run_something()  # Run something.
    instance = None  # type: Optional[SomeClass]
    
    • Such comment also has two spaces after the code as PEP8 recommends.
  • Before the block in question if the comment

    • is for a block of code or
    • the one-liner comment is so long it exceeds the 120 char limit.
    # A method streak to process an input.
    data = run_something(input)
    data = and_then_this(data)
    output = to_accomplish_your_task(data)
    
  • (Very rare) if an indented block is too big (or too complicated) to understand the structure, I may have to place a comment on the bottom of the block to indicate the end of what block.

  if something:
      VERY_LONG_CODE_HERE()
      SO_LONG_THAT_YOU_CANNOT_SEE()
      THE_START_AND_THE_END_OF_THE_IF_SIMULTANEOUSLY()
  # endif something:
Enter fullscreen mode Exit fullscreen mode

On the side note, I reckon one-liner comments usually are, or can be, made unnecessary by making the code obvious enough. Therefore, most of the comments in my code are above the lines involved.

Collapse
 
vulcanwm profile image
Medea

Cool!