I am trying to import a util package one directory up from where my code is, but I get an ImportError which I don't understand.
I have a number of different variations on the import syntax in Python, none of which are working.
There are a number of similar questions on Stack Overflow, but none have helped me understand or fix this issue.
Of the top of my head, I have tried the following variations:
import util
import ..util
from .. import util
from ..util import parser
from AdventOfCode2022 import util
from ..AdventOfCode2022 import util
from ...AdventOfCode2022 import util
Most of these I guessed wouldn't work, but I tried them anyway to be sure.
Error message:
ImportError: attempted relative import with no known parent package
Directory structure:
.
├── day03
│ ├── input.txt
│ ├── part1.py
│ ├── part2.py
│ └── test_input.txt
└── util
├── __init__.py
└── parser.py
I just want to import my util package from any "day0*/" directory - not sure why Python makes it so hard!
CodePudding user response:
Why can't you just go? from util import parser
and call whatever function you need?
Should work.
CodePudding user response:
You have to do
from util import parser
because the util directory is in the same location as day03 where as from ..util import parser
is trying to import the parser from ../util which is in the parent directory of day03.
and then parser.X
to access different objects in that file.
CodePudding user response:
Two options:
- Add the full path to
./util/
to yourPYTHONPATH
environment variable.
For example on Bash, your ~/.bashrc
might have export PYTHONPATH="${PYTHONPATH}:/Users/foobar/projects/advent-of-code/util/"
.
- Add
sys.path.append('/path/to/application/app/folder')
before the import.
The other solutions don't work because:
day03
and the parent directory are not modules with their own__init__.py
. Lines likefrom ..util import parser
only work if everything involved is a module.- You are presumably running the code from within
./day03/
.
View this as 'I have a bunch of independent Python projects (day01
, day02
etc) that all want to share a common piece of code I have living in a different project (util
) that lives somewhere else on my computer.'