Search code examples
pythonimportpep8

Pep 8 Conflict, Imports exceed 72 characters


What is / is there a best practice around long import statements in Python? Pep 8 allows 72-99 character long lines, but I find that I often exceed this limit which is a shame when I've made an effort to format the rest of my code.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.

Source: https://www.python.org/dev/peps/pep-0008/

Now of course, you can just import an entire package. i.e. import numpy as np, however I typically want to shorten my imports as much as possible to avoid reduce load times.


Solution

  • You can often avoid exceeding the the limit by putting parentheses around expressions. If there are parentheses you can break the expression inside them up over as many lines as you want. The other less-desirable way is to end a line with a backslash character which causes the newline following it to be ignored.

    This is explained in the Maximum Line Length section of PEP 8.