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

后端 未结 6 1249
半阙折子戏
半阙折子戏 2020-12-04 05:32

The python style guide suggests to group imports like this:

Imports should be grouped in the following order:

  1. standard library imp
6条回答
  •  广开言路
    2020-12-04 06:18

    Imports are generally sorted alphabetically and described in various places beside 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 duplicated imports

    There is nothing available in PEP 8 regarding sorting.So its all about choice what you use.

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

    for eg 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 is

    for each imported group the order of imports should be:
    import . style lines in alphabetical order
    from . import  style in alphabetical order
    

    References:

    • https://code.google.com/p/soc/wiki/PythonStyleGuide
    • https://github.com/reddit/reddit/wiki/PythonImportGuidelines
    • http://docs.openstack.org/developer/hacking/
    • http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#grouping-and-sorting

    PS: the isort utility automatically sorts your imports.

提交回复
热议问题