Skip to content

Instantly share code, notes, and snippets.

@therealzanfar
Created May 31, 2024 22:51
Show Gist options
  • Save therealzanfar/482964447b87a32e34818629c65f1463 to your computer and use it in GitHub Desktop.
Save therealzanfar/482964447b87a32e34818629c65f1463 to your computer and use it in GitHub Desktop.
Python Code Review

Python Code Review

Work in Progress

Introduction

A common request in /r/learnpython is for a review of existing code. While I have no intention of discouraging that practice, 90% of submissions include the same, basic issues. This is a list of those most common issues along with an attempt to elaborate on the issue and possible solutions.

Contents

Code Issues

Comments

Comments should be rare in Python code. For the most part, Python code is (or should be) readable enough that no description is necessary. MOST comments found in beginner code should be Docstrings instead (more below).

The exceptions are where the code is incomplete, is dealing with an unusual, external limitation, or where some "cleverness" was used. In this case, simply acknowleding the non-Pyhonic nature of the code and why it was necessary is enough. If a long description feels necessary, instead summarize and link to or reference a more exhaustive document.

Examples of unnecessary comments

  • students = []  # A list of students
    

    Completely obvious due to the fact that the variable is named "students" and it is initialized to a list.

  • ## Constants
    

    It's good to group your constants together, but that should be obvious by their formatting. See PEP8 for more details.

Examples of good comments

  • # For /reasons/, this request almost always fails the first time, so we try up to twice.
    # If the second request fails, something is really wrong.`
    
  • # See https://en.wikipedia.org/wiki/Fast_inverse_square_root for why this works
    

Docstrings

When you DO document Python code, most of it should be in docstrings. Every module, most functions or methods, and most classes should have a docstring briefly describing their purpose. When necessary, a docstring can ALSO contain a more in-depth description. Note that this longer description should always be IN ADDITION to the summary, and should still avoid re-describing the code.

Things that are usually NOT necessary in docstrings:

  • The name of the function, method, object, or module
  • Type information, unless used to generate external documentation

Good things to consider including in docstrings:

  • What exceptions the code might throw and when
  • Mutually-exclusive arguments

See PEP257 for implementation details.

Variable Names

Function or Method Names

Globals

Formatting

Project Issues

Toolchain Issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment