Consider the following directory structure
driver.py
m/__init__.py
m/bar.py
m/foo.py
With the following contents
driver.py:
import m.foo
print("Hello world!")
m/__init__.py: FILE IS EMPTY
m/bar.py:
print("I am bar")
m/foo.py:
import bar
print("I am foo")
Running python2 driver.py
works, running python3 driver.py
does not work (ImportError in m/foo.py trying to import bar) which leads me to ask several questions.
How did importing inside module that is inside a package work in Python 2.7 work? What is clear to me is, if I do a module import inside
driver.py
(e.g.import m.foo
) AFAIK this will search for the module in thesys.path
list that belongs to__main__
(in this casedriver.py
). What is not clear however is what happens when a module thatdriver.py
imports does an import itself (e.g.m/foo.py
tries to importm/bar.py
). It appears thatsys.path
inm/foo.py
is identical tosys.path
indriver.py
so I do not understand how Python 2.7 successfully doesimport bar
when them/
directory is not insys.path
.What changed between Python-2.7 and Python-3.x? It seems that I have to do
from . import bar
instead of
import bar
inside m/foo.py
for this trivial example to work under Python-3.x
UPDATE: It seems PEP328 is the reason for the change.
Thanks.