How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python)
Here’s everything about ImportError: attempted relative import with not known parent package in Python.
- The meaning of the error ImportError: attempted relative import with not known parent package
- How to solve the error ImportError: attempted relative import with not known parent package
- Lots more
So if you want to understand this error in Python and how to solve it, then you’re in the right place.
Let’s get started!
How to Solve ImportError: Attempted Relative Import With No Known Parent Package (ModuleNotFoundError: No module named ‘name’)
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:
- Run a script with the -m switch.
- Use global import inside the package files that you plan to run as scripts.
To get rid of the former version of this error ModuleNotFoundError: No module named ‘name’, the path to the package folder must be in the PATH system variable. You can do this in different ways, for example:
- Move the package folder to a directory that is already in PATH.
- Add the folder where the package is located to PATH on your own through the console or system settings.
- Install the package to the system using the setuptools module.
- Add the address of the package folder to PATH using the sys and pathlib modules in those package files that you plan to run as a separate script.
Let’s dive right in:
Understand the Error ImportError: Attempted Relative Import With No Known Parent Package
One of the key advantages of the Python language is its infrastructure. You can find a ready-made module for almost any of your tasks.
The meme from xkcd below is a good illustration of this statement:

In this comic, one man says that flying is a straightforward task; you just need to type import antigravity. WARNING! Don’t try to import antigravity at home without securing fragile items.
It’s effortless to create your modules and packages for Python. However, this also has a downside. As packages evolved, some of the internal names in packages began to duplicate global ones.
For example, there is a package called graphics, but this is a fairly common word and it is inevitably used in other packages related to graphics.
Let’s say you created a supergraphics package with the following structure:
How can you determine when to call import graphics inside the unittests.py file, whether you mean a package from PyPI (Python Package Index) (let’s assume that you have installed it) or a local module inside your library?
One way is to always use an absolute import:
But in Python you can use the so-called relative import. Its capability and usage are specified in PEP328.
Relative imports are implemented as follows: You can use one dot . to import a package from the same level where you are. If you import graphics from unittest.py, you would write this:
If you need to import something from another folder, you would put a point to rise to a higher level.
For example, to import graphics from the shrink.py file, you would write this:
You can consider that the invisible word parent precedes each dot:
This makes the principle a little clearer, but writing this, of course, is not very convenient. In the end, you can use global imports.
Thanks to relative imports, you can add new folders to the package structure. This will not always require you to redo all imports.

For example, if you want to move all your current folders and files to a higher-level folder, this will not cause changes in the child files.
Relative imports are allowed only within a package. This is consistent with common sense and safety. Only the folder structure within the package can be guaranteed.
A package is an independent structural unit, and its components should not interact with relative paths with neighbouring packages.
It is very easy to create a Python package; you just need to create an __init__.py file in the root of the folder to import this folder as a package.
Let’s create a little module with the following folder structure and file contents:
You can now use your package from the Python terminal:
Now let’s add testing to the introduce.py file. It will look like this:
Now you can import the hello_to() function from it.
If you run the introduce.py file as a script, it will check on whether the value returned from the hello() function contains the name that you submitted to as an argument.
If you try to run this file as a script, you will get an ImportError: attempted relative import with no known parent package:
Another solution would be to not use relative imports.
Let’s change the introduce.py file as follows:
Now you can run this file as a script without the -m key:
A separate problem may be that Python does not know where the package is located.
Let’s move the package down one level inside the Project folder and try again to run introduce.py:
To get rid of this problem, you need to add the package’s folder path to PATH or place the package in a folder that is already in PATH. For example, <Python directory>/lib/site-packages.
Before adding a module’s address to PATH or copying it to a folder that already exists in PATH, you must ensure that your package name is unique.
Otherwise, one of the packages will not work—either yours or the one already installed with the same name.

For your package to be globally available, Python has a special mechanism.
You can install your package using the utilities from the setuptools module.
Let’s create a setup.py file with the following content in the root folder of the package:
Next, start installing the package with the following command. By the way, you should always use a virtual environment; do not install any packages in the global interpreter.
For Python 3, there is a built-in venv utility. This is very useful if, for example, you have to use different versions of libraries in your different projects:
After launching, you will get a long installation log. If there were no errors, you could use the hi module globally.
If for some reason you do not want to install your module into the system, you can add the current directory to the path.
Make sure you do this before all imports from the module. Add a block that will modify PATH to the introduce.py file:
Now you can use global import in your introduce.py file even if the hi module is not installed in the system via setuptools.
Note that file.parents[1] is being used here because you need to move up one level for the hi package to be available.
In other words, you must go to the folder where the folder with the package is located. In the current case, this is Project:
If the tree structure were deeper, then the parents with higher indices would have to be used.
Почему не работает относительный import в Python (PyCharm).
Добрая ночь!
Проблема такая: нужно из папки tests в файле test_1.py импортировать файл sieves.py, который находит в директории выше. Я указал корневой директорией папку package. В файле test_1.py пишу from .. import sieves, PyCharm не ругается, ошибкой не подчеркивает. Но стоит мне запустить его, я получаю ошибку в лицо: ImportError: attempted relative import with no known parent package.
Скрины:

