The Python Oracle

Is there a recommended format for multi-line imports?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 Is There A Recommended Format For Multi-Line Imports?
00:35 Answer 1 Score 25
00:47 Accepted Answer Score 279
01:12 Answer 3 Score 17
01:34 Thank you

--

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

--

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,
)