Cody Brown Cody Brown - 1 year ago 42
Python Question

Python Module Import: Single-line vs Multi-line

So this is just a simple question. In python when importing modules, what is the difference between this:

from module import a, b, c, d

and this

from module import a
from module import b
from module import c
from module import d

To me it makes sense always to condense code and use the first example, but I've been seeing some code samples out there dong the second. Is there any difference at all or is it all in the preference of the programmer?

Answer Source

There is no difference at all. They both function exactly the same.

However, from a stylistic perspective, one might be more preferable than the other. And on that note, the PEP-8 for imports says that you should compress from module import name1, name2 onto a single line and leave import module1 on multiple lines:

Yes: import os
     import sys

No:  import sys, os

Ok: from subprocess import Popen, PIPE

In response to @teewuane's comment (repeated here in case the comment gets deleted):

@inspectorG4dget What if you have to import several functions from one module and it ends up making that line longer than 80 char? I know that the 80 char thing is "when it makes the code more readable" but I am still wondering if there is a more tidy way to do this. And I don't want to do from foo import * even though I am basically importing everything.

The issue here is that doing something like the following could exceed the 80 char limit:

from module import func1, func2, func3, func4, func5

To this, I have two responses (I don't see PEP8 being overly clear about this):

Break it up into two imports:

from module import func1, func2, func3
from module import func4, func5

Doing this has the disadvantage that if module is removed from the codebase or otherwise refactored, then both import lines will need to be deleted. This could prove to be painful

Split the line:

To mitigate the above concern, it may be wiser to do

from module import func1, func2, func3, \
     func4, func5

This would result in an error if the second line is not deleted along with the first, while still maintaining the singular import statement