'Importing Utils in Python
I have Python 3.9.7 and I have already installed utils==1.0.1.
So now I want to import this library and trying with this command
from . import utils
But this is not working. I receive this error :
ImportError: attempted relative import with no known parent package
So can anybody help me how to solve this problem ?
Solution 1:[1]
Trying to import from a folder that is not recognised as a python package (it must have an _init_.py file to be recognised as a package) can raise this error.
If utils is a package try importing it directly like
from utils import * or
import utils
Solution 2:[2]
I think there is some confusion around utils. I think you installed a Python package via pip, i.e. pip install python-utils. If that is the case, then you need:
import python_utils
Also you should check out their quickstart for that package.
There are many reasons not to use the . methodology, but the main one here is you're not actually accessing a parent folder, you're accessing a site package that you've installed. These will always be import X.
e.g.:
pip install numpy
import numpy
And if you're curious run pip show <package> to know where it is installed. It should be under site-packages.
Solution 3:[3]
import utils
Dont use this:
from . import *anything*
In file hierarchy . means current directory and python tries to find from {file} this file in the same level, where you launched your code. You should also read info about ../ file hierarchy in unix systems to understand how python works with files.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yorgos Katsaros |
| Solution 2 | Chrispresso |
| Solution 3 |
