0

I have a problem with importing sub-packages. The packages structure I have is:

project/
    __init__.py
    defaults.py
    helpers/
       __init__.py
       misc.py

I need to use data from defaults.py all over the project, including helpers\misc.py, while in defaults.py I need to use some functions from helpers\misc.py. To solve the circular reference I'm trying to refer everything from project root, i.e. inside defaults.py I do

import project

project.helpers.somefunction()

However this doesn't work. It does work though when I import the function directly, like this:

from project.helpers import somefunction

somefunction()

But then I have a circular reference problem. I also have same problem everywhere inside the project subpackages, but in other places I can import subpackages directly and workaround the problem.

So, why it works if I import from subpackages, but doesn't when I refer to same subpackages starting from the root package?

PS: there are no files like helpers.py on the same level with helpers\ or inside it.

PPS: whole project package is added to sys.path via sys.path.insert(0, '<project_abs_path>')

PPPS: Python 2.7.3, Ubuntu 12.04

1 Answer 1

1
import project.helpers

project.helpers.somefunction()
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain why this helps?
@Ophion when you import a package this executes the code in __init__.py. Period. It does not import subpackages. If you want to automatically import subpackages then you have to do so in the __init__.py of the package. A package is just like any other module. The only difference is its layout in the file-system(using name/__init__.py instead of name.py) and the ability to do relative imports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.