Is there a recommended format for multi-line imports?

Manuel Alvarez picture Manuel Alvarez · Jan 17, 2013 · Viewed 32k times · Source

I have read there are three ways for coding multi-line imports in python

With slashes:

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

Duplicating senteces:

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

With parenthesis:

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

Is there a recomended format or a more elegant way for this statements?

Answer

Brendan Maguire picture Brendan Maguire · Jan 17, 2013

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.