Search code examples
python-3.xpython-importimporterror

Can't import relative module


The file structure for a module im creating goes as follows:

PIV
| __init__.py
| base.py
| core.py
| exceptions.py
.gitignore
LICENSE
requirements.txt

But whenever I run a file like core.py, I get the following error:

Traceback (most recent call last):
  File "c:/Users/ghub4/OneDrive/Desktop/Python-Image-and-Video-tools/PIV/core.py", line 33, in <module>
    from . import base
ImportError: attempted relative import with no known parent package

The same thing happens when I run the __init__.py file. I'm not sure on what went wrong because all of the python files are in the same folder. Can someone clarify what's the problem and explain how I should fix it?

Import code for core.py file:

from __future__ import absolute_import
import sys
import os
from PIL import Image
import io
from . import base
from . import exceptions

(The __init__.py folder has the same relative imports as in the core file but also including: from . import core)


Solution

  • Based upon the two links you will given below, here is what needed for the problem to solve:

    You need to import the package as this

    from mymodule import some_useful_method
    

    Sometimes, we get the no module error, in this case, we can import like this

    from module_name.classname import some_useful_method