Use “import module” or “from module import”?


I"ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I"ve just started with Python and I"m trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what"s the best way to avoid any gotchas down the road?

Answer rating: 541

The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module

  • Pros:
    • Less maintenance of your import statements. Don"t need to add any additional imports to start using another item from the module
  • Cons:
    • Typing in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing

from module import foo

  • Pros:
    • Less typing to use foo
    • More control over which items of a module can be accessed
  • Cons:
    • To use a new item from the module you have to update your import statement
    • You lose context about foo. For example, it"s less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don"t use from module import *.

For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from "module", making it easy to get to the point where you think you don"t use the import any more but it"s extremely difficult to be sure.

Answer rating: 211

There"s another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I"ve needed it from time to time.

Due to the way references and name binding works in Python, if you want to update some symbol in a module, say, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:

module foo:

bar = "apples"

module a:

import foo = "oranges"   # update bar inside foo module object

module b:

import foo           
print        # if executed after a"s "" assignment, will print "oranges"

However, if you import symbol names instead of module names, this will not work.

For example, if I do this in module a:

from foo import bar
bar = "oranges"

No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its bar.