WodkaRHR
WodkaRHR

Reputation: 175

Python importing submodules from submodule

I have got a problem when using python imports. I wrote a finished module, that itself uses several submodules (those are imported).

e.g.

module:
   main_class.py
   submodule1.py
   ....

Now I want to use this finished module by another supermodule, so the folder structure would change like this

supermodule:
    main_class_super.py     -- this class imports module.main_class
    module:
       main_class.py
       submodule1.py
       ....

However now all imports that are used in the code of main_class.py inside the module fail (I guess because the import now works in the namespace of main_class_super.py)

Any idea how to solve this problem without restructuring the entire sources?


The concrete error:

In my main_class.py I use the line:

import submodule1

In my supermodule.py I use the line:

import module.main_class

When executing the superclass that imports module.main_class of course the import submodule1 line is executed as well, but fails as it can not find the module in the namespace of supermodule.py.

Upvotes: 3

Views: 7831

Answers (1)

janbrohl
janbrohl

Reputation: 2656

If you are on python 2 you should add from __future__ import absolute_import to your files (not needed on 3) so you can do the imports like Guido states in PEP 328

According to this you should

  • Make sure all your package folders have a __init__.py in it to mark them as importable

  • In main_class.py: replace import submodule1 or import module.submodule1 with from . import submodule1

  • In main_class_super.py: replace import module.main_class with from .module import main_class

This way you don't have to care about any outer package structure.

The option to use absolute and explicit relative imports was added in Python 2.5.

Upvotes: 5

Related Questions