Module import question

Mats Wichmann mats at python.org
Sun Aug 9 11:40:51 EDT 2020


On 8/9/20 12:51 AM, Gabor Urban wrote:
> Hi guys,
> 
> I have a quite simple question but I could not find the correct answer.
> 
> I have twoo modules A and B. A imports B. If I import A in a script, Will
> be B imported automatically? I guess not, but fő not know exactly.
> 
> Thanks for your answer ín advance,

Think of import as meaning "make available in namespace".

If A simply imports B, then B is available in A's namespace as a name
for module B's namespace, and you can access things inside B by
qualifying the names: if Foo is in B, then B.Foo works, Foo does not.
Different forms of the import statement change the way symbols are made
available, e.g you can do

from B import *    # all the symbols from B are in A's global namespace,
Foo works now
import B as Baz    # B is available through the name Baz, so use Baz.Foo
etc.

If you have a separate program, call it C, and it imports A, then A is
available in C as a name for module A's namespace.  That said nothing
about B, so the symbol B is not available in C.  But if C calls
something in A that uses B, then that will work fine, because B exists
in A's namespace. And you can access symbols from B by properly
qualifying: A.B.Foo.

Which is it you meant by "imported automatically"?

See Byung-Hee's example to see this in action without all these messy
words :)


More information about the Python-list mailing list