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 - Run tests with pytest, which handles imports correctly: ... # mypackage/cli.py from . import core # Works when run as: python -m mypackage.cli def main(): core.run() if __name__ == "__main__": main() ... Notebooks often have import issues. Use absolute imports and ensure the package is installed.
Discussions

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
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
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
Relative import issue when testing with pytest
Hi folks, I'm running into some issues with Chalice + CDK. I'm finding that if I set up my imports to enable pytest to find everything, I can't deploy - but getting the code into a depl... More on github.com
🌐 github.com
1
April 11, 2021
🌐
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.
🌐
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
... You are running the test script from inside its directory - python has no way of knowing this is part of a package. Try to cd to projectroot and from there: $ python -m pytest -m tests.test_util # note no py
🌐
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 β€Ί 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
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
🌐
Gideonbrimleaf
gideonbrimleaf.github.io β€Ί 2021 β€Ί 01 β€Ί 26 β€Ί relative-imports-python.html
Relative Imports in Python - Without Tearing Your Hair Out | Aiming to Misbehave
January 26, 2021 - As mentioned - Python 3.3 onwards can happily create namespaces for packages without an __init__.py file so we might think we’re all good to go. Let’s try and run our tests - for now let’s say we’re executing this whilst in the project directory (that’s going to matter real quick): python tests/drink_test.py ImportError: attempted relative import with no known parent package
🌐
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 ...
Author: aws
🌐
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

🌐
Iq-inc
iq-inc.com β€Ί importerror-attempted-relative-import
ImportError: attempted relative import with no known parent package – IQ Inc
February 25, 2021 - Packages can be imported the same way as modules. Intrapackage relative imports can get a bit tricky.
🌐
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
🌐
Finxter
blog.finxter.com β€Ί home β€Ί learn python blog β€Ί [error fixed] β€œattempted relative import in non-package” even with __init__.py
[ERROR FIXED] "Attempted relative import in non-package" even with __init__.py - Be on the Right Side of Change
February 10, 2022 - Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\Errors\Tests\app.py", line 1, in <module> from ..components import mod ImportError: attempted relative import with no known parent package
🌐
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 ... without a recognized parent package. It can be fixed by using absolute imports, converting the module to a package or installing it with a setup.py....
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί unit test issues with relative imports
r/learnpython on Reddit: Unit test issues with relative imports
June 4, 2021 - ====================================================================== ERROR: test_url_utilities (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: test_url_utilities Traceback (most recent call last): File "C:\Python37\lib\unittest\loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "C:\Users\Simon\Desktop\@Documents\@@Projects\Coding\@python\SubjectGrapher\@Project\src\tests\test_url_utilities.py", line 3, in <module> from ..utilities.url_utilities import * ImportError: attempted relative import with no known parent package Share
🌐
Itsourcecode
itsourcecode.com β€Ί home β€Ί attempted relative import with no known parent package
Attempted Relative Import With No Known Parent Package
July 11, 2026 - The ImportError: Attempted Relative Import With No Known Parent Package error occurs in Python when a relative import is attempted from a module that is not part of a package.
🌐
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.