1

Suppose I have a package structure like (as shown at pytest.org):

src/
    mypkg/
        __init__.py
        app.py
        view.py
tests/
    test_app.py
    test_view.py
    ...

Now suppose test_view defines a important_attr that I would like to import from within test_app. How can I accomplish this? It seems like absolute imports don't work because test_app and test_view are not technically part of any package (so the absolute import can't be resolved) and relative imports are not allowed for the same reason (since relative imports don't seem to be allowed outside of packages when files are run as scripts?)

e.g.:

# test_view.py

important_attr = 42
# test_app.py

from .test_view import important_attr


def main():
    print(important_attr)

if __name__ == "__main__":
    main()

When I run test_app.py I get ImportError: attempted relative import with no known parent package

I could solve this by moving tests under mypkg directory, but I've seen the "separate tests dir from src dir" suggestion a number of times and I'm trying to understand how/if it can work for this use case. Maybe this is just a known downside of this strategy compared to having tests under mypkg?

adding __init__.py into tests directory didn't seem to fix the error.

2 Answers 2

0

I was able to get this to work by changing the import to from test_view import important_attr.

0

I guess you need to tweak the value of the Python path, either by setting the PYTHONPATH environment variable before calling the Python interpreter, or by changing the sys.path array before trying to import the modules.

Something like this (I changed your example a bit):

./src/pkg/mod.py:

def go():
    print("Went")

./tests/t.py:


import os
import sys

# __file__ is the current file; take the parent directory of that, then append "src"
module_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "src")
sys.path.append(module_path)

from pkg.mod import go

go()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.