From this post:
Python: Disabling relative import
it is indicated that relative import can be disabled by:
from __future__ import absolute_import
However this rule seems cannot be extended to Jupyter notebook. Here is a quick experiment, when I create a python file that has identical name with a python package (in this case networkx). It can cause all absolute import of that package to fail. The following is a screenshot that describe this case:
The installed package 'network' already contains the submodule 'drawing', yet the import failed with the following message:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-2-e38c4f8fc4a0> in <module>
1 from __future__ import absolute_import
2
----> 3 from networkx import drawing
ImportError: cannot import name 'drawing'
How to fix it in Jupyter notebook or Jupyter lab? Does this means there is no way I can avoid relative import?
UPDATE: thanks a lot for the answers, one of them is to suggest that I have a corrupted PYTHONPATH (or sys.path), this is not the case, I have added the following line to show the inconsistency of PYTHONPATH and resolved module path:
from __future__ import absolute_import
import os
import sys
for p in sys.path:
print(p)
print("=================")
import networkx
print(os.path.abspath(networkx.__file__))
from networkx import drawing
result:
> /home/shared/anaconda3/lib/python36.zip
> /home/shared/anaconda3/lib/python3.6
> /home/shared/anaconda3/lib/python3.6/lib-dynload
> /home/peng/.local/lib/python3.6/site-packages
> /home/shared/anaconda3/lib/python3.6/site-packages
> /home/shared/anaconda3/lib/python3.6/site-packages/IPython/extensions
> /home/peng/.ipython
> ================= /home/peng/git/convnet-abstraction/slide/package/networkx.py
> --------------------------------------------------------------------------- ImportError Traceback (most recent call
> last) <ipython-input-4-d28ac292787c> in <module>
> 12 print(os.path.abspath(networkx.__file__))
> 13
> ---> 14 from networkx import drawing
>
> ImportError: cannot import name 'drawing'
Here is another screenshot: