0

I have a package/module structure as follows:

root/
├ aa
│ └──bb
│    └──b.py
├ cc
│ └──bb
│    └──b.py

In IPython I'm trying to import b from aa.bb like so:

import sys
sys.path.append('/path/to/root/')

from aa.bb import b

But I am getting a ModuleNotFoundError

ModuleNotFoundError: No module named 'aa.bb'

Importing just aa works, as does importing cc.bb.b:

import sys
sys.path.append('/path/to/root/')

import aa
from cc.bb import b

What might be causing the module to be ignored, and how can I debug this? I suspect this is due to some mechanism at play in my IPython setup but don't know where to look.

Ethereal
  • 2,604
  • 1
  • 20
  • 20
  • Just tried this, and it works for me. Are you sure your path is correct? What does `os.listdir(same_path_used)` give? – ParkerD Dec 17 '19 at 05:08
  • The path is correct, and the files are listed as expected. I am suspecting that there's something strange going on with my IPython setup, and I've updated the Q with a more minimal case, and it really seems that my shell is treating one particular filepath differently than another. – Ethereal Dec 17 '19 at 15:56

2 Answers2

0

have you tried using

import aa.bb.b

this has worked for me, or for a specific function in b.py you can use

from aa.bb.b import func

here is also a link to another stack overflow post about a similar topic: Importing files from different folder

  • This works (as does the methods I was employing before) with a toy example, but not with my real use case! I'd really like to learn some tools to debug this with, as I'm scratching my head about what might be causing my modules to fail importing. – Ethereal Dec 17 '19 at 05:21
0

It seems that a different aa module is being loaded on startup.

In a fresh shell you can check out the imported modules with sys.modules.keys() and find that aa is already there. You can see the source location using importlib:

importlib.util.find_spec('aa')
> ModuleSpec(name='aa', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f8f5c8dd0>, origin='/not/the/right/path/aa', submodule_search_locations=['/not/the/right/path/aa'])

You can reload the loaded module using importlib after ensuring a correct sys.path, which should load the target module:

import importlib                                                                                                                     
importlib.reload(aa)

from aa.bb import b
Ethereal
  • 2,604
  • 1
  • 20
  • 20