Importerror attempted relative import with no known parent package как исправить

ImportError: attempted relative import with no known parent package occurs in Python 3.6 and newer mainly and if you are doing relative import in a module.
Table of Contents
Hide
  1. How does module import work in Python?
  2. Absolute vs. Relative imports
  3. How to fix ImportError: attempted relative import with no known parent package?
    1. Option 1 – Use absolute imports
    2. Option 2 – Get rid of from keyword
    3. 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

Ezoic

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

Avatar Of Srinivas Ramakrishna

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.

It seems, from Python docs and experimenting, that relative imports (involving ., .. etc) only work if

  1. the importing module has a __name__ other than __main__, and further,
  2. the __name__ of the importing module is pkg.module_name, i.e., it has to be imported from above in the directory hierarchy (to have a parent pkg as part of it’s __name__.)

OR

the importing module is being specified via module syntax that includes a parent pkg as python -m pkg.module, in which case it’s __name__ is still __main__, so it is being run as a script, yet relative imports will work. Here __package__ is set and used to find the parent package while __name__ is __main__; more here.

[After all that, it appears that __package__ and sys.path are key to determining if/how relative imports work. __name__ indicates script or module(i.e., __main__ or module_name). __package__ indicates where in the package the relative imports occur with respect to, and the top of __package__ needs to be in sys.path.]

So, continuing with @AmitTendulkar ‘s example, if you run this as > python main.py or > python -m main or > python -m ecommerce.products from the project root directory, or enter interactive python from that root directory and import main, or import ecommerce.products the relative imports in products.py will work.

But if you > python products.py or > python -m products from within ecommerce directory, or enter interactive python from that ecommerce directory and import products they will fail.

It is helpful to add

print("In module products __package__, __name__ ==", __package__, __name__)

etc. in each file to debug.

UPDATE:

How imports work depend on sys.path and __package__, not on __name__.
Issued from /home/jj, > python sub/mod.py has a sys.path, __package__ of /home/jj/sub, None -absolute imports of modules in sys.path work, relative imports fail.

> python -m sub.mod has sys.path, __package__ of /home/jj, sub -absolute imports of modules in sys.path work, relative imports work relative to sys.path + __package__.

It is more helpful to add

import sys    
print("In module products sys.path[0], __package__ ==", sys.path[0], __package__)

etc. in each file to debug.

  • Why “ImportError: attempted relative import with no known parent package” is Raised?
  • Avoid ImportError: attempted relative import with no known parent package
    • 2 Ways to Check Whether the module belongs to a package
  • Sample for “ImportError: attempted relative import with no known parent package”
    • Review the __name__ and __package__ variables
  • How to fix “ImportError: attempted relative import with no known parent package”
    • Solution 1 : Change Directory Structure
    • Solution 2 : Use the -m option
    • Solution 3 : Workaround Without Changing Directory Structure
  • Summary

Relative imports in python can be frustrated from time to time. Therefore, from time to time, you may meet the mysterious and obscure exception “ImportError: attempted relative import with no known parent package” Let’s see what this exception means, why it is raised. Finally, we see how to get rid of the “ImportError: attempted relative import with no known parent package” exception 

As a rule of thumb – If you try to do relative import in a module that does not belong to a package, you will get the “ImportError: attempted relative import with no known parent package” exception.

Why? The reasons beyond this rule of thumb are related to how relative import works in python.

In PEP 328 (Imports: Multi-Line and Absolute/Relative) that add the support of relative imports, we can find how the python interpreter should resolve the relative modules.

Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy.

PEP 328

First, this statement implies that relative import is relative to the current package. What is the current package? The current package is the package the current module belongs to. However, you probably know that not all modules belong to a package. Therefore, the module where we do the relative import must belong to a package, or otherwise, the python interrupter will scream that you are doing something wrong.

Second, this statement describes how the python interrupter should find the current package when it searches for the imported module. When the Python interrupter tries to find out the current package, It obtains the package information by checking the value of the __name__ variable (the module’s name).

What should the interrupter do when the module’s name does not contain any package information?

