4

I'm working on a Python application consisting of a core and multiple independent modules using the core. I'm having difficulty setting up relative imports of packages.

app
  |- __init__.py
  |- core
        |- __init__.py
        |- corefile.py

  |- module1
        |- __init__.py
        |- main.py

The __init__.py files are empty. I'm running Python 2.7.1.

main.py
from .core import *

Running python main.py results in ValueError: Attempted relative import in non-package.

Similar questions: Ultimate answer to relative python imports, How to do relative imports in Python?, Relative imports in Python

Thanks for the help.

Community
  • 1
  • 1
mgold
  • 6,189
  • 4
  • 39
  • 41

2 Answers2

2

In short, you can only use relative imports from packages that are, themselves, imported.

For example, if you had:

$ cat run.py
from app.module1 import main
main.main()
$ python run.py

Then you could use a relative import in app/module1/main.py (although it would need to be from ..core import foo, because core/ is one level above main.py).

David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • That's made some headway, but now I'm getting `ValueError: Attempted relative import beyond toplevel package`. Printing `__name__` yields `module.main` and not `app.module.main`. Why doesn't it see the directory above it as part of the package? – mgold Apr 07 '12 at 23:42
  • How exactly are you importing it? And are you importing it as `module.main` from something inside `app`? – David Wolever Apr 08 '12 at 02:24
  • I've managed to come up with a slightly tacky solution that involved trying different paths. I also call `module.main` from the top level, as you recommend, so I'll go ahead and close this. – mgold Apr 09 '12 at 00:47
0
import sys
abs_filepath = '/home/n/Documents/IMPORTANT/deep_learning/drori_2018/    final_proj/Ryans_branch/StackGAN/'
# insert your absolute filepath above as abs_filepath = '/path/to/targ/dir'
sys.path.append(abs_filepath)

Please correct it if there are problems with doing the import this way

Other Answers:

Also please see here for a thorough answer about what's going on.

Nathan majicvr.com
  • 950
  • 2
  • 11
  • 31