pythonpython-importgoogle-style-guide

Multiple imports according to google style guide


I do not understand what is written in Google Python Style Guide about multiple imports per line.

Is it ok (according to Google Style Guide) to have it this way:

from wagtail.wagtailimages.blocks import ImageChooserBlock, EmbedBlock

or do I have to write it like this:

from wagtail.wagtailimages.blocks import ImageChooserBlock
from wagtail.wagtailembeds.blocks import EmbedBlock

Thanks.


Solution

  • If, in that linked style guide, you click on the right-facing triangle just under the section "Imports formatting", you get some positive and negative examples. This is one of the positive examples:

    import foo
    from foo import bar
    from foo.bar import baz
    from foo.bar import Quux
    from Foob import at
    

    As you can see, two items are imported from the single module foo.bar and they are listed on separate lines.

    So in your two examples, the Google Style Guide wants you to use the second--separate lines. Note that I am not saying that is what you really should do, just that apparently the Google Style Guide says you should do it, which seems to be your question.

    On the other hand, the Python Style Guidelines for The Chromium Projects, which is obviously also by Google, says

    • It is OK to import packages, modules, and things within a module.  This is mentioned solely because it contradicts the section on imports in the Google Style Guide (which, remember, is not an authority for Chromium OS).
      • Said another way, this is completely OK: from subprocess import Popen, PIPE

    That example, stated to be OK, does import multiple items from one module in one line. So make your choice what your authority will be.