pythoncoding-stylepython-importpep8

What's the correct way to sort Python `import x` and `from x import y` statements?


The python style guide suggests to group imports like this:

Imports should be grouped in the following order:

  1. standard library imports
  2. related third party imports
  3. local application/library specific imports

However, it does not mention anything how the two different ways of imports should be laid out:

from foo import bar
import foo

There are multiple ways to sort them (let's assume all those import belong to the same group):

PEP8 does not mention the preferred order for this and the "cleanup imports" features some IDEs have probably just do whatever the developer of that feature preferred.

I'm looking for another PEP clarifying this or a relevant comment/email from the BDFL (or another Python core developer). Please don't post subjective answers stating your own preference.


Solution

  • Imports are generally sorted alphabetically and described in various places besides PEP 8.

    Alphabetically sorted modules are quicker to read and searchable. After all, Python is all about readability. Also, it is easier to verify that something is imported, and avoids duplicate imports.

    There is nothing available in PEP 8 regarding sorting. So it's all about choosing what you use.

    According to few references from reputable sites and repositories, also popularity, Alphabetical ordering is the way.

    for e.g. like this:

    import httplib
    import logging
    import random
    import StringIO
    import time
    import unittest
    from nova.api import openstack
    from nova.auth import users
    from nova.endpoint import cloud
    

    OR

    import a_standard
    import b_standard
    
    import a_third_party
    import b_third_party
    
    from a_soc import f
    from a_soc import g
    from b_soc import d
    

    Reddit official repository also states that In general PEP-8 import ordering should be used. However, there are a few additions which are that for each imported group the order of imports should be:

    import <package>.<module> style lines in alphabetical order
    from <package>.<module> import <symbol> style in alphabetical order
    

    References:

    PS: the isort utility automatically sorts your imports.