The Python Oracle

Is there a recommended format for multi-line imports?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:44 Accepted answer (Score 239)
01:21 Answer 2 (Score 22)
01:41 Answer 3 (Score 11)
02:16 Thank you

--

Full question
https://stackoverflow.com/questions/1437...

Answer 1 links:
[PEP 328]: http://www.python.org/dev/peps/pep-0328/

Answer 2 links:
[PEP328]: https://www.python.org/dev/peps/pep-0328...
[Django]: https://github.com/django/django/blob/ma...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #pep8

#avk47



ACCEPTED ANSWER

Score 279


Personally I go with parentheses when importing more than one component and sort them alphabetically. Like so:

from Tkinter import (
    Button,
    Canvas,
    DISABLED,
    END,
    Entry,
    Frame,
    LEFT,
    NORMAL,
    RIDGE,
    Text,
    Tk,
)

This has the added advantage of easily seeing what components have been added / removed in each commit or PR.

Overall though it's a personal preference and I would advise you to go with whatever looks best to you.




ANSWER 2

Score 25


Your examples seem to stem from PEP 328. There, the parenthesis-notation is proposed for exactly this problem, so probably I'd choose this one.




ANSWER 3

Score 17


I would go with the parenthesis notation from the PEP328 with newlines added before and after parentheses:

from Tkinter import (
    Tk, Frame, Button, Entry, Canvas, Text, 
    LEFT, DISABLED, NORMAL, RIDGE, END
)

This is the format which Django uses:

from django.test.client import Client, RequestFactory
from django.test.testcases import (
    LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase,
    skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature,
)
from django.test.utils import (
    ignore_warnings, modify_settings, override_settings,
    override_system_checks, tag,
)