2

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.

  1. 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 the sys.path list that belongs to __main__ (in this case driver.py). What is not clear however is what happens when a module that driver.py imports does an import itself (e.g. m/foo.py tries to import m/bar.py). It appears that sys.path in m/foo.py is identical to sys.path in driver.py so I do not understand how Python 2.7 successfully does import bar when the m/ directory is not in sys.path.

  2. 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.

delcypher
  • 751
  • 7
  • 7
  • 2
    possible duplicate of [Changes in import statement python3](http://stackoverflow.com/questions/12172791/changes-in-import-statement-python3) – jonrsharpe Feb 26 '14 at 09:11
  • @jonrsharpe : The question you link to basically answers my second question **but** not the first. – delcypher Mar 05 '14 at 10:34
  • To answer the first question, the default CPython implementation will also look for files inside the current working directory to import files. Which is why the files m/foo.py and m/bar.py could have relative imports. – CasualDemon Mar 05 '14 at 11:38

0 Answers0