pythonmodule

Python Module Import: Single-line vs Multi-line


What is the difference between these:

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

It makes sense always to condense code and use the first example, but code samples do the second. Is it just preference?


Solution

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

    @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):