Why is "import *" bad?

  • Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it).

  • Because you don't know exactly what is imported and can't easily find from which module a certain thing was imported (readability).

  • Because you can't use cool tools like pyflakes to statically detect errors in your code.


According to the Zen of Python:

Explicit is better than implicit.

... can't argue with that, surely?


You don't pass **locals() to functions, do you?

Since Python lacks an "include" statement, and the self parameter is explicit, and scoping rules are quite simple, it's usually very easy to point a finger at a variable and tell where that object comes from -- without reading other modules and without any kind of IDE (which are limited in the way of introspection anyway, by the fact the language is very dynamic).

The import * breaks all that.

Also, it has a concrete possibility of hiding bugs.

import os, sys, foo, sqlalchemy, mystuff
from bar import *

Now, if the bar module has any of the "os", "mystuff", etc... attributes, they will override the explicitly imported ones, and possibly point to very different things. Defining __all__ in bar is often wise -- this states what will implicitly be imported - but still it's hard to trace where objects come from, without reading and parsing the bar module and following its imports. A network of import * is the first thing I fix when I take ownership of a project.

Don't misunderstand me: if the import * were missing, I would cry to have it. But it has to be used carefully. A good use case is to provide a facade interface over another module. Likewise, the use of conditional import statements, or imports inside function/class namespaces, requires a bit of discipline.

I think in medium-to-big projects, or small ones with several contributors, a minimum of hygiene is needed in terms of statical analysis -- running at least pyflakes or even better a properly configured pylint -- to catch several kind of bugs before they happen.

Of course since this is python -- feel free to break rules, and to explore -- but be wary of projects that could grow tenfold, if the source code is missing discipline it will be a problem.


That is because you are polluting the namespace. You will import all the functions and classes in your own namespace, which may clash with the functions you define yourself.

Furthermore, I think using a qualified name is more clear for the maintenance task; you see on the code line itself where a function comes from, so you can check out the docs much more easily.

In module foo:

def myFunc():
    print 1

In your code:

from foo import *

def doThis():
    myFunc() # Which myFunc is called?

def myFunc():
    print 2

It is OK to do from ... import * in an interactive session.