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.