If the module’s name does not contain any package information (e.g., it is set to __main__), then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.

PEP 328

If __name__ variable does not have any package information, the python interpreter should treat the module as a top-level module (a module that does not belong to any package). In that case, the current package does not exist. Therefore, the python interpreter can not resolve the location of the imported module and you get “ImportError: attempted relative import with no known parent package

This description shows one of the best example of a module that does not belong to a package : the __main__ module. The __main__ module, the script you invoked the python interrupter with, does not belong to any package. We use this example later to demonstrate how to get rid of “ImportError: attempted relative import with no known parent package” exception.

Avoid ImportError: attempted relative import with no known parent package

As we see, when you try to do relative import in a module that does not belong to a package, you will get the “ImportError: attempted relative import with no known parent package” exception. It is essential to know that the module where you do relative import belongs to a package; otherwise, you get this irritating exception.

2 Ways to Check Whether the module belongs to a package

One way to check if a module belongs to a package is to review the value of __name__ variable. If the __name__ variable contains a dot, the module belongs to a package.

Another way to check if a module belongs to a package is to review the value of __package__ variable. if the __package__ variable do not equal to None, the module belongs to a package.

Sample for “ImportError: attempted relative import with no known parent package”

The following sample demonstrates that the main module (The script you invoked the python interrupter with) does not belong to a package.

Suppose you have a project with the following simple directory structure:

Sample Directory Structure
 root
 ├── config.py
 └── package
     ├── __init__.py
     └── program.py

You are trying access variables defined in the config.py in your program.py. It seems a straightforward task and you choose to use relative import:

root/package/program.py
from .. import config
print("config.count => {0}".format(config.count))

However, when invoking program.py script, An exception is raised :

“ImportError: attempted relative import with no known parent package” Is Raised
Y:/root>python package/program.py
Traceback (most recent call last):
  File "package/program.py", line 1, in <module>
    from .. import config
ImportError: attempted relative import with no known parent package

Review the __name__ and __package__ variables

Let’s review the values of the __name__ and __package__ variables by adding some log messages at the top of the above modules:

root/config.py with logs
print('__file__={0:<35} | __name__={1:<25} | __package__={2:<25}'.format(__file__,__name__,str(__package__)))

count = 5
root/package/program.py with logs
print('__file__={0:<35} | __name__={1:<25} | __package__={2:<25}'.format(__file__,__name__,str(__package__)))

from .. import config
print("config.count => {0}".format(config.count))
Invoking program.py
Y:/root>python package/program.py
__file__=package/program.py                  | __name__=__main__                  | __package__=None
Traceback (most recent call last):
  File "package/program.py", line 3, in <module>
    from .. import config
ImportError: attempted relative import with no known parent package

As we can see in the above output, the value of the value of __package__ is None and the value of __name__ variable is __main__.

Since, the value __package__ is None and the value of the variable __name__ does not contains any dot, we can know that module does not belong to any package. Therefore, the python interrupter raises the unclear exception.

How to fix “ImportError: attempted relative import with no known parent package”

Solution 1 : Change Directory Structure

In this solution, we need to change directory structure and create a new script

  • First, create a new directory named new_root and move the root directory to new_root
  • Create main.py in new_root directory
  • Create a new empty __init__.py inside the root directory. This will signal to the python interrupter that this directory is a package.
The sample directory
 new_root
 ├── main.py
 └── root
     ├── __init__.py
     ├── config.py
     └── package
         ├── __init__.py
         └── program.py
Updating new_root/main.py
print('__file__={0:<35} | __name__={1:<25} | __package__={2:<25}'.format(__file__,__name__,str(__package__)))

import root.package.program

When we invoke the new script, we get the following output:

Invoking program.py
Y:/new_root>python main.py
__file__=main.py                             | __name__=__main__                  | __package__=None
__file__=Y:/new_root/root/package/program.py | __name__=root.package.program      | __package__=root.package
__file__=Y:/new_root/root/config.py          | __name__=root.config               | __package__=root
config.count => 5

It works. Let’s see why?

Now, the module root.package.program belongs to root.package.

