-1

This is a nodejs and python project so the directory structure is the way it is.

This is my directory structure:

top_level/
    scripts/
        __init__.py
        python_script.py
        some_nodejs_files.js
    tests/
        __init__.py
        test_python_script.py

I can put all my unit test code in the inside the scripts directory but I would like to put test code in the test directory which is at the same level as scripts. How do I import python_scripts.py from test_python_script.py

From tests/test_python_script.py I've tried doing a from ..scripts import python_script but I get a ValueError: attempted relative import beyond top-level package.

EDIT: After reading some of the links in the comments and trying some stuff out I added

import sys
sys.path.append("..")
from scripts import python_script

and that seems to do the trick.

What I learned

Where ever you have the init.py that folder is the name of the module.

  • What does the ValueError say? –  Aug 31 '18 at 04:17
  • @Terminus Updated original post – user3577138 Aug 31 '18 at 04:20
  • Possible duplicate of [beyond top level package error in relative import](https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import) –  Aug 31 '18 at 04:24
  • Ok, [this one](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) is probably more thorough. –  Aug 31 '18 at 04:28

1 Answers1

0

You have a couple of options:

# add scripts to the python path
from os.path import abspath, dirname, join
import sys
sys.path.append(join(dirname(abspath(__file__)), 'scripts'))

Then your import will work.

Or take advantage of the fact that the current directory is already part of the path and just use a symbolic link:

# bash
cd tests
ln -s ../scripts/python_script.py

Then your import will work.

gahooa
  • 131,293
  • 12
  • 98
  • 101