I found I must add __init__.py in test and projroot. __init__.py in src is not necessary. And pytest could run correctly in 3 folders:

# parent folder of project root
C:\>pytest projroot

# project root
C:\>cd projroot
C:\projroot>pytest

# test folder
C:\projroot>cd test
C:\projroot\test>pytest
Answer from Jacques Yang on Stack Overflow
Top answer
1 of 3
30

I found I must add __init__.py in test and projroot. __init__.py in src is not necessary. And pytest could run correctly in 3 folders:

# parent folder of project root
C:\>pytest projroot

# project root
C:\>cd projroot
C:\projroot>pytest

# test folder
C:\projroot>cd test
C:\projroot\test>pytest
2 of 3
14

Adding __init__.py to project root actually messed up my pytest discovery and also pylint (causing Unable to import 'angles' pylint(import-error)). I had to remove it from project root and only add it inside my tests folder, which solved both my pytest discovery and pylint warning.

With __init__.py in project root, i'll have ModuleNotFoundError: No module named 'angles'

Below is my folder structure with both pytest discovery and pylint (without warning) working :

powerfulpython
├── angles.py
└── tests
    ├── __init__.py
    └── test_angles.py

In angles.py I have a Class Angle which I try to absolute import using from angles import Angle inside test_angles.py.