We can see it in the second line (The print from the top of new_root/root/package/program.py).

__file__=Y:/new_root/root/package/program.py | __name__=root.package.program      | __package__=root.package

Now, when this module belong to a package, the python interpreter has all the information has all the information to resolve the relative import in root/package/program.py successfully.

Solution 2 : Use the -m option

In the first solution, we need to create a new script. In this solution, we use -m option without creating a new script.

Let’s change directory structure and use -m option

  • First, create a new directory named new_root and move the root directory to new_root
  • Create a new empty __init__.py inside the root directory. This will signal to the python interrupter that this directory is a package.
The sample directory
 new_root  
 └── root
     ├── __init__.py
     ├── config.py
     └── package
         ├── __init__.py
         └── program.py

Now, we invoke python with -m option and provide the module root.package.program.

The python -m option allows modules to be located using the Python module namespace for execution as scripts. As the following output demonstrate, It will also set the package information:

Invoking program.py with -m option
Y:/new_root>python -m root.package.program
__file__=Y:/new_root/root/package/program.py | __name__=__main__                  | __package__=root.package
__file__=Y:/new_root/root/config.py          | __name__=root.config               | __package__=root
config.count => 5

It works. Let’s see why?

Now, the module root.package.program belongs to root.package.

We can see it in the first line (The print from the top of new_root/root/package/program.py).

__file__=Y:/new_root/root/package/program.py | __name__=__main__                  | __package__=root.package

Now, when this module belong to a package, the python interpreter has all the information has all the information to resolve the relative import in root/package/program.py successfully.

Note: Unlike PEP 328, the python interpreter do not rely on the value of __name__ to find the package information and uses the value of __package__.

Solution 3 : Workaround Without Changing Directory Structure

In previous solutions, we needed to change the directory structure. Sometimes, you want to avoid changing the directory structure. For example, the framework you use in your code (such as django, pytest, airflow, fastapi or flask) or the environment you work with (such as pycharm, vscode or jupyter notebook) depend on this directory structure. In those cases, you may consider the following workaround.

As we see in solution 2, the python interrupter relies on the __package__ variable to extract the package information. Therefore, when the __package__ is none, the python interrupter will cry that you are doing something wrong.

So, Let’s use this observation and enclose the relative import with the following if statement based on the value of the __package__ variable.

Invoking program.py with -m option
if __package__:
    from .. import config
else:
    sys.path.append(os.dirname(__file__) + '/..')
    import config

It works. Let’s see why?

If the __package__ is not None, we can safely use relative import. However, if __package__ is None, we can not use relative import anymore. Therefore we add the directory of the module to sys.path and import the required module. Since sys.path is a list of paths that specify where the python interrupter should search for imported modules, python interrupter will find the required module.

How to generate the directory?

First, replace the first dot in the relative import with os.dirname(__file__) and then replace each successive dot with “../”. Now append successive part between the dots.

from . import config sys.path.append( os.dirname(__file__) )
import config
from .. import config sys.path.append( os.path.join( os.dirname(__file__), ‘..’ ) )
import config
from … import config sys.path.append( os.path.join( os.dirname(__file__), ‘..’ , ‘..’ ))
import config
from ..a.b.c import config sys.path.append( os.path.join( os.dirname(__file__), ‘..’ , ‘a’ ,’b’ ,’c’ ))
import config

OR better (less chance for name clashing)

sys.path.append( os.path.join( os.dirname(__file__), ‘..’ ))
from a.b.c import config

relative import : examples of adding path to sys.path

However, this method is very fragile. If a module with the required name (in our case, config) already exists in the sys path’s previous paths, the python interrupter will import it instead of our module. It can be a source of nasty and mysterious bugs.

So use this workaround with caution and only when necessary.

Summary

We see how the python interrupter resolve relative imports. Then, we see why the “ImportError: attempted relative import with no known parent package” exception is raised. Finally we see how to get rid of “ImportError: attempted relative import with no known parent package”

Here’s everything about ImportError: attempted relative import with not known parent package in Python.

You’ll learn:

  • 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!

Polygon art logo of the programming language Python.

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.

