У меня вот такая структура проекта
---package1/code.py
---package2/ext.py
Как мне импортировать переменную из ext.py в code.py ?
from ext import var
— не срабатывает, говорит что не существует модуля ext
from ..package2.ext import var
— тоже не срабатывает выдаётся ошибка: ImportError: attempted relative import with no known parent package
insolor
46k16 золотых знаков54 серебряных знака95 бронзовых знаков
задан 1 мар 2020 в 7:37
Greed WizardGreed Wizard
1981 золотой знак2 серебряных знака9 бронзовых знаков
1
Всё работает.
-
В файлах указывать
import
иfrom
без ведущих точек:from package2.ext import var
а не
from ..package2.ext import var
-
Вызывать нужно из папки ваш_проект вот такую команду:
python -m package1.code
Можно путь к python указать полностью, типа usr/bin/python
.
Важно указать -m
и точку .
между package1
и code
, а не /
, и после code
не писать .py
.
Вот так:
путь_к_вашему_проекту> python -m package1.code
insolor
46k16 золотых знаков54 серебряных знака95 бронзовых знаков
ответ дан 27 мая 2022 в 12:38
Python просматривает список каталогов определенный в sys.path
.
Ошибка: ImportError: attempted relative import with no known parent package
говорит о том что модуль не был найден в sys.path
(вывод ее на печать поможет прояснить ситуацию).
При такой структуре желательно использовать main.py
для запуска и импорта дочерних модулей:
project_folder/
main.py
package1/
__init__.py
code.py
package2/
__init__.py
ext.py
Если вам нужно запустить code.py
и при этом импортировать данные из ext.py
, то нужно:
- запустить
code.py
как модульpython -m package1.code
- или добавить
sys.path.append(os.getcwd())
в самое началоcode.py
ответ дан 10 апр 2021 в 14:43
StepanStepan
1192 бронзовых знака
1
- в пакетах package1 и package2 должен быть пустой файл
__init__.py
(если его нет) - такая структура будет:
ваш_проект/
package1/
__init__.py
code.py
package2/
__init__.py
ext.py
- я тестировал на таких файлах:
code.py
var = "code.py"
ext.py
from package1.code import var
print(var) # выводит code.py
P.S. Надеюсь чем-то помогло
ответ дан 1 мар 2020 в 9:21
2
One error you might encounter when working with a Python project is:
ImportError: attempted relative import with no known parent package
This error usually occurs when you try to import a module in Python using the relative import path (using a leading dot .
or ..
)
This tutorial shows an example that causes this error and how to fix it in practice.
How to reproduce this error
First, suppose you have a Python project with the following file structure:
.
└── project/
├── helper.py
└── main.py
The helper.py
script contains a function as follows:
def greet():
print("Hello World!")
Next, you tried to import helper.py
into main.py
as follows:
from .helper import greet
print("Starting..")
greet()
The output will be:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from .helper import greet
ImportError: attempted relative import with no known parent package
This error occurs because we used a relative import, which doesn’t work when you’re importing a module in the same directory as the main script you executed using Python.
Python doesn’t consider the current working directory to be a package, so you can’t do a relative import unless you run your main.py
script from the parent directory.
How to fix this error
To resolve this error, you need to change the relative import to an absolute import by removing the leading dot:
from helper import greet
print("Starting..")
greet()
The output will be:
Python is able to find the helper
module, so we didn’t get any errors this time.
If you still want to use the relative import path, then you need to run the main script as a module from its parent directory.
Since the main.py
file is located inside the project
directory, you can run the script with this command:
python -m project.main
# or
python3 -m project.main
This time, the relative import works because Python considers the project
directory to be a package. It keeps track of what’s inside the directory.
If you run the script directly without specifying the parent directory as follows:
Then the relative import error will occur again.
The same solution also works when you try to do sibling imports. Suppose you have the following file structure in your project:
.
└── project/
├── lib
│ └── helper.py
└── src
└── main.py
And you try to import the helper.py
script into the main.py
script as follows:
from ..lib.helper import greet
print("Starting...")
greet()
To make the relative import successful, you need to run the main
script from the project
directory like this:
python -m project.src.main
# or
python3 -m project.src.main
If you run the main.py
script directly, you’ll get the same error:
$ python3 main.py
Traceback (most recent call last):
File "/main.py", line 1, in <module>
from ..lib.helper import greet
ImportError: attempted relative import with no known parent package
The internal workings of Python doesn’t allow you to do relative import unless you specify the top-level directory where all your modules are located.
By adding the root directory of the project when running the main script, you can solve the relative import error.
I hope this tutorial is helpful. Happy coding! 👍
Table of Contents
Hide
- How does module import work in Python?
- Absolute vs. Relative imports
- How to fix ImportError: attempted relative import with no known parent package?
- Option 1 – Use absolute imports
- Option 2 – Get rid of from keyword
- Option 3 – Import inside package init file
Module imports sometimes can cause too much frustration if you are a Python beginner. This tutorial will learn how imports work and the solution for ImportError: attempted relative import with no known parent package.
Before getting into the solution, let’s first understand few basic terminologies in Python.
Python Module: A module is a file in Python containing definitions and statements. A module can contain executable statements as well as function definitions. In simple terms, think as a single .py file with some functionality.
Python Package: A Python package consists of one or more modules, and it contains one file named __init__.py
that tells Python that this directory is a package. The init file may be empty, or it may include code to be executed upon package initialization.
imports: Imports in Python are essential for structuring your code effectively, and by using the import keyword, you can import any module and reuse it effectively. There are two types of import, Relative and Absolute, which will look in-depth.
Let’s consider a simple example.
└── myproject
├── firstpackage
│ ├── a.py
└── secondpackage
├── b.py
├── c.py
└── subpackage
└── d.py
The above project has two packages named firstpackage and secondpackage. Each of these contains some modules, and the secondpackage also has a subpackage that includes its own module. Typically the project structure goes something like this, and it may grow pretty complex.
How does module import work in Python?
Now, let’s say if you import module b in one of your files using the import statement as shown below.
import b
Python will perform the following operations to import the module:
- Locate, load, and initialize (if required) the requested module
- Define necessary names in the local namespace and corresponding scope
Now Python interpreter is going to follow the following steps in an attempt to resolve module b .
Step 1: sys.modules
lookup
Python will try to look at the module first in the sys.modules
, which is a dictionary that has a mapping of key-value pairs of modules. If it finds, then the module is resolved and loaded.
Step 2: Python Standard Library lookup
Python Standard Library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers. Modules are written in Python that provides standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.
If the name is not found in the sys.modules
, it will search in the standard library. If it cannot find over there, then it goes to the next step.
Step 3: sys.path
lookup
Python will look into the sys.path as the last step to resolve the module. This is where things can go wrong, and you will get ModuleNotFoundError: No module named ‘b’
Absolute vs. Relative imports
In absolute imports, you need to specify the explicit path from the project’s root directory.
Example – If we have to import module b then we can use the following way to import
import secondpackage.b
Other ways of importing modules in Python
# importing modules a.py
import secondpackage.subpackage.d
import secondpackage.c
In case of relative imports, we need to specify the module’s path relative to the current module’s location.
Example –
# in module a.py
from ..secondpackage import b
from ..secondpackage.b import another_function
# in module b
from . import c
from .c import my_function
Option 1 – Use absolute imports
For instance, the directory structure may be as follows
.
├── project
│ ├── package
│ │ ├── __init__.py
│ │ ├── module.py
│ │ └── standalone.py
│ └── setup.py
where setup.py is
from setuptools import setup, find_packages
setup(
name = 'your_package_name',
packages = find_packages(),
)
Option 2 – Get rid of from keyword
Remove the from keyword and use the standard way of import as shown below.
import secondpackage.c
Option 3 – Import inside package init file
Put this inside your package’s __init__.py file:
# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Assuming your package is like this:
├── project
│ ├── package
│ │ ├── __init__.py
│ │ ├── module1.py
│ │ └── module2.py
│ └── setup.py
Now use regular imports in you package, like:
# in module2.py
from module1 import class1
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
This article will discuss the error – ImportError: Attempted Relative Import With No Known Parent Package. The primary reason for this error is that the specified module does not exist within the Python library.
In Python, the failure to import a module, module member, or other python files results in ImportError.
What Causes This Error?
Let’s take the following file structure as an example to better understand the reasons for this error.
->ProjectDirectory
|
|
|
---->myPackage1
- __init__.py
- runCode.py
|
|
|
---->myPackage2
- __init__.py
- function.py
ProjectDirectory
Consists of 2 folders : myPackage1
(runCode.py) and myPackage2
(function.py).
runCode.py
from .myPackage2 import runFunction print("Running Code") function.runFunction()
function.py
def runFunction(): print("Running Function")
Note that the runCode.py
program makes use of the function from function.py
by importing.
Now, let’s discuss what’s relative importing.
In runCode.py, note that a dot(.) is used in the import statement. This usage of the dot indicates a relative import. As we call a function from a different package(directory), the caller program (runCode.py) has to call one level above. Multiple directory levels require multiple dots. This is the concept of relative importing. Its counter-technique. Absolute importing requires the complete path.
Let’s look at the actual error produced by runCode.py
C:UsersSampleFolderPythonProgramsProjectDirectorymyPackage > python runCode.py Traceback (most recent call last): File "C:UsersSampleFolderPythonProgramsProjectDirectorymyPackagerunCode.py", line 1m in <module> from myPackage2 import runFunction ImportError: attempted relative import with no parent package
This is due to the fact that a parent package doesn’t exist.
How To Solve This Error?
The most straightforward approach is to make the particular package global using a setup.py file. Let’s look at the following steps to achieve the same.
Creating a Setup File
Create a Setup file using the setuptools
module from Python. The setup file defines the package to be made global.
from setuptools import setup, find_packages setup(name = "myPackage2", packages = find_packages())
The above lines import the module from myPackage2.
Running the Setup File
Access your project directory and run the following command in your command terminal.
python setup.py install
Changing the Caller Program (runCode.py)
Remove the dot from the import statement now that the package is global.
from myPackage2 import function print("Running Code") function.runFunction()
Output
C:UsersSampleFolderPythonProgramsProjectDirectorymyPackage > python runCode.py Running Code Running Function
Let’s look at the following program that deals with unit testing.
import unittest from ..programUtil import util class TestUrlUtilities(unittest.SampleTestCase): def test_simple(self): result = name_from_link("https://pythonpool.com") self.assertEqual(result, "Python") if __name__ == "__main__": unittest.main()
Output
ERROR: program_utilities(unittest.loader._FailedTest) ImportError: Failed to import test module: program_utilities Traceback (most recent call last): File "C:Python37libunittestloader.py", line 13, in loadTestsFromName module = __import__(module_name) ImportError: attempted relative import with no known parent package
What do we do in this situation? As the error says, the test folder doesn’t contain a parent package. This means using double dots (..) to import relatively will not work.
Go to the project source directory and run the following command:
python -m unittest
This creates a src
folder for our project path. Now that our module is in the path, there is no need for a relative import (..).
ImportError: Attempted Relative Import With No Known Parent Package Django
When you import a function into your Django project, you may receive the ImportError. This is due to the fact that you cannot import relatively from a direct run script. Relative imports work only if the package has been imported completely as a module.
For example, if a code is passed through /user/stdin
, there isn’t a reference for the file’s location.
Use relative imports when running .py programs. If a relative import is a must, convert the program file as a __main__.py file within the package directory while passing the Python -m command to run the module.
ImportError: Attempted Relative Import With No Known Parent Package IntelliJ (PyCharm IDE)
In this scenario, the program files may run without error. However, the unit test can fail and produce relative import errors when run from the program file’s directory.
To solve this problem, set the working directory as the top-level project directory. After this, any unit tests or relative imports will run properly. In summary, resetting the working directory should fix the relative import errors.
Attempted Relative Import Beyond Top Level Package Error
Let’s take the following file structure as an example
myModule/ __init__.py P/ __init__.py program.py testProgram_P/ __init__.py testCode.py
testCode.py
from ..P import program
To run tests, you may pass the following command within the myModule
directory
python -m testProgram_P.testCode
This can result in the following error:
"ValueError: attempted relative import beyond top-level package"
However, within the parent folder of myModule
, testProgram_P.testCode
will run perfectly.
Why does this error occur?
This is due to the fact that Python doesn’t keep track of the package location. Therefore, upon running python -m testProgram_P.testCode
Python doesn’t take into account that the file is located in myModule
. This means writing from ..P import program
is basically trying to fetch information that does not exist anymore.
FAQs
What is a Relative Import?
A relative import in Python specifies the content to be imported into the project, which is relative to its exact location.
What should __init___.py contain?
__init__.py file may contain Python code that a python package would have. However, Python will add extra attributes to the package whenever imported.
What is __import__() in Python?
The __import__() function is used by the Python import statement to import packages into the Python project. It takes the following parameters:name
– name of the module to be importedglobals/locals
– Determines the nature of the package.fromlist
– extra objects or submodules to be imported by the modulelevel
– specifies the type of import (absolute/relative)
Conclusion
In this article, we have looked at the exception: ImportError: Attempted Relative Import With No Known Parent Package. This error shows us how much the structure of a working directory matters in Python. We have learned that Python does not consider the current working directory to be a package itself, therefore hindering relative imports.
Trending Python Articles
-
[Solved] typeerror: unsupported format string passed to list.__format__
●May 31, 2023
-
Solving ‘Remote End Closed Connection’ in Python!
by Namrata Gulati●May 31, 2023
-
[Fixed] io.unsupportedoperation: not Writable in Python
by Namrata Gulati●May 31, 2023
-
[Fixing] Invalid ISOformat Strings in Python!
by Namrata Gulati●May 31, 2023
Importerror attempted relative import with no known parent package error occurs when we import any module from any package (Directory) where __init__.py file is missing or the path for the package is undefined. In this article, We will practically fix this problem.
In order to understand the cause let’s take a scenario for example. Suppose this is the file structure –
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
This article will discuss the error – ImportError: Attempted Relative Import With No Known Parent Package. The primary reason for this error is that the specified module does not exist within the Python library.
In Python, the failure to import a module, module member, or other python files results in ImportError.
What Causes This Error?
Let’s take the following file structure as an example to better understand the reasons for this error.
->ProjectDirectory
|
|
|
---->myPackage1
- __init__.py
- runCode.py
|
|
|
---->myPackage2
- __init__.py
- function.py
ProjectDirectory
Consists of 2 folders : myPackage1
(runCode.py) and myPackage2
(function.py).
runCode.py
from .myPackage2 import runFunction print("Running Code") function.runFunction()
function.py
def runFunction(): print("Running Function")
Note that the runCode.py
program makes use of the function from function.py
by importing.
Now, let’s discuss what’s relative importing.
In runCode.py, note that a dot(.) is used in the import statement. This usage of the dot indicates a relative import. As we call a function from a different package(directory), the caller program (runCode.py) has to call one level above. Multiple directory levels require multiple dots. This is the concept of relative importing. Its counter-technique. Absolute importing requires the complete path.
Let’s look at the actual error produced by runCode.py
C:UsersSampleFolderPythonProgramsProjectDirectorymyPackage > python runCode.py Traceback (most recent call last): File "C:UsersSampleFolderPythonProgramsProjectDirectorymyPackagerunCode.py", line 1m in <module> from myPackage2 import runFunction ImportError: attempted relative import with no parent package
This is due to the fact that a parent package doesn’t exist.
How To Solve This Error?
The most straightforward approach is to make the particular package global using a setup.py file. Let’s look at the following steps to achieve the same.
Creating a Setup File
Create a Setup file using the setuptools
module from Python. The setup file defines the package to be made global.
from setuptools import setup, find_packages setup(name = "myPackage2", packages = find_packages())
The above lines import the module from myPackage2.
Running the Setup File
Access your project directory and run the following command in your command terminal.
python setup.py install
Changing the Caller Program (runCode.py)
Remove the dot from the import statement now that the package is global.
from myPackage2 import function print("Running Code") function.runFunction()
Output
C:UsersSampleFolderPythonProgramsProjectDirectorymyPackage > python runCode.py Running Code Running Function
Let’s look at the following program that deals with unit testing.
import unittest from ..programUtil import util class TestUrlUtilities(unittest.SampleTestCase): def test_simple(self): result = name_from_link("https://pythonpool.com") self.assertEqual(result, "Python") if __name__ == "__main__": unittest.main()
Output
ERROR: program_utilities(unittest.loader._FailedTest) ImportError: Failed to import test module: program_utilities Traceback (most recent call last): File "C:Python37libunittestloader.py", line 13, in loadTestsFromName module = __import__(module_name) ImportError: attempted relative import with no known parent package
What do we do in this situation? As the error says, the test folder doesn’t contain a parent package. This means using double dots (..) to import relatively will not work.
Go to the project source directory and run the following command:
python -m unittest
This creates a src
folder for our project path. Now that our module is in the path, there is no need for a relative import (..).
ImportError: Attempted Relative Import With No Known Parent Package Django
When you import a function into your Django project, you may receive the ImportError. This is due to the fact that you cannot import relatively from a direct run script. Relative imports work only if the package has been imported completely as a module.
For example, if a code is passed through /user/stdin
, there isn’t a reference for the file’s location.
Use relative imports when running .py programs. If a relative import is a must, convert the program file as a __main__.py file within the package directory while passing the Python -m command to run the module.
ImportError: Attempted Relative Import With No Known Parent Package IntelliJ (PyCharm IDE)
In this scenario, the program files may run without error. However, the unit test can fail and produce relative import errors when run from the program file’s directory.
To solve this problem, set the working directory as the top-level project directory. After this, any unit tests or relative imports will run properly. In summary, resetting the working directory should fix the relative import errors.
Attempted Relative Import Beyond Top Level Package Error
Let’s take the following file structure as an example
myModule/ __init__.py P/ __init__.py program.py testProgram_P/ __init__.py testCode.py
testCode.py
from ..P import program
To run tests, you may pass the following command within the myModule
directory
python -m testProgram_P.testCode
This can result in the following error:
"ValueError: attempted relative import beyond top-level package"
However, within the parent folder of myModule
, testProgram_P.testCode
will run perfectly.
Why does this error occur?
This is due to the fact that Python doesn’t keep track of the package location. Therefore, upon running python -m testProgram_P.testCode
Python doesn’t take into account that the file is located in myModule
. This means writing from ..P import program
is basically trying to fetch information that does not exist anymore.
FAQs
What is a Relative Import?
A relative import in Python specifies the content to be imported into the project, which is relative to its exact location.
What should __init___.py contain?
__init__.py file may contain Python code that a python package would have. However, Python will add extra attributes to the package whenever imported.
What is __import__() in Python?
The __import__() function is used by the Python import statement to import packages into the Python project. It takes the following parameters:name
– name of the module to be importedglobals/locals
– Determines the nature of the package.fromlist
– extra objects or submodules to be imported by the modulelevel
– specifies the type of import (absolute/relative)
Conclusion
In this article, we have looked at the exception: ImportError: Attempted Relative Import With No Known Parent Package. This error shows us how much the structure of a working directory matters in Python. We have learned that Python does not consider the current working directory to be a package itself, therefore hindering relative imports.
Trending Python Articles
-
[Solved] typeerror: unsupported format string passed to list.__format__
●May 31, 2023
-
Solving ‘Remote End Closed Connection’ in Python!
by Namrata Gulati●May 31, 2023
-
[Fixed] io.unsupportedoperation: not Writable in Python
by Namrata Gulati●May 31, 2023
-
[Fixing] Invalid ISOformat Strings in Python!
by Namrata Gulati●May 31, 2023
Importerror attempted relative import with no known parent package error occurs when we import any module from any package (Directory) where __init__.py file is missing or the path for the package is undefined. In this article, We will practically fix this problem.
In order to understand the cause let’s take a scenario for example. Suppose this is the file structure –
As you can see, we are having two packages –
package_one -> script.py
Here is the code inside script.py-
from .package_two import functionality
print("Running Script file")
functionality.execute()
package_two -> functionality.py
## functionality.py file
def execute():
print("Running functionality")
Now you can see that we are importing package_two module functionality.py in the script.py file of package_one.
Relative Import –
While importing we use (.) dot before as you can see below image. This makes it a relative import. Let me explain since we are calling functionality modules from script.py files which are belonging to different packages( directories). Hence the caller file (script.py ) has to go one level up that is why one (.) dot. If suppose there are more directory levels we can use multiple dots for the same.
This is called relative importing while absolute importing needs a full path for the same.
Let’s run and see the error-
since we do not have a parent package define.
Importerror attempted relative import with no known parent package ( Solution) –
The easiest way to fix this relative import error is using the setup.py file, we can make the respective package global. Here are the steps-
Step 1: Create setup.py file-
All you need to create a simple python file with a setup name. Here we will define which package we want to make global.
from setuptools import setup, find_packages
setup(name = 'package_two', packages = find_packages())
In the above example, We are importing module from package_two.
Step 2: Running setup.py file –
Use the below command –
python setup.py install
Step 3: Modifying caller script –
We need to call this script.py file but as we have made this package global so need to remove this (.) in importing statement.
from package_two import functionality
print("Running Script file")
functionality.execute()
Now, let’s run this script.py file.
Hey !! we have cracked the same.
Notes –
As an alternative to this approach, we can also move the relevant package to the directory where we have a path set.
Or we can copy the same package to any existing directory for which path is already configured.
In order to set the path for the package, We can use sys and pathlib modules.
Read more in detail about ImportErrors in the below well written and informative article.
Easiest way to Fix importerror in python ( All in One )
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.