Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a recommended format for multi-line imports?

People also ask

Why should you avoid using `` import *`` code?

Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it). Because you don't know exactly what is imported and can't easily find from which module a certain thing was imported (readability).

Why import * is not recommended?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.

Should imports always be at top?

PEP 8 recommends putting imports at the top. It's often more convenient to get ImportError s when you first run your program rather than when your program first calls your function. Putting imports in the function scope can help avoid issues with circular imports.

Can we import multiple modules with single import statement?

Import multiple modulesYou can write multiple modules separated by commas after the import statement, but this is not recommended in PEP8. Imports should usually be on separate lines. If you use from to import functions, variables, classes, etc., as explained next, you can separate them with a comma.


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