Programmer stressed while analyzing codes in his computer.

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:

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:

Python comic.

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:

supergraphics
 | - graphics
 |	 | --rectangles.py
 |	 | --circles.py 	
 | - utils
 |	 | --resize
 |	 |	| --shrink.py
 |	 |	| --stretch.py
 |	 | --screen.py 
 |	 | --printer.py
 | --unittests.py

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:

import supergraphics.graphics 

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:

import .graphics

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:

import ...graphics Imagine

You can consider that the invisible word parent precedes each dot:

import __parent__.__parent__.__parent__.graphics

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.

Close-up of hand typing on a keyboard, concept of an office job.

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:

hi
 | - say_hello.py
 |	def hello(name):  
 |   	   return f"Hello, {name}!" 
 | - introduce.py
 |	 from .say_hello import hello  
 |	    def hello_to():  
 |	    name = input('What is your name?n')  
 |	    return hello(name) + ' nNice to meet you!'  
 | --__ init__.py

You can now use your package from the Python terminal:

>>> from hi.introduce import hello_to
>>> print(hello_to())
What is your name?
Robot
Hello, Robot!
Nice to meet you!

Now let’s add testing to the introduce.py file. It will look like this:

from .say_hello import hello 	
def hello_to():	
   name = input('What is your name?n')  
   return hello(name) + ' nNice to meet you!' 	
if __name__ == '__main__':
   assert 'Alex' in hello('Alex')  
   print('Test passed!')

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:

(venv)> python hiintroduce.py
Traceback(most recent call last):
  File "hiintroduce.py", line 1, in <module>
    from .say_hello import hello
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:

(venv)> python -m hi.introduce
Test passed!

Now you can run this file as a script without the -m key:

from hi.say_hello import hello 	
def hello_to():	
   name = input('What is your name?n')  
   return hello(name) + ' nNice to meet you!' 	
if __name__ == '__main__':
   assert 'Alex' in hello('Alex')  
   print('Test passed!')  

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:

Project
   | --hi
 | - say_hello.py
 |	def hello(name):  
 |   	   return f"Hello, {name}!" 
 | - introduce.py
 |	 from .say_hello import hello  
 |	    def hello_to():  
 |	    name = input('What is your name?n')  
 |	    return hello(name) + ' nNice to meet you!'  
 | --__ init__.py

		(venv)Project> python hiintroduce.py
Traceback(most recent call last):
  File "hiintroduce.py", line 1, in <module>
    from hi.say_hello import hello
ModuleNotFoundError: No module named 'hi'

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.

Programmer looking stressed while looking at codes on the monitor.

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:

from setuptools import setup, find_packages  
setup(name = 'hi', packages = find_packages())

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:

(venv)> python hisetup.py install

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:

import sys  
from pathlib import Path  
file = Path(__ file __). resolve()  
package_root_directory = file.parents [1]  
sys.path.append(str(package_root_directory))  
  
from hi.say_hello import hello  
def hello_to():  
    name = input('What is your name?n')  
    print(hello(name) + 'nNice to meet you!')  
if __name__ == '__main__':  
    assert 'Alex' in hello('Alex')  
    print('Test passed!')

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:

Project
   | --hi
 | - say_hello.py
 | - introduce.py
 | --__ init__.py

file.parents[0] =.Projecthi
file.parents[1] =.Project

If the tree structure were deeper, then the parents with higher indices would have to be used.

Here’s more Python support:

  • 9 Examples of Unexpected Character After Line Continuation Character
  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
  • How to Solve ‘Tuple’ Object Does Not Support Item Assignment
  • How to Solve SyntaxError: Invalid Character in Identifier
  • IndentationError: Unexpected Unindent in Python (and 3 More)
Solve Attempted Relative Import With No Known Parent Package in Python

Relative imports in Python can be tricky, especially when dealing with multiple modules within a single directory. Depending on how you design your Python codebase, you can experience an ImportError.

However, a good understanding of the import system is sufficient to prevent such errors, including the ImportError: attempted relative import with no known parent package. The error message makes it easy to troubleshoot where the problem might stem from.

