简体   繁体   中英

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.

Definitely the first way is fine. No one does the second option, that would be incredibly wasteful. You shouldn't import multiple different modules on the same line, but your first example is about getting multiple attributes from a single module.

Use the first one.

from wagtail.wagtailimages.blocks import ImageChooserBlock, EmbedBlock

To import multiple members you can use parenthesis and add a few newlines. Here is an example:

from OpenGL.GLUT import (GLUT_DEPTH, GLUT_DOUBLE, GLUT_RGB, glutCreateWindow,
                         glutDisplayFunc, glutInit, glutInitDisplayMode,
                         glutInitWindowSize, glutMainLoop, glutSwapBuffers)

Please note the difference:

You should not import multiple modules in one line:

import os, sys, platform    # DO NOT DO THIS!

But importing multiple members is just fine:

from math import sin, cos

hint: check out isort

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM