0

This has been asked before, but none of the solutions are yielding any results. I have a parent directory with

parent/
    __init__.py
    database.py
    collect/
        __init__.py
        collect.py

I would like to import database.py from collect.py but I constantly get ValueError: Attempted relative import in non-package. Currently in collect.py I am just doing

import sys
sys.path.append("..")
import database

which does not feel very pythonic. I would like to have something like

from .. import database

Yet I always get that ValueError. Any help is appreciated. What exactly is causing this error. I thought adding __init__.py would fix the issue, but it changed nothing. Also, is there anything wrong with my current fix? It doesn't feel like the best solution to me.

Edit: I should add that I cannot successfully import from ipython running in collect/ either, if that affects anything.

Shatnerz
  • 2,353
  • 3
  • 27
  • 43
  • That is a fantastic explanation. Thanks. I see where the issue lies now. Is using `sys.path.append("..")` bad practice though? I will end up refactoring so I do not need it, but I am still curious. – Shatnerz Apr 19 '16 at 15:30
  • I would not say it is bad practice but you have to be aware of what this means, i.e. "ultimately if all the possible directories do not contain a module of that name, have a look in the parent directory of this file". If a module named database was found before yours it would be loaded first. – Jacques Gaudin Apr 19 '16 at 15:49

0 Answers0