Before I found out that the issue was having an unnecessary __init__.py in project root. I also tried

  1. editing python.testing.cwd
  2. setting '--rootdir' of pytest
  3. Downgrading Python extension to 2020.9.114305 (following https://github.com/microsoft/vscode-python/issues/14579)

None of them worked.

Before i deleted the __init__.py in project root, when testing pytest, doing python -m pytest worked because the project root is prepended to sys.path automatically so the absolute import was working correctly from root and the import statement can find angles under root. Doing pytest (without python -m) fails because the project root is not prepended to sys.path. The latter can be temporarily solved by adding the root directory manually to $PYTHONPATH. However this is an unsustainable solution as I don't want to add every single new project i want to test as a PYTHONPATH edit to my ~/.zshrc.

Another hack I tried which fixed both pytest and test discovery was inserting sys.path.insert(0,'/Users/hanqi/Documents/Python/powerfulpython') in the code but this is way too ugly. I didn't want to add lines to code just for testing then have to delete them later.

After all these, I deleted __init__.py in root and all's good. No need for any of the above list of 3 items.

Many solutions I went through deal with finding the tests folder, but that was not my problem. My tests were found correctly in their folders, just that the from angles import Angle was breaking which causes test discovery to fail.

Investigating how does __init__.py in project root break things:

I printed sys.path and realized with it, ~/Documents/Python got prepended to sys.path and without it, ~/Documents/Python/powerfulpython got prepended. The latter path is exactly my project root.
I'm guessing this has something to do with https://docs.pytest.org/en/6.2.x/pythonpath.html (--import-mode=prepend (default)). I was expecting to see the __init__.py inside tests to cause ~/Documents/Python/powerfulpython to be prepended and the __init__.py in project root cause ~/Documents/Python to be prepended, but strangely i only saw the latter when I left both __init__.py inside.

I also tried deleting the __init__.py inside tests (but let __init__.py in root stay), and see ~Documents/Python/powerfulpython/tests prepended to sys.path. This same line is also prepended if I delete both __init__.py in root and tests, not sure why.

Edit: The above behaviour is explained at https://docs.pytest.org/en/6.2.x/pythonpath.html

It will then search upwards until it can find the last folder which still contains an __init__.py file in order to find the package root

After further repeating my above experiments running using python -m pytest -s (-s so successful test runs don't swallow my print(sys.path)) instead of just pytest, I confirm that there are 2 actors prepending to sys.path.

  1. python -m (what it prepends depends on from which directory the command is run)
  2. pytest (what it prepends depends on where are __init__.py inserted (explained in pytest docs linked above)

Both have the effect of editing sys.path, helping to make failing imports possible

Jacques Yang above needed 2 __init__.py to put the containing folder of his projroot into sys.path so projroot.test appears as the value of __package__ in his test_a.py and __name__ would appear as projroot.test.test_a, and the 2 dots in this module name (__name__) allow the two dot relative import of from ..src import a. He could also have used an absolute import of from projroot.src import a.

If he didn't add the __init__.py in projroot, the __package__ would become just test and __name__ would be test.test_a, which would only allow an upwards relative step of at most 1 step. (This stepping concept is also explained by BrenBarn at Relative imports for the billionth time).

When there is __init__.py in test but not projroot, that would have been ValueError: attempted relative import beyond top-level package, because __package__ is test and __name__ is test.test_a allowing only 1 step back up but 2 steps back was coded. The question in the title occurs when there isn't even __init__.py in test, so __package__ is completely blank and __name__ is only the test_a file itself)

I was thinking why did OP need 2 __init__.py while I only needed 1, and 2 actually harms my attempt. Then I realized OP was doing relative import and I was doing absolute import with from angles import Angle. If i followed OP's pattern and did relative import from ..angles import Angle, then I also would have needed to add __init__.py under powerfulpython, otherwise i'll get the same errors.

So why does doing absolute import break with the extra __init__.py in ~/Documents/Python/powerfulpython? Because the __init__.py causes pytest to step up even higher in the hierarchy and prepend ~/Documents/Python to sys.path, but my absolute import needed to have ~/Documents/Python/powerfulpython (this can be resolved with running using python -m pytest as explained in the 2 actors of prepending section above, but feels somewhat unnatural compared to simply pytest)

I have a 30-min demo video on import concepts at https://towardsdatascience.com/taming-the-python-import-system-fbee2bf0a1e4 that could help people understand __package__ and __name__.

🌐
OneUptime
oneuptime.com › home › blog › how to fix 'importerror: attempted relative import' in python
How to Fix 'ImportError: attempted relative import' in Python
January 25, 2026 - The "ImportError: attempted relative import with no known parent package" error confuses many Python developers. It occurs when you try to use relative imports in a script that Python does not recognize as part of a package.
Discussions

python - Issue with pytest: ImportError - attempted relative import with no known parent package - Stack Overflow
I'm working with pytest in a FastAPI project and trying to run unit tests. Project Structure: 📁 app └── 📁 fastapi_app ├── __init__.py ├── celery_worker.py ├── Dockerfile ├── main.... More on stackoverflow.com
🌐 stackoverflow.com
Tsts fail: ImportError: attempted relative import with no known parent package
The PyTest log looks like this: _______________________________________________________________________ ERROR collecting tests/test_pyfftw_complex.py _______________________________________________... More on github.com
🌐 github.com
0
November 8, 2024
python - Attempted relative import with no known parent package when doing automated testing - Stack Overflow
My simplified folder structure is: projectroot/ __init__.py src/ __init__.py util.py tests/ __init__.py test_util.py In util.py I have the following function: def build_format_strin... More on stackoverflow.com
🌐 stackoverflow.com
Can't use relative imports from conftest.py in test package with --import-mode=importlib
With tests outside application code in a tests package containing conftest.py, pytest --import-mode=importlib doesn't import conftest as part of the package. Example Files: test/__init__.py tes... More on github.com
🌐 github.com
1
August 15, 2020
🌐
Reddit
reddit.com › r/learnpython › importerror: attempted relative import with no known parent package - despite following tutorials
r/learnpython on Reddit: ImportError: attempted relative import with no known parent package - despite following tutorials
November 21, 2021 -

My project structure:

├── config
│   ├── __init__.py
│   └── config.yaml
├── log
│   ├── .main.log
│   └── gatelog.sqlite
├── mods
│   ├── __init__.py
│   ├── complex.py
│   ├── config.py
│   └── simple.py
├── test
│   ├── __init__.py
│   └── test_cmd.py
├── other.py
└── main.py

All __init__.py files are currently blank. The one I'm having trouble with is test_cmd.py which is for running unittests (that I'm trying to learn):

# test_cmd.py

import unittest
from .. mods import simple,complex

class TestComplex(unittest.TestCase):
    def test_complex(self):
        
        self.assertEqual(complex.complexMethod(6,7),2)

    def test_simple(self):
        self.assertEqual(simple.simpleSum(),4)

def main():
    pass

if __name__ == '__main__':
    unittest.main()

In VSCode I get no error writing line 4 (the from .. mods etc.) but on running it I get

File "./testbed/test/test_cmd.py", line 4, in <module>

from .. mods import simple,complex

ImportError: attempted relative import with no known parent package

Do I have to start adding syspath directives in or is there a way to do it without? I've tried omitting the space after the .. but that makes no difference

🌐
PyDevTools
pydevtools.com › home › python developer tooling handbook › how to › how to fix "importerror: attempted relative import with no known parent package"
How to Fix "ImportError: attempted relative import with no known parent package"
September 7, 2026 - ImportError: attempted relative import with no known parent package means Python ran a file that uses a relative import, but that file had no parent package to resolve the import against.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-importerror-attempted-relative-import-with-no-known-parent-package
How to Fix: ImportError: attempted relative import with no known parent package - GeeksforGeeks
July 23, 2025 - The "ImportError: attempted relative import with no known parent package" error typically arises in Python projects with multiple modules or packages. Python uses the concept of packages and modules to organize code into manageable units.
🌐
Stack Overflow
stackoverflow.com › questions › 79458652 › issue-with-pytest-importerror-attempted-relative-import-with-no-known-parent
python - Issue with pytest: ImportError - attempted relative import with no known parent package - Stack Overflow
Traceback: ..\..\..\..\..\AppData\Local\Programs\Python\Python313\Lib\importlib\__init__.py:88: in import_module return _bootstrap._gcd_import(name[level:], package, level) fastapi_app\tests\test_process.py:3: in <module> from ..main import app E ImportError: attempted relative import with no known parent package =============================================== short test summary info =============================================== ERROR fastapi_app/tests/test_process.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
🌐
GitHub
github.com › pyFFTW › pyFFTW › issues › 405
Tsts fail: ImportError: attempted relative import with no known parent package · Issue #405 · pyFFTW/pyFFTW
November 8, 2024 - Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) test_pyfftw_dask_interface.py:49: in <module> from .test_pyfftw_base import run_test_suites E ImportError: attempted relative import with no known parent package
Author: pyFFTW
Find elsewhere
🌐
YouTube
youtube.com › vlogommentary
How to Resolve ImportError: attempted relative import with no known parent package in Pytest - YouTube
Discover how to effectively resolve the `ImportError: attempted relative import with no known parent package` error encountered in Pytest while working with ...
Published: January 13, 2025
Views: 31
🌐
Built In
builtin.com › articles › importerror-attempted-relative-import-no-known-parent-package
Python ImportError: Attempted Relative Import With No Known Parent Package Solved | Built In
July 22, 2025 - Summary: The “ImportError: attempted relative import with no known parent package” occurs in Python 3 when using a relative import without a recognized parent package. It can be fixed by using absolute imports, converting the module to a ...
🌐
GitHub
github.com › pytest-dev › pytest › discussions › 13470
Creating a pyproject.toml makes pytest fail with "E ImportError: attempted relative import with no known parent package" · pytest-dev/pytest · Discussion #13470
$ touch src/program/pyproject.toml $ python -m pytest --import-mode=importlib src/program ImportError while loading conftest '/Users/me/Documents/git/pytest/src/program/tests/conftest.py'. src/program/tests/conftest.py:1: in <module> from ..code import foo E ImportError: attempted relative import beyond top-level package
🌐
Stack Overflow
stackoverflow.com › questions › 70536469 › attempted-relative-import-with-no-known-parent-package-when-doing-automated-test
python - Attempted relative import with no known parent package when doing automated testing - Stack Overflow
When running the automated test from command line as python -m pytest test_util.py or py.test test_util.py, I get the attempted relative import beyond top-level package error message, while when running the test_util.py in debug mode in my code editor, I get a similar attempted relative import with no known parent package error.
🌐
GitHub
github.com › pytest-dev › pytest › issues › 7652
Can't use relative imports from conftest.py in test package with --import-mode=importlib · Issue #7652 · pytest-dev/pytest
August 15, 2020 - [100%] ================================== 1 passed in 0.01s ================================== $ pytest --import-mode=importlib ImportError while loading conftest 'mwe/test/conftest.py'. test/conftest.py:3: in <module> from .util import helper_function E ImportError: attempted relative import with no known parent package ·
Author: pytest-dev
🌐
GitHub
github.com › aws › chalice › issues › 1699
Relative import issue when testing with pytest · Issue #1699 · aws/chalice
April 11, 2021 - then pytest is happy but I can't cdk deploy, because · ImportError: attempted relative import with no known parent package · So: have I set up my project incorrectly? Should my tests be somewhere else? Thanks in advance for any help anyone can give me · Reactions are currently unavailable ·
Author: aws
🌐
Gentoo Forums
forums.gentoo.org › board index › assistance › portage & programming
[SOLVED] can't make pytest work... - Gentoo Forums
October 26, 2022 - teste> python tests/test_example.py ... relative import with no known parent package teste> That happens because, when running "test_example.py" as a script, __name__ is set to __main__, therefore the folder structure expressed within the import "from ..source.trial.example ...
🌐
GitHub
github.com › oneuptime › blog › tree › master › posts › 2026-01-25-fix-importerror-relative-import-python
blog/posts/2026-01-25-fix-importerror-relative-import-python at master · OneUptime/blog
The "ImportError: attempted relative import with no known parent package" error confuses many Python developers. It occurs when you try to use relative imports in a script that Python does not recognize as part of a package.
Author: OneUptime
🌐
Tech With Tech
techwithtech.com › home › how to solve importerror: attempted relative import with no known parent package (python)
How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python) - Tech With Tech
January 13, 2024 - For example, you get the error when running a file inside a package as a script. To get rid of the error ImportError: attempted relative import with no known parent package you have two ways to test package functions:
🌐
Python Pool
pythonpool.com › home › error › fix importerror: attempted relative import with no known parent package
Fix ImportError: Attempted Relative Import With No Known Parent Package
July 13, 2026 - Fix attempted relative import errors by running modules with -m, using a real package layout, checking __package__, and avoiding fragile script execution paths.
🌐
Gentoo Forums
forums.gentoo.org › viewtopic-p-8755529.html
Gentoo Forums :: View topic - [SOLVED] can't make pytest work...
October 26, 2022 - FAQ | Search | Memberlist | Usergroups | Statistics | Profile | Log in to check your private messages | Log in | Register · Links: forums.gentoo.org | www.gentoo.org | bugs.gentoo.org | wiki.gentoo.org | forum-mods@gentoo.org
🌐
Python.org
discuss.python.org › python help
Relative Imports - Python Help - Discussions on Python.org
Hello, I am currently on the topic of Relative Imports. My package is set up as shown in the following figure: I have Windows 11 Home, and Python v3.12. I am attempting to import file_2.py and sub_file.py into file…
Published: January 14, 2024