Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 703
Filip Dupanović Avatar asked Apr 02 '09 16:04

Filip Dupanović


People also ask

What is the difference between import and from import?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.

What is the use of from module import?

from .. import statement allows you to import specific functions/variables from a module instead of importing everything. In the previous example, when you imported calculation into module_test.py , both the add() and sub() functions were imported.

How can we import a module in Python using from?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

What does from module import * mean in Python?

It just means that you import all(methods, variables,...) in a way so you don't need to prefix them when using them.


1 Answers

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 module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

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.

like image 135
Mark Roddy Avatar answered Sep 20 '22 08:09

Mark Roddy