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