Specific imports versus module imports in Python

I've always been a fan of explicit, separate imports in Python, vs generic module imports. Maybe it's because I like things to be explicit, or I've been spoiled by the way Eclipse Pydev deals with auto-importing, but I have an aversion towards generic module imports. To keep the code style consistent, I even rewrite to this style any foreign code that ends up in my code.

Specifically, I'm talking about:

from foo import Bar
Bar()

vs

import foo
foo.Bar()

Needless to say, I like the first style better.

There are advantages and disadvantages for each of the above methods:

from zope.app import component
from zope import component

Of course, some people sensed this problem and write code like:

class MyView(object):
    template = zope.app.pagetemplate.ViewPageTemplateFile('template.pt')

But this code is hard to read, hard to write and is almost at the limit with the self-imposed line length of 80 characters, which means most of the times it needs to be broken in two lines.

Today I became aware of what I consider the biggest advantage of using specific import (from foo import Bar). Heavy refactoring, in the absence of a comprehensive test suite, is a lot easier! When starting the program, the imports will fail and you get an immediate pointer to where you need to make a fix. If I would have used a generic module import, the error will have appeared only when trying to use the piece of code that calls foo.Bar().

TL;DR: use specific imports! If your editor doesn't support it, take some time to look at Eclipse Pydev or Netbeans, two free IDEs with Python support. You'll get:

Comments