Search code examples
pythonpython-2.7pep8

Is there a recommended format for multi-line imports?


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?


Solution

  • 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.