This question already has an answer here:
- Use 'import module' or 'from module import'? 13 answers
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?
You should never use
from X import *
unless you really know what you're doing. You can get symbols from module X that conflict with symbols from another module or even your own program. The only exception I have to that rule is sometimesfrom math import *
.You can use the form
from X import y
to get a single thing from a module.If you use the
import X
form, not only do you make your usage of the module explicitX.y
but you can now use thereload
function if you make changes to the module and need to reimport it.from X import *
imports all elements from the moduleX
into the current namespace.import X
imports X but doesn't "merge" the namespaces. E.g.:Module X:
Your code:
Or:
There are differences, some simple, others requiring more explanation.
import X
just imports the entire module (read: "runs the module"), and assigns it a name in the local scope. The name can be aliased like so:import X as Y
from X import *
imports all of the attributes of moduleX
into the local scope, by default. Here's an example of different usage:Where this gets slightly more complicated is when a module defines
__all__
. This changes the semantics offrom X import *
to mean "import everything that is listed in the__all__
property." This allows module writers to have control over which functions and objects are exported from their module.Creates a label in the local namespace that references the module object.
Creates a label for every member attribute of the
X
module, directly in the local namespace.Both operations add
X
tosys.modules
, true, but the effect on the local namespace is the difference.import X
: this imports everything asX.var1
,X.var2
,etcfrom X import *
: this imports everthing asvar1
,var2
etc ,i.e it floods the local namespacesee the difference after two calls:
After
import x
, you can refer to things inx
likex.something
. Afterfrom x import *
, you can refer to things inx
directly just assomething
. 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, thefrom x import *
is discouraged.You can also do
from x import something
, which imports just thesomething
into the local namespace, not everything inx
. 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.