Reputation:
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.
Upvotes: 10
Views: 3815
Reputation: 409
Import always imports the namespace of the module or package.
Package: A a directory containing __init__.py
Module: A file with the extension .py
If you have a file named a.py
with the content:
x=2
File named b.py
with the content:
import a
y=3
In the interpreter it will be
>>> import b
>>> b.y
3
>>> b.a.x
2
Packages are behaving differently(maybe not so intuitive, if you come from Java), having a directory structure like:
+ mypackage
+-__init__.py
+-test.py
A import of the package mypackage
wont import the module test.py
but only evaluate __init__.py
:
>>> import mypackage
>>> mypackage.test # will fail
Upvotes: 2
Reputation: 2119
C/C++'s #include
works on preprocessor level. Java and Python doesn't have a preprocessor. They are more smart, their VMs know about any modules you can import at runtime. Imports there is a way to avoid conflicts of names. In Java you may not use imports at all but then you should define full class names every time (e.g. java.util.List
instean of just List
). Almost the same for Python.
Upvotes: 0
Reputation: 11338
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
Upvotes: 9