Difference between "import X" and "from X import *"?

temporary_user_name picture temporary_user_name · Sep 4, 2012 · Viewed 30.6k times · Source

In Python, I'm not really clear on the difference between the following two lines of code:

import X

or

from X import *

Don't they both just import everything from the module X? What's the difference?

Answer

BrenBarn picture BrenBarn · Sep 4, 2012

After import x, you can refer to things in x like x.something. After from x import *, you can refer to things in x directly just as something. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import * is discouraged.

You can also do from x import something, which imports just the something into the local namespace, not everything in x. This is better because if you list the names you import, you know exactly what you are importing and it's easier to avoid name conflicts.