← Back to team overview

launchpad-dev team mailing list archive

Re: New coding standard for formatting imports

 

Am 18.08.2010 16:26, schrieb Brad Crittenden:
> Henning Eggers will be writing a tool to reformat imports and will do it all at once.

OK, the tool is ready and first tests look very promising. Here is what it
will do:

- Identify the import section at the top of each .py file. Other imports in
the file are not treated. Early "from __future__" statements are skipped, too.

- Group the imports in three sections as specified by PEP8[1]:
  1. All standard library imports. I used this list[2].
  2. Anything not in the other two sections, considered third-party modules.
     Most notably lazr, storm and twisted but also pytz.
  3. All imports beginning with "lp" and "canonical", considered local.

- Sort import statements within each section alphabetically by module.

- Break up multiple modules in simple import lines.

    import os, sys, unittest

  becomes

    import os
    import sys
    import unittest

- Statements importing only one object are placed on a single line unless the
statement becomes too long for the line length limit of 78.

- Multiple objects in one import statement are each placed on a line by
itself, in list style (the core of this change). Objects are sorted
alphabetically using Python's "sorted" function which sorts Capital letters
*first*. I know this is a change to the previous style but who are we to argue
with Python? ;)

  from lp.myapp.interfaces.mymodule import (
      IMyInterface,
      JustToProveThePoint,
      a_lower_case_object,
      b_is_lower_case_too,
      )

- Multiple import statements for the same module will be conflated into one.

- The script will warn me about comments in the import section as it is
dropping them and I will have to look into the file to see what needs to be
done to keep them. The first tests show that there aren't too many of these cases.

- It will also warn about modules being imported via "import ..." and
"from...import" in the same file and I will have to fix those bugs... ;)

If anybody sees a problem with any of these changes, please let me know.

For whoever is interested, here is the script:
lp:~henninge/+junk/format-imports

Cheers,
Henning


[1] http://www.python.org/dev/peps/pep-0008/
[2] http://docs.python.org/release/2.5.4/lib/modindex.html



Follow ups

References