How to import a Python module from a sibling folder?

PythonImportModuleRelative Path

Python Problem Overview


I have gone through many Python relative import questions but I can't understand the issue/get it to work.

My directory structure is:

Driver.py

A/
      Account.py
      __init__.py

B/
      Test.py
      __init__.py

Driver.py

from B import Test

Account.py

class Account:
def __init__(self):
    self.money = 0

Test.py

from ..A import Account

When I try to run:

python Driver.py

I get the error

Traceback (most recent call last):

from B import Test

File "B/Test.py", line 1, in <module> from ..A import Account

ValueError: Attempted relative import beyond toplevel package

Python Solutions


Solution 1 - Python

This is happening because A and B are independent, unrelated, packages as far as Python is concerned.

Create a __init__.py in the same directory as Driver.py and everything should work as expected.

Solution 2 - Python

In my case adding __init__.py was not enough. You also have to append the path of the parent directory if you get module not found error.

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \_ __init__.py
 |      \__B.py
 |

To import B.py from A.py, you have to do the following

import sys
  
# append the path of the parent directory
sys.path.append("..")

from SiblingB import B
print("B is successfully imported!")

Solution 3 - Python

The reason for

ValueError: Attempted relative import beyond toplevel package

is that A is the same directory level as Driver.py. Hence, ..A in from ..A import Account is beyond top-level package.

You can solve this by create a new folder named AandB together with __init__py in this new folder, and then move A and B folders into AandB folder. The directory structure is as following:

The directory structure

Correspondingly, the content in Driver.py should be modified as from AandB.B import Test.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshuaView Question on Stackoverflow
Solution 1 - PythonDavid WoleverView Answer on Stackoverflow
Solution 2 - PythonShekharView Answer on Stackoverflow
Solution 3 - PythonFEMistaView Answer on Stackoverflow