0

I have a project with the following folder structure and file contents:

├── code
│   ├── my_lib
│   │   ├── __init__.py
│   │   ├── moduleA.py
│   │   └── moduleB.py
│   ├── scriptA.py
│   └── scriptB.py

__init__.py

#empty 

moduleA.py

def funA():
    print("A")

moduleB.py

import moduleA

moduleA.funA()

def funB():
    print("B")

scriptA.py

from my_lib import moduleA

moduleA.funA()

scriptB.py

from my_lib import moduleB

moduleB.funB()

In Python 2.7, I can successfully run all four Python files. But with Python 3.5, I can't run scriptB.py, since it gives me following error:

Traceback (most recent call last):
  File "scriptB.py", line 1, in <module>
    from my_lib import moduleB
  File "/home/marjan/Desktop/code/my_lib/moduleB.py", line 1, in <module>
    import moduleA
ImportError: No module named 'moduleA'

If I run moduleB.py (the one that is apparently causing the problems) on its own with Python 3, it runs without problems.

What principle is behind the different behaviour of chained imports in Python 2 vs Python 3, and how can I overcome the differences with minimal changes in the code or project structure?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Marjan Moderc
  • 2,747
  • 23
  • 44

2 Answers2

2

You use

from __future__ import absolute_import

and then you just use the Python 3 way in both: your moduleB can use either

from mylib import moduleA

or

from . import moduleA  # Relative to directory of this module

but imports are never implicitly relative anymore.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

You need to use from . import moduleA in moduleB.py with python3 for relative imports. Otherwise it is considered an absolute import.

a_guest
  • 34,165
  • 12
  • 64
  • 118