Python Module Import: Single-line vs Multi-line

后端 未结 3 1379
天涯浪人
天涯浪人 2020-12-13 08:07

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

3条回答
  •  误落风尘
    2020-12-13 08:34

    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

提交回复
热议问题