In this case, it is from the non-presence of the parent package. This article showcases and explains how to solve the ImportError issue.

Use submodules to Solve the ImportError: attempted relative import with no known parent package in Python

The error ImportError: attempted relative import with no known parent package stems when we use the .module_name expression as in the code below.

Let’s replicate the issue by creating three files within a new directory. You can use the structure below to test it out.

The IError directory houses all the Python code, and the myPackage directory houses all the package files. Then, the [main.py](http://main.py) accesses the myPackage.py.

IError/
    myPackage/
        __init__.py
        myNewPackage.py
    main.py

To recreate the error message, we need only the __init__.py file. The __init__.py file lets the Python interpreter know that a directory contains Python module code, in this case, the myNewPackage.py.

Before we recreate the error, let’s write the code that will be contained in all three Python files.

In the myNewPackage.py file, the below code snippet is present:

def createSingleDict(name, value):
    return {"name": name, "value": value}

The __init__.py file:

from .myNewPackage import createSingleDict

The main.py file, which uses the myPackage module:

import myPackage as pkg

User = pkg.createSingleDict("Jacob", 25)

print(User)

The myNewPackage.py contains a single function that takes two arguments and returns a dictionary with the arguments passed. The __init__.py uses the import statement and keywords, from and import to import the myNewPackage.py into the __init__.py file.

The main.py imports the myPackage without using the myPackage.myNewPackage expression. All of these are possible because of submodules.

The __init__.py file and the statement within it load the submodule mechanism where the myNewPackage file (attribute) is bound to the parent (myPackage) namespace.

The key part of the statement within the __init__.py file is the dot before the module name. This allows for the binding to the placed to the parent’s module.

Remember the part of the error message, with no known parent package. This is the reason you are experiencing the error.

Let’s run just the __init__.py file. The output of the execution is below.

Traceback (most recent call last):
  File "c:UsersakinlDocumentsIErrormyPackage__init__.py", line 1, in <module>
    from .myNewPackage import createSingleDict
ImportError: attempted relative import with no known parent package

This error occurs because we are running the __init__.py file without the context of the parent namespace, myPackage. However, if we run the main.py with the import statement, import myPackage as pkg, we will not have any errors.

The output can be seen below:

{'name': 'Jacob', 'value': 25}

Therefore, don’t use the . operator before the module_name unless within the __init__.py or the binding or context of a parent namespace to prevent the ImportError: attempted relative import with no known parent package.

To better understand what is going on, if you remove the . operator within the import statement in __init__.py, we will not have any errors running the file.

from myNewPackage import createSingleDict

However, if we run the main.py file, it will cause the error below because we have not made binding of the myNewPackage module to the parent module, myPackage.

Traceback (most recent call last):
  File "c:UsersakinlDocumentsIErrortempCodeRunnerFile.py", line 1, in <module>
    import myPackage as pkg
  File "c:UsersakinlDocumentsIErrormyPackage__init__.py", line 1, in <module>
    from myNewPackage import createSingleDict
ModuleNotFoundError: No module named 'myNewPackage'

To make the code run, we will have to use the . operator within the import statement in main.py and remove (delete) the __init__.py file.

import myPackage.myNewPackage as pkg

User = pkg.createSingleDict("Jacob", 25)

print(User)

However, this is cumbersome, and it makes more sense to bind your submodules to the parent module using the . operator within __init__.py, but always make sure you are running it within the parent context.

If you have two submodules, it works the same way. The new submodules otherPackage.py may contain the code below:

def printName(name):
    print("The user's name is " + name)

You update the __init__.py file to bind the new submodule to the parent namespace.

from .myNewPackage import createSingleDict
from .otherPackage import printName

And within the main.py, you have to use the alias pkg to access the function within the other submodule. That is the beauty of binding to the parent namespace, the ease of importing.

import myPackage as pkg

User = pkg.createSingleDict("Jacob", 25)

print(User)
pkg.printName("Jacob")

The output of the code:

{'name': 'Jacob', 'value': 25}
The user's name is Jacob

With all these, you have all the required information to prevent or solve the ImportError: attempted relative import with no known parent package within your Python codebase.

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.

“Other Commands Don’t Work After on_message” in Discord Bots

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.

[Resolved] NameError: Name _mysql is Not Defined

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.testCodePython 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:
namename of the module to be imported
globals/locals Determines the nature of the package.
fromlist extra objects or submodules to be imported by the module
levelspecifies 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

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 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 –

import with no known parent package example scenario

import with no known parent package example scenario

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.

import with no known parent package explanation

import with no known parent package explanation

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-

Importerror attempted relative import with no known parent package

Importerror attempted relative import with no known parent package

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

setup file

setup file

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.

import with no known parent package solved

import with no known parent package solved

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.

sys path management

sys path management

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.

Every program in any programming language starts with a header file, package, or module. In Python, the Import statement is the first statement of the program that allows users to import modules into the code. It has a similar function to the #include header_file statement of C or C++.

Python modules can access the built-in code from other modules by importing the Python function or file using the word «import.» But most Python users do not know that their program may show an error if they fail to use the packages in a proper format.

This article will discuss one of the most common error messages, i.e., the ImportError: attempted relative import with no known parent package in Python.

What is import statement in Python?

One of the most common ways to invoke import machinery is to use the import statement, but apart from this, users can also add to the Python import. The import statement comprises the import keyword, including the name of a Python module.

In the import statement, the interpreter performs two operations, i.e., it involves two procedures. Firstly, import looks for a module, and secondly, the import wraps the search result to the name in the local scope.

When users import a module in their code, Python executes all of the code of the desired module file and presents it to the importer file to run.

Syntax of an import statement in Python:

The import statement allows programmers to import both packages and modules. Generally, Python has two types of import syntax. When programmers use the first import syntax, they import the built-in resource directly. Programmers can also import specific objects from the module or package.

Note:

It is a point to remember that when users import a package, it virtually imports the package’s __init__.py file as a module.

import abcd

Here, «abcd» can either be a package or a module. Again, when users use the second syntax, i.e., they can also import the resource from other packages or modules.

Syntax:

from abcd import mod

here, the «mod» can be a subpackage, module, or object, like a class or function.

What are packages and modules in Python?

Before understanding this error, we have to understand the concept of packages & modules so that we can easily debug those errors. When users use a package in a Python code, they import the file __init__.py, which is for every user-oriented code.

A Python package operates on a library, explaining the whole Python code as a single unit of a particular function. A Python package also changes the user-interpreted code by modifying it so that the Python interpreter can efficiently operate it in the run time.

On the other hand, a Python module is a file including Python code in run time for any user-oriented code. The Python modules are different libraries themselves, which contain built-in functions.

Syntax:

from abcd import mod

Here, the term «abcd» signifies a package, and the term «mod» defines a module or a sub package.

The cause behind the error named, ImportError: attempted relative import with no known parent package in python:

Before fixing the error, let us know why the Python interpreter shows the Importerror message. as we have discussed above, users can import a module inside a package, two packages, or one module inside another module.

Often, programmers make a mistake while calling a package in the import statement. They should know the difference between the parent package and the subpackage while importing.

If users fail to import the parent library in the import statement, the interpreter will show the error message, «ImportError: attempted relative import with no known parent package in Python.»

How to fix the «Importerror attempted relative import with no known parent package» error in Python?

The solution to this problem is easy. Before advancing to the body of the Python program, programmers first create a Python file with their setup name; then make that package global so they can easily access it.

After users create their file, inside that file, they need to specify the name of the Python package they want to import.

Let us see an example with the help of a code and understand it more precisely:

from setuptools import setup, find_packages
setup(name = 'package_two', packages = find_packages())

Here, you can see that we have provided our package name. Now we need to remove the relative path from our one.py file.

To do so follow the below code example:

Code Snippet:

from package_two import second_module
print("Hello World!")
two.fun()

Output:

Explanation:

Now, we can see in the above output there is no error message. Both the parent package and the module are known to the interpreter.

An example to show how to use the Python packages and modules in the right format:

└── myproject
├── first_package
│ ├── A.py
└── second_package
├── B.py
├── C.py
└── sub_package
└── D.py

Conclusion:

We hope from this article; Python programmers get the solution to fix the error named «ImportError: attempted relative import with no known parent package.» Debugging these import-related errors is essential in the real-life scenarios where software development requires using packages & modules frequently to reduce or eliminate repetitive work in Python prorgrams.

Содержание

  1. How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python)
  2. How to Solve ImportError: Attempted Relative Import With No Known Parent Package (ModuleNotFoundError: No module named ‘name’)
  3. Understand the Error ImportError: Attempted Relative Import With No Known Parent Package
  4. ImportError: attempted relative import with no known parent package
  5. How does module import work in Python?
  6. Absolute vs. Relative imports
  7. How to fix ImportError: attempted relative import with no known parent package?
  8. Option 1 – Use absolute imports
  9. Option 2 – Get rid of from keyword
  10. Option 3 – Import inside package init file
  11. ImportError: Attempted Relative Import With No Known Parent Package
  12. What Causes This Error?
  13. runCode.py
  14. function.py
  15. How To Solve This Error?
  16. Creating a Setup File
  17. Running the Setup File
  18. Changing the Caller Program (runCode.py)
  19. ImportError: Attempted Relative Import With No Known Parent Package Unit Tests
  20. ImportError: Attempted Relative Import With No Known Parent Package Django
  21. ImportError: Attempted Relative Import With No Known Parent Package IntelliJ (PyCharm IDE)
  22. Attempted Relative Import Beyond Top Level Package Error
  23. Why does this error occur?
  24. Conclusion

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,

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.

