Search code examples
pythonpackaging

Importing a module from an upper directory within a package when the package is imported from another place


I have a project that I am having problems with.

kreveik.
|-- classes
|   |-- baseclasses.py
|   |-- family.py
|   |-- __init__.py
|   `-- network.py
|-- family
|   |-- __init__.py
|   `-- killer.py
`-- genetic
    `-- __init__.py

This is the relevant part of the project. The traceback explains me what I was trying to do in my code.

/home/mali/workspace/kreveik/<ipython-input-7-ec5770ffbdf2> in <module>()
----> 1 import kreveik

/home/mali/workspace/kreveik/kreveik/__init__.py in <module>()
----> 1 import classes
      2 import numpy as num
      3 import matplotlib.pyplot as plt
      4 import network
      5 import probes

/home/mali/workspace/kreveik/kreveik/classes/__init__.py in <module>()
      9 import copy
     10 from baseclasses import ProbeableObj,Ensemble,Element
---> 11 from network import TopologicalNetwork,Motif,Network
     12 from family import Family
     13 

/home/mali/workspace/kreveik/kreveik/classes/network.py in <module>()
      3 """
      4 
----> 5 import classes
      6 import numpy as num
      7 import matplotlib.pyplot as plt

ImportError: No module named classes

I open an interactive python session in the directory /kreveik then I try to import kreveik package, which has its init file at /kreveik/kreveik/__init__.py There, it starts to import other tools that are needed in the package, and in the package classes, I import the classes that I use the most, dreaming that I'd be able to reach them via their position in the hierarchy with respect to the folder /kreveik/kreveik/ But within the file /kreveik/kreveik/classes/network.py the call to the package classes fails, as if it is not in the topmost level on the project dir. hierarchy. I was planning to reach all of my classes referring them as classes.baseclasses.SomeClass(), independent of where I call it in the project. Where have I done wrong?

Thanks PS. I know hat there are similar entries addressing this issue, but I failed to find the one that could help me.


Solution

  • You must also reference the enclosing package when importing from a sub-package.

    In this example, in network.py, use

    from kreivik.classes import *