0

I'm having trouble understanding how nested imports work in a python project. For example:

test.py
package/
    __init__.py
    package.py
    subpackage/
        __init__.py

test.py:

import package

package/__init__.py:

from .package import functionA

package/package.py:

import subpackage

def functionA():
    pass

In Python 3.5 when I run test.py I get the following error, but no error in Python 2.7:

C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py
Traceback (most recent call last):
  File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in <module>
    import package
  File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in <module>
    from .package import functionA
  File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1, in <module>
    import subpackage
ImportError: No module named 'subpackage'

However if I run package.py with Python 3.5. I get no error at all.

This seems strange to me as when package.py is run on its own the line import subpackage works, but with it is being 'run' (don't know if this is the right terminology here) through the nested import, the same line cannot find subpackage.

Why are there differences between Python 2.7 and 3.5 in this case and how can this be resolved in a way that works for both 2.7.x and 3.x?

I think this might be due to the fact that import subpackage in the nested import counts as an implicit relative import in the nested import but not when package.py is run directly, but if I do import .subpackage instead, I get this error on both 2.7 and 3.5:

C:\Users\Patrick\Anaconda3\python.exe C:/Users/Patrick/Desktop/importtest/test.py
Traceback (most recent call last):
  File "C:/Users/Patrick/Desktop/importtest/test.py", line 1, in <module>
    import package
  File "C:\Users\Patrick\Desktop\importtest\package\__init__.py", line 1, in <module>
    from .package import functionA
  File "C:\Users\Patrick\Desktop\importtest\package\package.py", line 1
    import .subpackage
           ^
SyntaxError: invalid syntax
pbreach
  • 16,049
  • 27
  • 82
  • 120
  • You shouldn't be trying to run `package.py` on its own. – martineau Jul 28 '16 at 00:28
  • Thanks. The point was just trying to understand why `subpackage` could be imported one way and not the other. Of course there is no reason to run `package.py`. – pbreach Jul 28 '16 at 00:39
  • 1
    In that case see [_Relative imports for the billionth time_](http://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – martineau Jul 28 '16 at 00:43
  • 1
    @martineau I've actually read that post a couple of months back but for some reason it makes more sense now. Funny how that works – pbreach Jul 28 '16 at 01:23

1 Answers1

2

You should use:

from . import subpackage

in package/package.py.

donkopotamus
  • 22,114
  • 2
  • 48
  • 60