Источник

ImportError: attempted relative import with no known parent package

Table of Contents Hide

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.

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.

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

Other ways of importing modules in Python

In case of relative imports, we need to specify the module’s path relative to the current module’s location.

Example –

How to fix ImportError: attempted relative import with no known parent package?

Option 1 – Use absolute imports

For instance, the directory structure may be as follows

where setup.py is

Option 2 – Get rid of from keyword

Remove the from keyword and use the standard way of import as shown below.


Option 3 – Import inside package init file

Put this inside your package’s __init__.py file:

Assuming your package is like this:

Now use regular imports in you package, like:

Источник

ImportError: Attempted Relative Import With No Known Parent Package

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 Consists of 2 folders : myPackage1 (runCode.py) and myPackage2 (function.py).

runCode.py

function.py

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

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 .

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.

Changing the Caller Program (runCode.py)

Remove the dot from the import statement now that the package is global.

Output

ImportError: Attempted Relative Import With No Known Parent Package Unit Tests

Let’s look at the following program that deals with unit testing.

Output

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:

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

To run tests, you may pass the following command within the myModule directory

This can result in the following error:

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.

A relative import in Python specifies the content to be imported into the project, which is relative to its exact location.

__init__.py file may contain Python code that a python package would have. However, Python will add extra attributes to the package whenever imported.

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 imported
globals/locals – Determines the nature of the package.
fromlist – extra objects or submodules to be imported by the module
level – 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.

Источник

Importing modules can sometimes cause excessive failure if you are a beginner in Python. This tutorial will teach you how to import and how to resolve importError: try importing a relative without knowing the parent package.

Before getting into the solution, let’s first understand few basic terminologies in Python.

Python Module: A module is a Python file with definitions and commands. The module can contain executable commands, such as function definitions. Simply put, think of it as a .py file with some function.

Python Package: A Python package contains one or more modules and contains a file named __init__.py, which tells Python that this folder is a package. The hot file may be empty or may contain code that must be run at the beginning of the package.

imports: Imports in Python are essential for structuring your code effectively, and you can use the import keyword to import any module and reuse it efficiently. There are two types of imports, Relative and Absolute, that deal with 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

How to fix ImportError: attempted relative import with no known parent package?

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

Понравилась статья? Поделить с друзьями:
  • Importer mpeg error premiere
  • Import yaml error
  • Import validation error django
  • Import tensorflow as tf ошибка
  • Import tensorflow as tf error