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.

Community
  • 1
  • 1
A.J.Rouvoet
  • 1,203
  • 1
  • 14
  • 29
  • 4
    Could you show the *actual* code being executed? – Jon Clements Dec 12 '12 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. – A.J.Rouvoet Dec 12 '12 at 15:49
  • This was my problem from messing with someone else's code.. what an obscure issue – Fosa Jan 30 '18 at 14:11

1 Answers1

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • I don't see the point of the downvote... please explain. – glglgl Dec 12 '12 at 17:25
  • 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 Dec 13 '12 at 11:03
  • @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. – glglgl Dec 13 '12 at 12:04
  • Yes I agree with you; I obviously wasn't clear enough. I undid the downvote in accordance. – A.J.Rouvoet Dec 13 '12 at 15:21