1

I have the following structure:

/a
 /b
  module1.py
/c
  module2.py

So, from some root folder there are 2 modules:

a/b/module1.py and

c/module2.py

I want to do import of some function of module1 from module2.

All 3 folders have ____init___.py

Both py files have inside:

if __name__ == '__main__':
    func()

module2.py has the following import code:

from .. a.b.module1 import func1

If I just run module2.py from a terminal (staying in the root folder):

python -m c.module2.py 

I have the following error:

ValueError: attempted relative import beyond top-level package

How to solve this problem?

mimic
  • 4,897
  • 7
  • 54
  • 93

1 Answers1

2

This is a common problem with the python import system, but one way to make it more manageable may be to define some imports in another __init__.py in your projects root directory, which will create a separate namespace for your package and all subdirectories.

The way I setup the directories to reproduce your error is this structure:

Root directory: /package:

/package
/package/__init__.py
/package/a
/package/a/__init__.py
/package/a/b
/package/a/b/__init__.py
/package/a/b/module1.py
/package/c
/package/c/__init__.py
/package/c/module2.py

In package/__init__.py put the top-level module imports:

from a.b import module1

and then the only change I made is to module2.py to contain only this function for testing:

from package import a # import top-level module from root package 

def func():
    a.b.module1.some_object() # call function of module1 from module2 (this module).

if __name__ == '__main__':
    func()

then in the top-level root of the package, from terminal you should be able to run module2.py:

$ python package/c/module2.py 

should print out:

from a.b.module1: some object

Improvement and refinements can be made to get the exact behavior you desire.

For reference, I used this answer's suggestions: How to avoid circular imports in Python?

  • 3
    Why is it sooooo complicated? Python pretends to be a simple language, but turns out to be a nightmare as soon as you do one small step aside :( – mimic Nov 13 '18 at 18:08