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?
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.
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.
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,
)
Usually with Tkinter, it is okay to just use from Tkinter import *
as the module will only export names that are clearly widgets.
PEP 8 does not list any conventions for such a case, so I guess it is up to you to decide what is the best option. It is all about readability, so choose whatever makes it clear that you are importing stuff from a single module.
As all those names are made available in your scope, I personally think that options 2 is the most clearest as you can see the imported names the best. You then could even split it up more to maybe group those names together that belong with each other. In your example I might put Tk
, Frame
and Canvas
separately as they group widgets together, while having Button
and Text
separately as they are smaller components in a view.