1

Is there any recommended/opinionated way of importing modules within the same projects without hacks like sys.path.append or exporting PYTHONPATH with paths to neighbour directories?

I am trying to add some tests to my app, nothing extraordinary.

app/
  - __init__.py
  - app_to_be_tested.py
tests/
  - test_app_to_be_tested.py

How am I supposed to do that in most 'pythonic' way - either one the hacks above, build a package for my own code that will never be imported by any other app or restructure directory topology?

Any advice appreciated.

edit

app.py

def some_func():
   return 'abcd'

test_app.py

from ..app import app

def test_some_func():
    assert app.some_func() == 'abcd'

ImportError: attempted relative import with no known parent package

edit 2

had a change to get back to it

.
├── app
│   ├── __init__.py
│   ├── app.py
│   └── inner
│       └── __init__.py
└── tests
    └── test_app.py

content of app/inner/__init__.py

def func_from_inner():
    return 'from inner'

app/app.py

from inner import func_from_inner

def some_func():
    return func_from_inner()

running the code from root dir results in ModuleNotFound (how come?)

 python3 -m app.app
 ...
 File "/redacted/app/app.py", line 11, in <module>
 from inner import func_from_inner ModuleNotFoundError: No module named 'inner'

running it the same way from the app directory works

when I change the import in app/app.py to

from .inner import func_from_inner

it works from the root dir

sys.path does contain the root project dir, doesn't it mean it should import everything recursively?

in addition to that, running python3 app/app.py results in

Traceback (most recent call last):
  File "/redacted/app/app.py", line 11, in <module>
    from .inner import func_from_inner
ImportError: attempted relative import with no known parent package
Łukasz
  • 1,980
  • 6
  • 32
  • 52

1 Answers1

0

You asked for opinionated - here is something that works for me based on working with someone experienced in python - based on this question/answers - When would the -e, --editable option be useful with pip install?

set up a virtual env and install your app there:

test -d .venv || python -m venv .venv # make sure all venv pkgs are available
. .venv/bin/activate # or as appropriate for your os
pip install -e .
python tests/test_app.py

then in your test just import as normal:

from app import app

def test_some_func():
    print('running test: test_some_func')
    assert app.some_func() == 'abcd'

if __name__ == '__main__':
    test_some_func()

complete demo here - https://github.com/alexanderankin/demo-so76882111

Dave Ankin
  • 1,060
  • 2
  • 9
  • 20