97

When importing modules in Python, 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?

mrj
  • 849
  • 2
  • 8
  • 18
Cody Brown
  • 1,409
  • 2
  • 15
  • 19
  • 1
    The first could be ever so slightly faster, depending upon interpreter implementation, I think, but I can't really think of any other way they would be different from the perspective of a language user. – Silas Ray Feb 21 '13 at 20:16
  • 2
    If you look at some linters they recommend an import per line. This is suggested because it leads to less merge conflicts. –  Jul 02 '19 at 18:23

6 Answers6

137

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

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

informatik01
  • 16,038
  • 10
  • 74
  • 104
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • I sort of thought this was the case. All in the eyes of the programmer. I never knew about the single line module issues though, I use that everywhere, going to need to make some alterations. Thanks! – Cody Brown Feb 21 '13 at 20:44
  • 5
    @CodyBrown: `single line issues` <- they're not really issues; more like style guides. There's absolutely no mandate to follow them. You may be working on a team that uses a completely different style guide, in which case PEP-8 becomes completely inapplicable – inspectorG4dget Feb 21 '13 at 21:42
  • 4
    @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. – teewuane Sep 24 '14 at 17:16
  • @inspectorG4dget Perfect! I'll go with the splitting the line. In my case it actually helps to make the code more readable. Thank you! – teewuane Sep 24 '14 at 20:39
50

To add to some of the questions raised from inspectorG4dget's answer, you can also use tuples to do multi-line imports when folder structures start getting deeply nested or you have modules with obtuse names.

from some.module.submodule.that_has_long_names import (
    first_item,
    second_item,
    more_imported_items_with_really_enormously_long_names_that_might_be_too_descriptive,
    that_would_certainly_not_fit,
    on_one_line,
)

This also works, though I'm not a fan of this style:

from module import (a_ton, of, modules, that_seem, to_keep, needing,
                    to_be, added, to_the_list, of_required_items)
Community
  • 1
  • 1
Jacob Powers
  • 601
  • 6
  • 8
  • 3
    Personally, I find this to be my personal favorite style. It doesn't require escaping line breaks or redundancy – Ben Reed Dec 03 '17 at 20:45
  • Using this style also allows your linter to highlight unused imports one by one. This way I can easily identify, navigate to, and remove unused imports with the help of my linter. When imports are all on one line, it's more work to identify which is the unused import. I use the `scrooloose/syntastic` Vim plugin, and I navigate from one linting issue to the next, removing the unused import then becomes a two-keystroke step `dd`. This also produces easy-to-read diffs and conflict-free merges as mentioned in this answer: https://stackoverflow.com/a/71134644/332936 – Stew Apr 18 '23 at 20:38
11

I would suggest not to follow PEP-8 blindly. When you have about half screen worth of imports, things start becoming uncomfortable and PEP-8 is then in conflicts with PEP-20 readability guidelines.

My preference is,

  1. Put all built-in imports on one line such as sys, os, time etc.
  2. For other imports, use one line per package (not module)

Above gives you good balance because the reader can still quickly glance the dependencies while achieving reasonable compactness.

For example,

My Preference

# one line per package

import os, json, time, sys, math
import numpy as np
import torch, torch.nn as nn, torch.autograd, torch.nn.functional as F
from torchvision models, transforms

PEP-8 Recommandation

# one line per module or from ... import statement

import os
import json
import time
import sys
import math

import numpy as np

import torch
from torch import nn as nn, autograd, nn.functional as F
from torchvision import models, transforms
Shital Shah
  • 63,284
  • 17
  • 238
  • 185
  • 1
    You can list imports in alphabetical order, which makes your imports much more readable and searchable than how your example demonstrates. – MattSt May 30 '22 at 07:07
4

A concern not mentioned by other answers is git merge conflicts.

Let's say you start with this import statement:

import os

If you change this line to import os, sys in one branch and import json, os in another branch, you will get this conflict when you attempt to merge them:

<<<<<<< HEAD
import os, sys
=======
import json, os
>>>>>>> branch

But if you add import sys and import json on separate lines, you get a nice merge commit with no conflicts:

--- a/foo.py
+++ b/foo.py
@@@ -1,2 -1,2 +1,3 @@@
+ import json
  import os
 +import sys

You will still get a conflict if the two imports were added at the same location, as git doesn't know which order they should appear in. So if you had imported time instead of json, for example:

import os
<<<<<<< HEAD
import sys
=======
import time
>>>>>>> branch

Still, it can be worth sticking with this style for the occasions where it does avoid merge conflicts.

1

Imports should usually be on separate lines as per PEP 8 guidelines.

# Wrong Use
import os, sys
# Correct Use
import os
import sys

For more import based PEP 8 violations and fixes please check this out https://ayush-raj-blogs.hashnode.dev/making-clean-pr-for-open-source-contributors-pep-8-style.

pythonboi
  • 11
  • 1
1

Both are same. Use from module import a, b, c, d.

If you want to import only one part of a module, use:

from module import a

If u want to import multiple codes from same module, use:

from module import a,b,c,d

No need to write all in separate lines when both are same.

Alex
  • 785
  • 6
  • 9