ImportError : Attempted relative import with no known parent package [duplicate]
I am learning to program with python and I am having issues with importing from a module in a package. I am usingvisual studio code with Python 3.8.2 64 bit.
in the ecommerce/products.py file I have:
So that I can import the Database class from the ecommerce/database.py file. But I get error
8 Answers 8
It seems, from Python docs and experimenting, that relative imports (involving ., .. etc) only work if
Resolving intra-project imports in Python — A simple guide
When importing between Python files in a project (i.e. importing from one project file to another), exceptions such as ModuleNotFoundError or ImportError may occur if one file is outside the directory of another. The following article explains why this occurs and how to resolve these import errors, which involves configuring your editor and/or installing your project as a package.
An Example Broken Project
Consider a very basic Python project. It has two code folders, each with a Python code file in; plus a test folder with one test.
project/folder1/file1.py contains a simple add() function.
project/folder2/file2.py is a Python file that we want to import our add() function into and use. We use an absolute import starting from under our project folder: from folder1 import file1 .
Lastly, tests/test_file.py contains a simple pytest-style test method for our add() function.
This is one of the simplest Python projects there can be, so everything should work perfectly, right? Not so much; as we will see below.
Firstly, let’s try to run our file2.py script:
Oh dear! Our script tripped up on what should be a very simple import by raising the error message ModuleNotFoundError: No module named ‘folder1’, with Python complaining that it cannot find the module in question.
Let’s check how our test runner fares:
The exact same error again. Not good. But, perhaps we can fix it, right? Let’s try to use a relative import in file2.py instead:
With this import, we use .. to go up one folder from where we currently are (i.e. going up from folder2 to project ); before going back down into folder1 and into file1.py .
Let’s try to run the file:
Unfortunately, now we get a completely different error. Python raises the error message ImportError: attempted relative import with no known parent package and refuses to perform the relative import.
So, why do these errors occur? And how can they be fixed?
An IMPORTant PATH
To understand why these errors occur, first we must understand how Python deals with imports.
Python resolves import statements using a list variable called sys.path . This variable contains a list of directories, and Python searches each directory in turn looking for a Python package to import.
As you can see, the only directories listed are those where Python is installed. So how do intra-project imports work? The key is in the very first entry; that empty '' string. This empty string represents the directory that contains the Python file that was run or where a Python REPL shell was invoked. In our above example, if we run project/folder1/file1.py , then project/folder1/ is what the empty string would represent.
The rules of how Python decides what it can import from these directories are complex to describe accurately; a condensed version is as follows: you can import from within any directory in this list (including subdirectories), but you can’t import from outside them.
If we look at the example project structure again:
We tried to run project/folder1/file1.py , which means project/folder1/ is in the Python path. However, project/folder2/file2.py , which we want to import from, is outside of this directory. We have to go up one directory to project — Python will not allow us to do this at the moment.
What we really want is for the project folder to be in sys.path . If the project folder was in sys.path , then we would be able to import from any folder or file within it.
Fear is the PATH to the Dark Side
As sys.path is a list, we can directly modify it to suit our needs if we desire. We can append to it just you can with any other list. Adding the project root is as simple as appending the absolute path of the folder to sys.path .
If we place this line in our file2.py script,
then the imports will resolve correctly when we run the file.
As you can see though, this is a pretty ugly method of setting the import correctly. Firstly, we have to perform the sys.path append before we try to import file1 ; we can’t group all our imports together like we would in any normal file. Perhaps more significantly, this operation will only work for this file as it stands. If we wanted to import file1.py into other files in our project structure, we might have place this line somewhere different or append to sys.path in multiple places. Regardless, it’s an ugly way to resolve the issue.
There Must Be a Better Way
Fixing the issue properly, without resorting to hacking the sys.path , involves two main approaches.
If you run your code through PyCharm or Visual Studio Code run configurations only, then you can set up those editors to add your project root folder to sys.path . In the case of PyCharm, this is done automatically for you; in the case of Visual Studio Code, you must do this manually for each new project.
If, however, you invoke your code manually through the terminal, whether through PyCharm or Visual Studio Code or any other terminal instance; then you can add your project root folder to sys.path by installing your project as a package.
Below are step-by-step guides on how to carry out these approaches. If you use PyCharm or Visual Studio Code, please choose those articles; if you use any other editor or IDE, please choose the “Text Editor and Terminal” article instead.
Afterword
Issues dealing with intra-project imports are extremely common, and encountered by Python programmers of all skill levels. They can be extremely frustrating to deal with. Error information gives little to no direction on how to fix the issue, and online resources like StackOverflow often confuse by providing a multitude of answers, many of which are incorrect and/or incomplete. I hope the above helps in providing a simple guide for resolving intra-project imports.
The information in these resources have been collated from multiple sources; the most important source was pytest’s article on Good Integration Practices. The guides above provide a detailed procedure of the first section in that article.