1

Possible Duplicate:
How to do relative imports in Python?

I'm experiencing something that seems very random to me.

I have a folder structure much like this:

dir A
    __init__.py is empty
    a.py imports stuff and b.py
dir B
    __init__.py is empty
    b.py imports NOTHING

a.py raises an error (cannot import name b). This only happens while b is part of module B. If I move it outside the directory, the import error does NOT occur.

Any help would be appreciated. I must be overlooking something.

3
  • 4
    Could you show the actual code being executed? Commented Dec 12, 2012 at 11:52
  • B was actually called utils and I think that's the real issue here. utils is probably a python dist module and those take precedence. I've renamed the module to util which seems to have solved the problem. The weird thing is, that I had other files in the module and imported those without problems. Commented Dec 12, 2012 at 15:49
  • This was my problem from messing with someone else's code.. what an obscure issue Commented Jan 30, 2018 at 14:11

1 Answer 1

4

Did you try the relative import

from ..B import b

?


EDIT: This does not apply if it doesn't matter where package B lives.

But you don't describe what exactly you do. As you may know or not, there are several import forms:

import module
import package # imports package.__init__ under the name package
import package.module
from package import module
import package
from module import component
from package.module import component

As you only write

a.py imports stuff and b.py

I don't know what exactly happens: if you try to

import b

that fails because b lives in the package B. So you need one of

from B import b
import B.b

Your comment above mentions a name clash. Which of two equally named packages and modules have priority depends on in which directory you are: '.' is normally at the very start of sys.path, so if you are directly under your utils directory you might have a different experience than otherwise.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't see the point of the downvote... please explain.
It was already suggested that my question is a duplicate of a 'relative import' question. It is now CLOSED as a duplicate. But it's not. Since I'm not trying to accomplish a relative import but an absolute one, and I wanted to know why THAT didn't work. But thank you for taking a shot ;-)
@A.J.Rouvoet But it sounded like a "relative" problem, and obviously not only to me. Maybe it is a problem of wording in the question.
Yes I agree with you; I obviously wasn't clear enough. I undid the downvote in accordance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.