In Python3, does import
work transitively?
For example, if a module contains import A
, and the module for A
contains import B
, then does the module import B
indirectly?
Compared to other languages:
In Java, some said that import
doesn't work transitively, see https://stackoverflow.com/a/46677664.
in C, include
does work transitively. For example, if a file contains #include "A.h"
, and A.h
contains #include "B.h"
, then the file also includes B.h
indirectly.
How do Python's import
, Java's import, and C's
include` work under the hook to have differences?
Thanks.
When you're importing a module to your namespace, Python creates a module namespace. This goes recursively; when you import A
, it will import B
and if it fails you'll get an error. Otherwise it will be accessible through A.B
# temp.py
def func_in_b():
print 'this is B'
# temp2.py
import temp
def func_in_a():
print 'this is A'
>>> import temp2
>>> temp2.func_in_a()
this is A
>>> temp2.temp.func_in_b()
this is B