Home > Blockchain >  Relative path ImportError when trying to import a shared module from a subdirectory in a script
Relative path ImportError when trying to import a shared module from a subdirectory in a script

Time:01-16

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:

  1. Add the full path to ./util/ to your PYTHONPATH environment variable.

For example on Bash, your ~/.bashrc might have export PYTHONPATH="${PYTHONPATH}:/Users/foobar/projects/advent-of-code/util/".

  1. Add sys.path.append('/path/to/application/app/folder') before the import.

The other solutions don't work because:

  1. day03 and the parent directory are not modules with their own __init__.py. Lines like from ..util import parser only work if everything involved is a module.
  2. 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.'

  • Related