2

Below is the structure of my project:

Python_Projects/
        └── project_1/
            ├── __init__.py
            ├── my_functions.py
            ├── test.py
            └── sub_folder_add/
                └── add.py

code in add.py:

from .my_functions import addition

While running code.py am getting error:

ImportError: attempted relative import with no known parent package

namo
  • 51
  • 1
  • 3
  • 9

3 Answers3

2

As documentation says:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

So you're not supposed to use relative imports when running your script as the main module. Relative imports get resolved correctly when they get imported.

The simplest fix is:

  1. Be sure that your root folder is in sys.path so that interpreter always finds it. (If not, append it manually)
  2. Use absolute imports start from the root folder.

This way you lose portability of your sub-module/sub-packages but your imports work as expected no matter you run your sub-modules directly or not.

By losing portability, I mean if you decide to change the location of a sub package, you need to change all the imports in side that package even if the sob-modules point to each other inside that package.

S.B
  • 13,077
  • 10
  • 22
  • 49
  • so I need to import like:- `from d:/folder/Python_Projects/project_1/my_functions import addition` – namo Aug 21 '22 at 12:52
  • @namo No. Take a look at : https://stackoverflow.com/q/22678919/13944524. Relative imports start with `.`, absolute import don't. – S.B Aug 21 '22 at 12:53
0

If you don't want to use absolute imports, in the worst case, you can hack your way around using the lower-level importlib library:

import importlib
addition = importlib.import_module('my_functions').addition
0

In order to use relative imports, you have to have a package. In this example I think 'project_1' folder is the best candidate to be the top level package folder. Make a __init__.py inside 'project_1' folder (you've already done) and put the following code inside it to make it the top level folder in the package:

__package__ = ''

Now you can use relative imports. In add.py you can access my_functions module in this way:

from ..my_functions import addition
Megacodist
  • 132
  • 5