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?
The difference between
import moduleandfrom module import foois 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 moduleimportstatements. Don’t need to add any additional imports to start using another item from the modulemodule.fooin your code can be tedious and redundant (tedium can be minimized by usingimport module as mothen typingmo.foo)from module import foofooimportstatementfoo. For example, it’s less clear whatceil()does compared tomath.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 theimportany more but it’s extremely difficult to be sure.