Understanding The Difference Between Import X And From X.y Import Z
Solution 1:
If you import A
, and then try to access A.B
, then B
must be a valid attribute present in module A
. For instance:
# A.pyfrom . import B
# or
B = 'foo'
If A
contains the above code, then inside A
, B
is a valid local name and by extension an accessible attribute of module A
. However, if module A
does not define any B
, then you can't access it when you import A
.
Now, import A.B
or from A.B import ...
explicitly looks not at the attributes of the modules, but at the files and folders. So even if inside A.py
there's no symbol B
defined, as long as there's a file B.py
or folder B
, import
will import it.
Solution 2:
These are equivalent:
from mod importvalvalimport mod
mod.val
As are these:
from mod1.mod2 importvalvalimport mod1.mod2
mod1.mod2.val
But this doesn't work, as mod2
is not imported:
import mod1
mod1.mod2.val
If you add import mod2
inside mod1.py
(or mod1/__init__.py
), then mod2
becomes a value exported by mod1
, and the last example will work. distutils
does not import distutils.util
, so you have to import it yourself in order to gain access to its exported members.
Post a Comment for "Understanding The Difference Between Import X And From X.y Import Z"